Get value from text area

JavascriptHtmlJqueryTextarea

Javascript Problem Overview


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);
    }
  
});

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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/

Solution 3 - Javascript

$('textarea').val();

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

Solution 4 - Javascript

use the val() method:

$(document).ready(function () {
    var j = $("textarea");
    if (j.val().length > 0) {
        alert(j.val());
    }
});

Solution 5 - Javascript

You need to be using .val() not .value

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

Solution 6 - Javascript

Use val():

 if ($("textarea").val()!== "") {
        alert($("textarea").val());
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2077469View Question on Stackoverflow
Solution 1 - JavascriptMars RobertsonView Answer on Stackoverflow
Solution 2 - JavascriptMuthu KumaranView Answer on Stackoverflow
Solution 3 - JavascriptJames DonnellyView Answer on Stackoverflow
Solution 4 - JavascriptsillyView Answer on Stackoverflow
Solution 5 - JavascriptSanchitView Answer on Stackoverflow
Solution 6 - JavascriptZaheer AhmedView Answer on Stackoverflow