2

Can anyone tell me why the scope of $mytextarea, in the code below, doesn't extend into the getAnswerToo() function?

getAnswer() works because I'm explicitly selecting the element I want updated. However, trying to use a global 'handler' variable doesn't work.

I'm assuming that this problem with the scope of the variable is specifically related to the fact that it holds a jQuery object. The other variable, myurl, works fine.

Any help much appreciated!

var myurl = "php/getAnswer.php";

var $mytextarea = null;  //  a handler for the textarea element
$mytextarea = $('textarea#mytextarea');

getAnswerToo();

    function getAnswer(){ // works

        var request = $.ajax({
          url: myurl,
          type: "POST",
          data: {question: questionId, user: userId},
          dataType: "html",
          success: function(data) {
            $('textarea#mytextarea').val(unescape(data));
          }
        });

    }

    function getAnswerToo(){ // doesn't work

        var request = $.ajax({
          url: myurl,
          type: "POST",
          data: {question: questionId, user: userId},
          dataType: "html",
          success: function(data) {
            $mytextarea.val(unescape(data));
          }
        });

    }
1
  • Thank you to both Aktee and Amareswar - of course! It's makes complete sense when you remember that jQuery selectors can only reference an object after the DOM has initialized. I'd stupidly put my code outside of the document ready function. Commented Oct 12, 2012 at 9:04

2 Answers 2

1

Where is this placed?

$mytextarea = $('textarea#mytextarea');

Selector works when your DOM is initialized. This should work:

$(function() {     
   $mytextarea = $('textarea#mytextarea'); 
   getAnswerToo();
});
Sign up to request clarification or add additional context in comments.

Comments

1

$('textarea#mytextarea') returns empty array as the DOM is not initialized yet. Wrap entire code with in code block while will be invoked after DOM is ready.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.