Tuesday, 27 August 2013

Validate multiple inputs with AJAX/JQUERY and change css of wrong inputs only

Validate multiple inputs with AJAX/JQUERY and change css of wrong inputs only

I have a form which has multiple inputs with the same name and brackets like:
<input name=foo[] id=foo[]/>
I'm using the brackets to process the input as array with PHP and because
the amount of inputs is not fixed.
I'm trying to add some form validation with AJAX/JQUERY because each input
must contain a value that's already in the database. Once checked I want
to change the CSS of the input to green if correct and red if wrong.
The AJAX part is working but I can't get JQUERY to change the CSS of the
inputs.
Here's the code I'm using:
<script>
$(document).change(function(){
$('input[id="foo[]"]').each(function(){
$(this).change(validate);
});
});
function validate(){
var foo = $(this).val();
if(foo == "" || foo.length < 4){
$('input[id="foo[]"]').css('border', '3px #C33 solid');
}else{
jQuery.ajax({
type: "POST",
url: "common/check.php",
data: 'foo='+ foo,
cache: false,
success: function(response){
if(response == 0){
$('input[id="foo[]"]').css('border', '3px #C33 solid');
}else{
$('input[id="foo[]"]').css('border', '3px #00FF00 solid');
}
}
});
}
}
</script>
Thanks for your help!

No comments:

Post a Comment