April 26, 2012

Function fails when called by other function

Question by Mark Hollas

fairly new to jQuery so bear with me.

I am having trouble getting the results of one function over to another an executing it.

Then the point is to pass the text as a var to the function populateMessage() and it writes the text to a text box.

I can get the text and it does get passed to the populateMessage function but the function never fully executes and the text box is not populated. If I wrap the populateMessage function in document.ready and have it write something like .text(‘test’); it will work.

How can I make this work?

Thanks for the help

$(document).ready(function () {
    getClickedInvite();
});

//gets clicked item template and sends it to message box

function getClickedInvite() {
    $('.card').click(function () {
        var selectedMessage = $(this).text();
        alert(selectedMessage);
        populateMessage(selectedMessage);
    });
}

function populateMessage(selectedMessage) { 
    alert(selectedMessage + ' has been sent to the message box ')
    var inviteMessageBoxId = $('#inviteMessageBox').find('textarea').attr('id');
    alert(inviteMessageBoxId);
    $('#' + inviteMessageBoxId).text(selectedMessage);
}

Answer by Starx

There is no need to extend the function like that. And if you read the manual, it says

Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.

SO .find() always does not return a single element.

$('#inviteMessageBox').find('textarea')[0].text(selectedMessage);

Or, if getting id is really that necessary then

var id = $('#inviteMessageBox').find('textarea')[0].attr('id');
$("#"+id").text(selectedMessage);

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!