Jeniapus Jeniapus - 1 year ago 56
jQuery Question

checking if text field is empty via jquery

I have the following Code

$('#myform').submit(function() {
return false;

$('#insert').click(function() {
var value = $.trim($("#msg").val());
if (value.length < 0) {
alert("לא הכנסת הודעה !");
} else {
$('#myform :input').serializeArray(),
function(result) {
document.getElementById('msg').value = "";

<form method="post" action="insertmsg.php" id="myform">
<td width="100%">
<textarea class="form-control" placeholder="ההודעה שלך" name="msg" id="msg"></textarea>
<button id='insert' class="form-control">שלח</button>

<p id='result'></p>

I'm unable to check if the field is empty or not. I tried something but it doesn't work.

Any suggestions ?

Bri Bri
Answer Source

Get the value of the textarea and check to see if there is a value. You can also use required="required" if you want to use the browser check.

<textarea class="form-control" placeholder="ההודעה שלך" name="msg" id="msg" required="required"></textarea>

$('#insert').click(function () {
        var textField = $('#myform').find('textarea#msg'); // Or give textarea an id and find that. 
        var textFieldValue = textField.val();
        if (textFieldValue.trim() == '') return;

            function (result) {
                document.getElementById('msg').value = ""; // this part only clears the textarea after submission .

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download