Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value from text area [duplicate]

How to get value from the textarea field when it's not equal "".

I tried this code, but when I enter text into textarea the alert() isn't works. How to fix it?

<textarea name="textarea" placeholder="Enter the text..."></textarea>

$(document).ready(function () {
    if ($("textarea").value !== "") {
        alert($("textarea").value);
    }

});
like image 806
user2077469 Avatar asked Feb 18 '13 14:02

user2077469


People also ask

How to get data From textarea in JavaScript?

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.

Does textarea have value attribute?

<textarea> does not support the value attribute.

How do I get input from text area?

We can get the value of textarea in jQuery with the help of val() method . The val() method is used to get the values from the elements such as textarea, input and select. This method simply returns or sets the value attribute of the selected elements and is mostly used with the form elements.

What property would you use to get the text that has been entered into a textarea?

The value property sets or returns the contents of a text area.


3 Answers

Vanilla JS

document.getElementById("textareaID").value

jQuery

$("#textareaID").val()

Cannot do the other way round (it's always good to know what you're doing)

document.getElementById("textareaID").value() // --> TypeError: Property 'value' of object #<HTMLTextAreaElement> is not a function

jQuery:

$("#textareaID").value // --> undefined
like image 85
Mars Robertson Avatar answered Oct 16 '22 10:10

Mars Robertson


Use .val() to get value of textarea and use $.trim() to empty spaces.

$(document).ready(function () {
    if ($.trim($("textarea").val()) != "") {
        alert($("textarea").val());
    }
});

Or, Here's what I would do for clean code,

$(document).ready(function () {
    var val = $.trim($("textarea").val());
    if (val != "") {
        alert(val);
    }
});

Demo: http://jsfiddle.net/jVUsZ/

like image 25
Muthu Kumaran Avatar answered Oct 16 '22 08:10

Muthu Kumaran


$('textarea').val();

textarea.value would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value).

like image 1
James Donnelly Avatar answered Oct 16 '22 10:10

James Donnelly