samedi 14 octobre 2017

jQuery - index() function returns wrong index (CheckBox and Select)

I've created list of CheckBox elements and Select with same values as previously mentioned list. What I achieve to do is if I change CheckBox selection, Select list automaticly updates itself to the same named option as CheckBox. I've created this in pure JavaScript (and it's working) like this:

function addChckBoxListener() {
    for (var i = 0; i < chckBox.length; i++) {
        (function(index) {
            chckBox[i].addEventListener("change", function() {
                update(0, index);
            });
        })(i);   
    }    
}

function addSelectListListener() {
    selectList.addEventListener("change", function() {
        update(1, this.selectedIndex); 
    });
}

Later, I wanted to achieve the same with jQuery library but it's index() function returns wrong index. I have no idea why. Here is same code but in jQuery:

function addChckBoxListener() {
    chckBox.each(function() {
        $(this).change(function() {
            update(0, $(this).index());    
        });
    });   
}
function addSelectListListener() {
    selectList.change(function() {
        update(1, $(this).selectedIndex);  
    });
}

Here is my HTML code:

<body>
    <div>
        <ul>
            <li><input type="checkbox" value="red">&nbsp;Czerwony</li>
            <li><input type="checkbox" value="blue" checked>&nbsp;Niebieski</li>
            <li><input type="checkbox" value="green">&nbsp;Zielony</li> 
        </ul>
        <select name="selectColors">
            <option value="red">Czerwony</option>
            <option value="blue" selected="selected">Niebieski</option>
            <option value="green">Zielony</option>
        </select>
    </div>
</body>

In case you want to test this code, here is the link (JSFiddle): http://ift.tt/2wUmho2




Aucun commentaire:

Enregistrer un commentaire