Reputation: 633
EDIT jQuery.inArray kept failing to do string != int comparisons, and this was resolved with the help of ShankarSongoli. Originally it was thought to be a variable scope issue, so please remember to look at all aspects and not just one in any given problem.
omit_all_user_contacts = new Array();
add_contacts = new Array();
function is_added_contact(id) {
if ( jQuery.inArray(id, add_contacts) == -1 )
return false;
return true;
}
function selectcontacts(userid){
document.getElementById("ic"+userid).checked = true;
omit_all_user_contacts.push(userid);
var buf = '<table class="contactlist" width="100%">';
buf = buf + "<tr class='contactlistheader'><td></td><td>Contact Name</td><td>Company</td><td>Email</td><td>Profession</td></tr>";
var tmp;
jQuery.getJSON('/user/get_user_contacts/'+userid, function(data) {
jQuery.each(data.contacts, function(key, value) {
buf = buf + "<tr><td><input type='checkbox' name='manualcontact[]' onclick='manualcontact(" + value.id + ",this.checked)' ";
alert(is_added_contact(value.id));
if ( jQuery.inArray(value.id, add_contacts) > -1 ) {
buf = buf + " checked ";
}
buf = buf + "/></td>";
buf = buf + "<td>" + value.firstname + " " + value.lastname + "</td>";
buf = buf + "<td>" + value.company + "</td>";
buf = buf + "<td>" + value.email + "</td>";
buf = buf + "<td>" + value.profession + "</td></tr>";
});
buf = buf + '</table>';
iBox.show(buf);
});
}
function manualcontact(id,val) {
if ( val == true ) {
add_contacts.push(id);
} else {
add_contacts.splice( jQuery.inArray(val, add_contacts), 1 );
}
}
Upvotes: 0
Views: 2102
Reputation: 19
It is important that the type of the variable is the same. I needed to compare integers, but since my original text contained numbers split by commas then the items in my array were being seen as strings.
Here was a simple function I wrote to check for integers only. It works the same as jquery.inArray but it only checks a specific data type.
function in_array(val,arr) {
cnt=0;
index=-1;
$(arr).each(function () {
if(parseInt(this) == parseInt(val)) { index=cnt; }
cnt++;
});
return index;
}
Upvotes: 0
Reputation: 69905
You should change the title of the question first and also since the issue is resolved through our comments accept this answer and close it.
Solution:
The array values were of string type and comparison was done with integers, so it was failing.
var tmpContacts = ["2"];
jQuery.inArray(2, tmpContacts) was always returning `-1`
Change it to jQuery.inArray("2", tmpContacts)
Upvotes: 2