首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >检查输入是否为空JQuery

检查输入是否为空JQuery
EN

Stack Overflow用户
提问于 2017-03-12 18:51:07
回答 2查看 7.4K关注 0票数 1

Hello,我的代码中有简单的问题,我把自己作为一个用户,让我们假设如果用户单击空格按钮(在键盘上),那么解决方案是什么。

这里我的简单代码:

代码语言:javascript
复制
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
}
代码语言:javascript
复制
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-03-12 18:53:43

使用$.trim函数移除空格

代码语言:javascript
复制
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
}
票数 5
EN

Stack Overflow用户

发布于 2017-03-12 18:53:51

.trim函数在JavaScript中删除前导和尾随空格/新行。因此,如果用户只是垃圾邮件栏,name.trim()将删除所有前导/尾随空格,从而产生"“和”等于“。因此,您的错误代码将显示。

代码语言:javascript
复制
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
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42751647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档