samedi 14 février 2015

how to check existence of a value in array by jQuery

If a user selects a checkbox, related value is stored in a hidden input field by jQuery. Then I have to check whether the value already is in the array or not. If it is in array, I don't want to add it again (avoiding duplicates), but if it is not in array it will be added to the array. My code, mentioned below, is working accordingly except checking of the first entered check box, i.e when the array is empty. It is showing the value is in array while the array is empty. Please look at my code below:


HTML of the page:



<input type="hidden" name="selected" id="selected" value="" />
<input type="checkbox" name="check_list[]" class="check_list" value="23" />
<input type="checkbox" name="check_list[]" class="check_list" value="24" />
<input type="checkbox" name="check_list[]" class="check_list" value="25" />


jQuery code for adding an ID while any checkbox is selected:



$(document).ready(function(){
var ids = [];
$(".check_list").change(function(){
code = $(this).val();
if($.inArray(code,ids)){
alert("Value is in array");
}else{
alert("Value is not in array");
ids.push(code);
$("#selected").val(ids);
});
});


Let, a user selects the checkbox which value is 23 at first. At this time, the 'id' array is empty. Then the jQuery checks the existence of 23 in array 'id' and as it is empty, it is showing 'Value is in array'. But later if a user selects 24 or 25, the code works well.


Why it is not working for the firstly selected checkbox? How to resolve this issue?





Aucun commentaire:

Enregistrer un commentaire