AnApprentice
AnApprentice

Reputation: 110960

jQuery for getting a Textarea's Input

I have the following:

textareaID = 'comment_content_300'
textareaValue = $('#' + textareaID).val();

What I can't figure out is, sometimes this works sometimes it doesn't. It does work when the page loads with the form that uses the above.

It does not work when the site is loaded, and an ajax load injects the commenting form that uses the above, it returns nothing, blank, not unidentified, just blank.

Any ideas?

UPDATING WITH CODE

JS

$('.new_comment').live('submit', function() {

    textareaID = $(this).find('textarea').attr('id');
    commentableID = textareaID.replace('comment_content_', '');
    textareaValue = $('#' + textareaID).val();
    textareaValue = jQuery.trim(textareaValue);
    .
    .
console.log(textareaValue); 

returns empty

    ajax call doesn't happen until down here

HTML

<div class="write-comment">
 <textarea class="comment_content_bigbox" cols="40" id="comment_content_297" name="comment[content]" placeholder="Write your reply here..." rows="20" style="color: black; ">
 </textarea>
</div>

Upvotes: 0

Views: 984

Answers (1)

user113716
user113716

Reputation: 322492

Can't tell for sure without seeing more code, but I'd guess that instead of calling this code in the callback to the AJAX request, you're calling it after the request.

If that's right, then this is because the code that comes after the request does not wait for the response before it executes. That's why $.ajax() allows callback functions.

Something like:

var textareaID, textareaValue;

$.ajax({
    url: 'someurl',
    success: function(d) {
        $('body').append(d);
        textareaID = 'comment_content_300';
        textareaValue = $('#' + textareaID).val();
    }
});

EDIT: Issue was with duplicate IDs.

Upvotes: 1

Related Questions