Yunbae
Yunbae

Reputation: 21

How do you assign onclick within for loop in javascript?

function initnav(){
var cbox=document.getElementsByClassName('box');
for(var i=0;i<cbox.length;i++){
    cbox[i].innerHTML=cbox[i].id;
    <!--so far I have set their captions after setting their ids same as how I want them            to appear.-->

    <!--what comes next is what doesn't really work.-->
    getElementById(cbox[i].id).onclick=Mclick(cbox[i].id);
}

};

function Mclick(id){alert(id);}

The whole thing is in a js file, and promptly linked from my html file.

As planned, all the buttons should appear and be clickable, but what is happening instead is only one of them is visible and that one is not working when I click on it.

When I create a lot of div-oriented buttons, I wish I could run for loop and be able to assign each of them as clickable instead of writing lines as many as they are.

How do you assign onclick within for loop in javascript?

Upvotes: 2

Views: 195

Answers (2)

Sur
Sur

Reputation: 303

So basically you don't call the for loop since the for loop is in the function. If you want to call all your variables and the statements in the for loop you have put the statements in the function and call the function outside of the function but inside of the script.

Upvotes: -1

Eevee
Eevee

Reputation: 48546

You're calling the function instead of assigning it.

getElementById(cbox[i].id).onclick = Mclick;

Of course, now your function will receive an event argument instead of an id. (Passing the id inside the loop is a huge pain; easiest fix is to not bother trying.) But it also gets the attached element as this, which is convenient:

function Mclick() {
    alert(this.id);
}

Other comments:

  1. You should try not to be in the habit of using innerHTML if you're not assigning a string that contains known HTML. Saves you from having to care about escaping. Use textContent instead.
  2. Assigning to onclick is a bit inflexible; you can only ever assign one click handler this way, and it's hard to notice if you accidentally overwrote an existing handler. Use addEventListener.
  3. getElementById(element.id) should surely be equivalent to element.
  4. Don't use HTML comments within JavaScript! :) They only work for... weird backwards-compatibility reasons. JavaScript comments are either // ... or /* ... */.
  5. Best not to capitalize a function name unless it's supposed to be a constructor; you may notice that SO's highlighting made Mclick green, because it thinks it's a class name.

So I'd end up with:

function initnav() {
    var cbox = document.getElementsByClassName('box');
    for(var i = 0; i < cbox.length; i++) {
        cbox[i].textContent = cbox[i].id;
        cbox[i].addEventListener('click', alert_id);
    }
}

function alert_id(event) {
    alert(this.id);
}

Upvotes: 6

Related Questions