Reputation: 11871
I have a series of checkboxs and on change event like so:
$(".checkbox").on('change', function () {
UpdateHolder($(this).attr('id'), customerID, this.checked);
});
function UpdateHolder(questionid, customerid, checked) {
holder.push({ questionid: questionid, customerid: customerid, checked: checked });
console.log(holder);
}
with this, I am able to add an item to the array, but my question is how would I update an item ? I only want to update if a checkbox is selected or not.
Upvotes: 0
Views: 79
Reputation: 337570
The easiest way to achieve this is to not update the list at all, but instead to create a new one on each action. Try this:
$('.checkbox').on('change', function() {
holder = $('.checkbox').map(function() {
return {
questionid: this.id,
customerid: customerID, // I presume this is a global variable?
checked: this.checked
};
}).get();
console.log(holder);
});
Upvotes: 1
Reputation: 24638
To be able to update existing entries, your function should look something like this:
function UpdateHolder(questionid, customerid, checked) {
var index = holder.indexOf({
questionid: questionid,
customerid: customerid,
checked: checked
});
index = index > -1 ? index : holder.indexOf({
questionid: questionid,
customerid: customerid,
checked: !checked
});
//item was not found, insert it
if( index < 0 ) {
holder.push({
questionid: questionid,
customerid: customerid,
checked: checked
});
//item was found, update it
} else {
holder[index] = {
questionid: questionid,
customerid: customerid,
checked: checked
};
}
console.log(holder);
}
Upvotes: 0