javascript - Check If Input is empty JQuery - Stack Overflow

Hello, There are simple problem in my code, I've put myself as a user, let's assume that if t

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
Add a ment  | 

2 Answers 2

Reset to default 5

Use 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
}

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742342201a4425851.html

相关推荐

  • javascript - Check If Input is empty JQuery - Stack Overflow

    Hello, There are simple problem in my code, I've put myself as a user, let's assume that if t

    4小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信