Jeniapus Jeniapus - 4 months ago 11
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 {
$.post(
$('#myform').attr('action'),
$('#myform :input').serializeArray(),
function(result) {
document.getElementById('msg').value = "";
$('#result').html(result);
}
);
}
});


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

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


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;

        $.post(
            $('#myform').attr('action'),
            $('#myform:input').serializeArray(),
            function (result) {
                document.getElementById('msg').value = ""; // this part only clears the textarea after submission .
                $('#result').html(result);
            }
        );

    });