Reputation: 45
I have a field in my HTML, and I want to check its size and value against certain validation rules. Here is the jQuery code:
$(function(){
$('#id_title').keyup(function() {
data = $(this).val();
if (data == " ") {
$('#output').text("The title can not be spaces");
$('#SubmitAction').attr("disabled", true);
} else {
if (data.length < 5) {
$('#output').text("The title can not be shorter than 5 characters");
$('#SubmitAction').attr("disabled", true);
} else {
if (data.length > 30) {
$('#output').text("The title can not exceed 30 characters");
$('#SubmitAction').attr("disabled", true);
}
}
}
data = $(this).val();
});
});
The thing is, when it gets into any of the if blocks, it keeps stuck even if the user completed the info properly.
Upvotes: 2
Views: 168
Reputation: 144699
disabled
is a property, for modifying properties you should use prop
method instead of attr
. Instead of using empty characters, you can use jQuery $.trim
utility function and check the length of the value.
$('#id_title').keyup(function() {
var val = $.trim(this.value),
error = '';
if ( val.length === 0 ) {
error = "The title can not be empty");
} else if ( val.length < 5 || val.length > 30 ) {
error = "The title can not be shorter than 5 characters and exceed 30 characters";
}
$('#output').text(error);
$('#SubmitAction').prop("disabled", error.length);
});
Note that validating text inputs on keyup is not user-friendly, user enters a character and on the first keyup
event you are showing an error . I would suggest using blur
event instead.
Upvotes: 1
Reputation: 2129
in first use var
for your variable, var data = $(this).val();
to be local. and then you should set disabled
to false
when user completed the info properly something like this:
$(function(){
$('#id_title').keyup(function(){
data = $(this).val();
if( data == " "){
$('#output').text("The title can not be spaces");
$('#SubmitAction').attr("disabled", true);
}
else {
if(data.length < 5){
$('#output').text("The title can not be shorter than 5 characters");
$('#SubmitAction').attr("disabled", true);
}
else{
if(data.length > 30){
$('#output').text("The title can not exceed 30 characters");
$('#SubmitAction').attr("disabled", true);
}else{
$('#SubmitAction').attr("disabled", false);
}
}
}
data = $(this).val();
});
});
Upvotes: 0
Reputation: 15885
You need to set the input field again enable after it was disabled for any if functions
$(function(){
$('#id_title').keyup(function(){
var data = $(this).val();
if( data == " "){
$('#output').text("The title can not be spaces");
$('#SubmitAction').attr("disabled", true);
}
else {
if(data.length < 5){
$('#output').text("The title can not be shorter than 5 characters");
$('#SubmitAction').attr("disabled", true);
}
else{
if(data.length > 30){
$('#output').text("The title can not exceed 30 characters");
$('#SubmitAction').attr("disabled", true);
} else $('#SubmitAction').attr("disabled", false);
}
}
data = $(this).val();
});
});
Upvotes: 0