简体   繁体   English

检查输入是否为空JQuery

[英]Check If Input is empty JQuery

Hello , There are simple problem in my code, I've put myself as a user, let's assume that if the user click on the space button (in keyboard), So What is the solution. 您好 ,我的代码中有一个简单的问题,我已经将自己设置为用户,我们假设如果用户单击空格键(在键盘上),那么解决方案是什么。

Here my simple code: 这是我的简单代码:

 var name = $('input#name').val(); // get the value of the input field if(name == "" || name == " ") { $('#err-name').fadeIn('slow'); // show the error message error = true; // change the error state to true } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 

Use the $.trim function to remove spaces 使用$.trim函数删除空格

var name = $.trim( $('input#name').val() ); // get the value of the input field
if(name == "") {
    $('#err-name').fadeIn('slow'); // show the error message
    error = true; // change the error state to true
}

The .trim function in JavaScript removes leading and trailing spaces/new lines. JavaScript中的.trim函数可删除开头和结尾的空格/换行符。 So, if the user just spams space bar, the name.trim() will remove all leading/trailing spaces, resulting in "" and that equals "". 因此,如果用户只是向垃圾邮件发送垃圾邮件,则name.trim()将删除所有前导/后跟空格,结果为“”,并且等于“”。 Thus, your error code would show. 这样,您的错误代码就会显示出来。

var name = $('input#name').val(); // get the value of the input field
if(name.trim() == "") {
    $('#err-name').fadeIn('slow'); // show the error message
    error = true; // change the error state to true
}

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

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