简体   繁体   English

为什么此事件总是触发?

[英]Why does this event always fire?

I'm building a easy chat app with html/css and javascript, and mongoDB. 我正在使用html / css和javascript和mongoDB构建一个简单的聊天应用程序。 The application works great but i want to add a check that checks if the value of name is not empty. 该应用程序工作正常,但我想添加一个检查,以检查name的值是否不为空。 I think the code is correct, but it always fire. 我认为代码是正确的,但是它总是会触发。

This is the html code related to the problem. 这是与问题相关的html代码。

<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. 这是执行检查的JavaScript,始终会触发。

$("#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. :empty (和empty() )旨在指示该元素没有子元素。 In your case you want to know if the element has no value , so it's not applicable. 在您的情况下,您想知道元素是否没有value ,因此它不适用。

Instead get the value using val() and test its length . 而是使用val()获取值并测试其length You can also trim() it to ensure it wasn't just filled with whitespace. 您还可以trim()以确保它不只是被空格填充。

 $("#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. 或者,您可以将字段与提交按钮一起放在form ,并使用required属性,并不需要进行显式JS验证。 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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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