简体   繁体   中英

Why does this event always fire?

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> 

Alternatively you could put the fields in a form , along with a submit button, and use the required attribute and negate the need for the explicit JS validation. This has the added benefit that pressing return in the textbox will not also send the value as it submits the form.

 $("form").on('submit', (e) => { e.preventDefault(); 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> <form> <input id="name" class="form-control" placeholder="Name" required="true" /> <textarea id="message" class="form-control" placeholder="Message" required="true"></textarea> <button type="submit" class="btn btn-success" id="send">Send</button> </form> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM