2

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 ?

Nope
  • 22,147
  • 7
  • 47
  • 72
Jeniapus
  • 33
  • 4

2 Answers2

0

if ($(textarae #msg).val() == '' || $(textarae #msg).val() == null)

Biplab Malakar
  • 750
  • 6
  • 11
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Jun 20 '17 at 15:16
-1

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

    });
Bri
  • 573
  • 1
  • 5
  • 23