11

I am submitting a form using JQuery. The form looks like below

<form class="ask-more-form">
<div class="product_info_2">
<textarea name="product_question" class="textbox" placeholder="Ask You Question Here"></textarea>
</div>
<input type="hidden" name="product_id" value="1" id="product_id">
<a href="#" class="whiteButton submit" id="ask-more-submit-button">Ask Question</a>
</form>

And the JQuery to catch the form looks like this:

$('#ask-more').on('submit', '.ask-more-form', function() {
        var product_id = $(this).children('input[name=product_id]').val();
        var product_question = $(this).children('textarea[name="product_question"]').text();

alert(product_question);
//submitQuestion(product_id, product_question);

                });

The product_id is always read but the product question is is always null. Can anyone tell me why this is happening?

4 Answers 4

17

.children only goes one level down. Use .find instead:

$('#ask-more').on('submit', '.ask-more-form', function () {
    var product_id = $(this).children('input[name=product_id]').val();
    var product_question = $(this).find('textarea[name="product_question"]').text();
    alert(product_question);
    //submitQuestion(product_id, product_question);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Is a combination of using val() and find
Personally, I would use .val(), but .text() will work for a textarea. See jsfiddle.net/kfD7b for a demo.
4

You're using text() on a <textarea> when you should be using val()

var product_question = $(this).children('textarea[name="product_question"]').val();

This is true for other input element types like <select> and <input>

1 Comment

Should be noted that all elements designed for input, such as input, textarea, and select should be accessed using val(). This is one of the things that makes jQuery awesome.
0

Use .val() instead of .text(). It will do the trick

1 Comment

Maybe explain the difference between .val() and .text() like here.
0

You don't need to use children or find. Since you already have the id of the form you can use that for your base and just use a standard jquery selector like so:

var product_question = $('textarea[name="product_question"]', this).val();

by adding a seocnd argument you are telling jquery to use only this as the DOM tree.

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.