Thursday, 6 August 2015

Avoid spaces being submitted in the script using jQuery

Leave a Comment

When we create any application using textfields it is possible that user may click on the submit button without entering any values in the textfield. We can restrict this easily simply by using if condition and double quotes like.

var name = $("#textfield").val();
if(name == ""){
alert("Please enter text in the text box");
}

But what if user presses spacebar a couple of times in the textfield and submits. This time the above code does not work. It will not alert the message instead it considers it as a value and executes the rest of the script. In this case we will get a null value submitted.


To stop user from entering null values ie spaces and submitting the form. We can trim the value first. That is we will remove the empty spaces. It can be done using jQuery trim statement.

var name = $("#textfield").val();
if($.trim(name) == ""){
alert("Please enter text in the text box");
}

Now the value gets trimmed and null values are avoided.

0 comments:

Post a Comment

.