LaVOZs

The World’s Largest Online Community for Developers

'; javascript - Why does this event always fire? - LavOzs.Com

I'm building a easy chat app with html/css and javascript, and mongoDB. The application works great but i want to add a check that checks if the value of name is not empty. I think the code is correct, but it always fire.

This is the html code related to the problem.

<input id="name" class="form-control" placeholder="Name">

<textarea id="message" class="form-control" placeholder="Message"></textarea>

<button type="button" class="btn btn-success" id="send">Send</button> 

This is the javascript that does the check, wich always fires.

$("#send").click(() => {
    if ($('#name').is(':empty')){
        alert("Name cant be empty");
    } else {
        var message = {name: $("#name").val(), message: $("#message").val()}
        postMessage(message)
    }
})

:empty (and empty()) are intended to indicate that the element has no children. In your case you want to know if the element has no value, so it's not applicable.

Instead get the value using val() and test its length. You can also trim() it to ensure it wasn't just filled with whitespace.

$("#send").click(() => {
  if ($('#name').val().trim().length == 0) {
    alert("Name cant be empty");
  } else {
    var message = {
      name: $("#name").val(),
      message: $("#message").val()
    }
    postMessage(message)
  }
});

function postMessage(message) {
  console.log(message);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="name" class="form-control" placeholder="Name">
<textarea id="message" class="form-control" placeholder="Message"></textarea>
<button type="button" class="btn btn-success" id="send">Send</button>