So I have 2 check-boxes:
var statusList = [];
function updateStatusString(x) {
if (statusList != null) {
if (statusList.length > 0) {
for (var i = 0; i < statusList.length; i++) {
if (parseInt(statusList[i]) == parseInt(x)) {
statusList[i] = 123;
} else {
statusList.push(x);
}
}
} else {
statusList.push(x);
}
}
alert(statusList);
}
<label> <input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")> "Active"</label>
<label> <input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")> "Active"</label>
When I click a checkbox it adds it to a JavaScript list, if it's already in the list I want to overwrite it with another value (123 in this example).
But when I click the second one (doesn't matter the order, the 2nd element is always 123 for some reason.
Where as I would expect if I click the top check-box it would be a list containing '5', then clicking the second check-box I would expect 5,8 but it alerts as 5,123, don't really see why it's doing this as 5==8 is false... any ideas?
Updated algorithm to fix underlying issue:
In-case anyone ever finds this useful I changed the algorithm to a better alternative:
var statusList = [];
function updateStatusString(x) {
if (statusList.length > 0) {
if (statusList.includes(x)) {
var idx = statusList.indexOf(x);
if (idx != -1) {
statusList.splice(idx, 1);
}
}
else {
statusList.push(x);
}
} else {
statusList.push(x);
}
alert(statusList);
}