This is the first time I've tried to do data validation with Javascript and jQuery.
My array with errors is getting filled fine, but my problem is checking if this array is empty. In my situation it's always true. It will always alert me "errors leeg", even if the array is empty, checked with console.log(error):
<script type="text/javascript">
$(document).ready(function ()
{
var error = [];
$('#contactformulier').submit(function() {
if($('input#namet').val().length == 0) {
error['naam'] = 'Geen geldige naam ingevuld';
} else{
delete error['naam'];
}
if($('input#mailt').val().length == 0){
error['mail'] = 'Geen geldig e-mailadres ingevuld';
} else{
delete error['mail'];
}
if($('textarea#message').val().length == 0){
error['bericht'] = 'Geen geldig bericht ingevuld';
} else{
delete error['bericht'];
}
console.log(error);
if (error.length < 1) {
alert('errors leeg');
}
return false;
});
});
</script>
Any suggestions?
error['naam']assigns a property on the array object, it does not put any elements in the array.error[0] = "foo";do? It adds a property to the array with the key "1" and value "foo". Arrays are Objects. Only when using numbers as the key does it affect thelengthproperty.lengthproperty and therefore a regularforloop can't be used as well. But the elements are still "in" the array, you just have to access it in a different way. I think it's obvious things were mixed up in the OP