timtour97
timtour97

Reputation: 222

Passing One's Self to OnClick Event JavaScript

The on click event that I add to an input in javascript isn't working in the proper manner.
My code so far looks like so:

function order(option) {
    if(option.checked) {
        document.getElementId("col_order").value = document.getElementById("col_order").value + " " + option.value;
    }
}
...//somewhere further down
for(var i = 0; i < options.length; i++) {
    var check = document.createElement("input");
    var label = document.createElement("label");
    var description = document.createTextNode(options[i]);
    check.type = "checkbox";
    check.name = "order_list[]";
    check.value = options[i];
    check.onclick = "order(check)";  //Problem here
    label.appendChild(check);
    label.appendChild(description);
    element.appendChild(label);
}

I have also tried:

check.onclick = (function() { var option = check; return function() {order(option);}})();

The problem that I am having is the check.onlick line of code. When I add this with normal HTML:

<input type = "checkbox" name = "order_list[]" onclick = "order(this)" value = "randVal">randVal</input>

I don't have any problem whatsoever; the method executes with the intended results. Any thoughts?
Let me clarify: I make it to the order function just fine, but I never get into the if statement, even though the checkbox was just clicked

Upvotes: 0

Views: 5146

Answers (2)

adeneo
adeneo

Reputation: 318192

Use addEventListener instead, and even if it looks like it should work, you're overwriting the same variables on each iteration as there is no closure in for loops, so I would probably add a closure to avoid issues.

For a checkbox you would listen for the change event, not click

for(var j = 0; j < options.length; j++) {
    (function(i) {

        var check = document.createElement("input");
        var label = document.createElement("label");
        var description = document.createTextNode(options[i]);

        check.type = "checkbox";
        check.name = "order_list[]";
        check.value = options[i];

        check.addEventListener('change', function() {
            if (this.checked) {
                var col_order = document.getElementById("col_order");
                col_order.value = col_order.value + " " + this.value;
            }
        }, false);

        label.appendChild(check);
        label.appendChild(description);
        element.appendChild(label);

    })(j);
}

FIDDLE

Upvotes: 2

Aaron Digulla
Aaron Digulla

Reputation: 328594

check.onclick = "order(check)"; assigns a String as an on-click handler. That doesn't work; the browser expects a function there:

check.onclick = function() {
    order(check);
}

Upvotes: 0

Related Questions