Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting TextArea Using JQuery

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?

like image 891
Devin Dixon Avatar asked Mar 03 '12 17:03

Devin Dixon


People also ask

How do I get textarea?

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.

How to set textarea value by jQuery?

Answer: Use the jQuery val() Method You can simply use the val() method to set the value of a textarea dynamically using jQuery.

How do I display HTML content in textarea?

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.


2 Answers

.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);
});
like image 174
pete Avatar answered Oct 05 '22 23:10

pete


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>

like image 43
JaredPar Avatar answered Oct 05 '22 23:10

JaredPar