Reputation:
I have a question about how I can shorten a Jquery if statement. In my form I have several fields that I check if they are filled. I know there are several plugins to do that for me, but I wan't to learn it by myself (with some help of others ;-))
I got this check
//---- First define hasError
var hasError = false;
//---- Get the value from the inputfield
var firstname = $('#firstname').val();
//---- Do the check
if(firstname == ''){
$("#error_firstname").show();
hasError = true;
}else{
$("#error_firstname").hide();
}
I thought I could write it like this:
(firstname == '') ? $(".firstname").show(): $(".firstname").hide();
And this works, but I can't put the hasError=true in it, so I can't ask this in the end
if(hasError != false) {
//---- if error, don't refresh page and show errors
return false;
}else{
//---- Save values to DB and show succes message
}
Anybody got an idea?
Tnx in advance
Grtzz
Wim
Upvotes: 2
Views: 1161
Reputation: 7781
You can set callback for jQuery show()
and hide()
methods:
(firstname == '') ? $(".firstname").show(function(){ hasError = true; }): $(".firstname").hide();
Upvotes: 0
Reputation: 1109132
To start, refactor it to a function so that you can reuse it for all fields.
Example:
function check(fieldname) {
var value = $('#' + fieldname).val();
var error = $('#error_' + fieldname);
if (value == '') {
error.show();
$.hasError = true;
} else {
error.hide();
}
}
so that you can use it as follows:
check('firstname');
check('lastname');
// etc..
Of course you can refactor that again further by storing all names in an array or just by getting $(':input')
and calling check()
in a loop. You keep busy refactoring ;) You can eventually take a look how existing form validation plugins do it. For example the jQuery Validator.
Whole point is: don't duplicate code. Refactor it.
Upvotes: 8
Reputation: 25810
Well, I would have recommend you to use JQuery Validation plugin but I'll take it that you want to learn it the 'hard' way. :P
Have the error messages adopt the same class e.g. "error"
<span class="error" id="err_firstname">...</span>
<span class="error" id="err_lastname">...</span>
<span class="error" id="err_email">...</span>
If any of the span.error:visible
has at least one item, then hasError = true
$("span.error:visible").each(function (i) {
hasError = true;
return;
});
The hasError flag check can be shortened too:
if(hasError) {
//---- if error, don't refresh page and show errors
return false;
}
else {
//---- Save values to DB and show succes message
}
Upvotes: 0