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
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742342201a4425851.html
评论列表(0条)