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

本文标签: javascriptCheck If Input is empty JQueryStack Overflow