mardi 11 juin 2019

Why is Javascript equating 5 == 8 as true?

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>&nbsp;<input type="checkbox" name="Active" value="5" onchange=updateStatusString("5")>&nbsp;"Active"</label>
<label>&nbsp;<input type="checkbox" name="NonActive" value="8" onchange=updateStatusString("8")>&nbsp;"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?




Aucun commentaire:

Enregistrer un commentaire