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?
Use the value property to get the value of a textarea, e.g. const value = textarea. value . The value property can be used to read and set the value of a textarea element. If the textarea is empty, an empty string is returned.
Answer: Use the jQuery val() Method You can simply use the val() method to set the value of a textarea dynamically using jQuery.
Complete HTML/CSS Course 2022Use the <textarea> tag to show a text area. The HTML <textarea> tag is used within a form to declare a textarea element - a control that allows the user to input text over multiple rows. Specifies that on page load the text area should automatically get focus.
.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);
});
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With