1

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.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

2 Answers 2

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
}
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you mr.Gaby but I'd Like to know what this mean '$'?
$ is the jQuery library object. (You are already using it)
i Know that if i need select element I using $('CSS Selector') :) :) But I Don't Know what is the difference between $ and $('')
@MoHamedHaSsn exactly. And jquery provides a method named trim that removes leading/trailing spaces from a string. To call that you use $.trim( <string here> )
Thank you for helping me MR.Gaby
1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.