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?

sinemetu1
  • 1,726
  • 1
  • 13
  • 24
Devin Dixon
  • 11,553
  • 24
  • 86
  • 167

4 Answers4

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);
});
pete
  • 24,141
  • 4
  • 37
  • 51
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>

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • 1
    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. –  Mar 03 '12 at 17:29
0

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

Kunal Vashist
  • 2,380
  • 6
  • 30
  • 59
  • Maybe explain the difference between `.val()` and `.text()` like [here](http://stackoverflow.com/a/807908/1183294). – sinemetu1 Mar 04 '12 at 06:14
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.

Brombomb
  • 6,988
  • 4
  • 38
  • 57