I have a form with 4 input (can be even many more) where the user can put a number or nothing. The only rule is that if you put a number in a input you cannot submit if the same number is in another input (no duplicates). You can submit with as many empty input as you want.
To validate the input I compare the length of the array of all the inputs with the same array with only unique values. If they have the same length it's ok. I need to improve my code because now it works only if the user enters all the input fields. If some inputs are empty they are considered in the array with unique value as they all have "" as a value. So, if the user enters just one number I will get that array length is 4 and array unique is 2 but it should be 1 and 1 (skipping the blank items).
I was thinking about using splice()
on arr
, but is this the best way to do this validation?
**EDIT: I applied splice BUT if the array is ('1','','') my code gives me ('1','') instead of just (1) as I'd expect... ** This is because splice remove the item and change array length so that the for loop point to the wrong index.
Any idea?
HTML:
<div class="sez-form">
<fieldset>
<legend>Messaggi inclusi</legend>
<div class="percheckbox">
<input class="checkseq" type="checkbox" value="1" name="messaggio[0]">
Prova di messaggio che scorre<br>
<label>Ordine: </label>
<input class="seq" type="text" name="ordine[0]" maxlength="2" size="2">
</div>
<div class="percheckbox">
<input class="checkseq" type="checkbox" value="3" name="messaggio[1]">
Titoli di film<br>
<label>Ordine: </label>
<input class="seq" type="text" name="ordine[1]" maxlength="2" size="2">
</div>
<div class="percheckbox">
<input class="checkseq" type="checkbox" value="6" name="messaggio[2]">
Prova a testo fisso<br>
<label>Ordine: </label>
<input class="seq" type="text" name="ordine[2]" maxlength="2" size="2">
</div>
<br style="clear: both;">
</fieldset>
</div>
JAVASCRIPT:
function uniqueArray(arr) {
return $.grep(arr,function(v,k) {
return $.inArray(v,arr) === k;
});
}
$(document).ready(function() {
$('#invia').click(function(e) {
e.preventDefault();
var arr = $(".seq").map(function(){ return $(this).val(); }).toArray();
var empty = $(".seq").filter(function() {
return this.value == "";
})
for (index = 0; index < arr.length; ++index) {
if (arr[index]=='') {
new_arr = arr.splice([index],1);
}
console.log(arr);
}
if(empty.length == $('.seq').length) {
alert('Non hai scelto alcun messaggio per il workflow. Correggi per procedere.');
}
else if(uniqueArray(arr).length != $('.seq').length) {
console.log(uniqueArray(arr));
alert('Ci sono voci duplicate nella sequenza. Correggi per procedere.');
}
else if($('#dt_from').val()=='__/__/____ __:__') {
alert('Scegli data e ora di inizio validit\u00E0 per il workflow');
}
else if($('#dt_to').val()=='__/__/____ __:__') {
alert('Scegli data e ora di fine validit\u00E0 per il workflow');
}
else {
ajaxSubmit();
}
});
});