admin管理员组文章数量:1336645
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=".11.1/jquery.min.js"></script>
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./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Share
Improve this question
asked Mar 12, 2017 at 18:51
MoHamed HaSsnMoHamed HaSsn
5551 gold badge7 silver badges21 bronze badges
2 Answers
Reset to default 5Use the $.trim
function to remove spaces
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. So, if the user just spams space bar, the name.trim() will remove all leading/trailing spaces, resulting in "" and that equals "". 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
}
本文标签: javascriptCheck If Input is empty JQueryStack Overflow
版权声明:本文标题:javascript - Check If Input is empty JQuery - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742342201a2456827.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论