user3932611
user3932611

Reputation:

Javascript HTML checkbox array set onclick

I have an array of check boxes, that I pass in to a function, with the intention of setting up a listener for each box.

At this point all I want the listener to do is to display the id and the value of each checkbox in an alert box. Both attributes have been set before being passed into this function.

The array is created and then passed through using the following line:

var oCustomMultiSelect = new customMultiSelect(oCheckBoxes);

The listeners are then activated using the following method:

function customMultiSelect(pCheckBoxes)
{        
    for (i = 0; i < pCheckBoxes.length; i++) {
        pCheckBoxListener(pCheckBoxes[i])
    }
}

and this is the method that is supposed to set up the listeners:

function pCheckBoxListener(pCheckBox)
{
    alert("Value " + pCheckBox.value + " ID " + pCheckBox.id);
}

The method I have so far will display the correct values, but not onclick, it displays them at the time of construction. I want it to display them when they are clicked.

I assume this is a very simple problem, but i cannot find the correct way to achieve this.

Upvotes: 2

Views: 1330

Answers (2)

dreyescat
dreyescat

Reputation: 13808

You can add the click event listener in your customMultiSelect for all your check boxes:

function customMultiSelect(pCheckBoxes)
{
    for (var i = 0; i < pCheckBoxes.length; i++) {
        pCheckBoxes[i].addEventListener('click', function () {
            pCheckBoxListener(this);
        });
    }
}

See demo

Upvotes: 0

Slippery Pete
Slippery Pete

Reputation: 3110

Per David's comment, you need to assign an event handler rather than call a function in your loop.

http://jsfiddle.net/qfbee5ot/

var oCheckBoxes = document.getElementsByName("cb");
var oCustomMultiSelect = new customMultiSelect(oCheckBoxes);

function customMultiSelect(pCheckBoxes) {
    for (i = 0; i < pCheckBoxes.length; i++) {
        //pCheckBoxListener(pCheckBoxes[i])
        addEventHandler(pCheckBoxes[i], pCheckBoxListener);
    }
}

function addEventHandler(element, func) {
    if (element.addEventListener) {
        element.addEventListener("click", func, false);
    } else {
        element.attachEvent('onclick', func);
    }
}

function pCheckBoxListener(e) {
    var pCheckBox = e.target;
    alert("Value " + pCheckBox.value + " ID " + pCheckBox.id);
}

Upvotes: 1

Related Questions