Josh Pratt Josh Pratt - 1 month ago 8
jQuery Question

How do I use a concatenated element id with .click()?

I have 4 input boxes (streamInput1-4) and 4 buttons (button1-4) and I'm trying to use a loop to assign each button to its corresponding input box, but for some reason the buttons won't click when I use a concatenated element id with the .click() method.

This code works:

document.getElementById("streamInput1")
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById("button1").click();
}
});


But this code does not:

var numOfPlayers = 4;
var ii;

for ( ii = 1 ; ii <= numOfPlayers ; ii++ ) {
document.getElementById("streamInput"+ii)
.addEventListener("keyup", function(event) {
event.preventDefault();
if (event.keyCode == 13) {
document.getElementById("button"+ii).click();
}
});
}


I found that using "button1" in place of "button"+ii will work but "streamInput1" in place of "streamInput"+ii won't work. So only the concatenated element id with .click() isn't working properly.

Am I doing something wrong?

Answer

Please have a look at the modified code:

var numOfPlayers = 4;
var ii;


for ( ii = 1 ; ii <= numOfPlayers ; ii++ ) {
  var elm = document.getElementById("streamInput"+ii);
  elm.index = ii;
  elm.addEventListener("keyup", function(event) {
     var index = event.target.index;
      event.preventDefault();
      if (event.keyCode == 13) {
          document.getElementById("button"+index).click();
      }
  });
}



function onClick(e) {
  console.log('button clicked:' + e.target.id);
}
<div>
  <input type="text" id="streamInput1" /> <input type="button" value="Update" id="button1" onclick=onClick(event) />
</div>
<br/>
<div>
  <input type="text" id="streamInput2" /> <input type="button" value="Update" id="button2" onclick=onClick(event) />
</div>
<br/>
<div>
  <input type="text" id="streamInput3" /> <input type="button" value="Update" id="button3" onclick=onClick(event) />
</div>
<br/>
<div>
  <input type="text" id="streamInput4" /> <input type="button" value="Update" id="button4" onclick=onClick(event) />
</div>