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);
}
});
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.
<textarea> does not support the value attribute.
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.
The value property sets or returns the contents of a text area.
document.getElementById("textareaID").value
$("#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
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/
$('textarea').val();
textarea.value
would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value
).
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