Reputation: 939
I want to bind following code in custom function and return true if field has value and false if field is empty. Validating with only one variable, it was easy. But when validating two array I think it can be possible only custom function. I think code becomes unnecessarily lengthy as well because of lack of custom function. Please guide me.
$(document).on('click', '.subadd', function(){
//I want to bind this code in function
var sid = [];
$('input[name="sid[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
sid.push(this.value);
}
});
var title = [];
$('input[name="title[]"]').each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
};
if($(this).val()){
$(this).removeClass('border1red');
title.push(this.value);
}
});
//function
//if function return true
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};
});
Upvotes: 0
Views: 213
Reputation: 2262
First you can shorten your each
loop.
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
title.push(this.value);
}
You can also make a function for that, with the selector and the array as parameters.
$.validate = function(selector, array) {
$(selector).each(function(){
if(!$(this).val()){
$(this).addClass('border1red');
return false;
} else {
$(this).removeClass('border1red');
array.push(this.value);
}
}
}
In the end, the main section of the code would look like this:
var sid = [];
var title = [];
$.validate('input[name="sid[]"]', sid);
$.validate('input[name="title[]"]', title);
if(sid.length && title.length){
$('table#menutable tr:last').after("<tr>.....</tr>");
};
Upvotes: 1