I'm attempting to create onclick
events for a list of items that will basically achieve the same affect from a different sources of information that depends on the list item selected.
function buttonOnclick(whichButton) {
document.getElementById("dialog0").innerHTML = document.getElementById("dialog" + whichButton.toString());
}
document.getElementById("button1").onclick = function breakerOnclick1() {
buttonOnclick(1);
}
document.getElementById("button2").onclick = function breakerOnclick2() {
buttonOnclick(2);
}
document.getElementById("button3").onclick = function breakerOnclick3() {
buttonOnclick(3);
}
document.getElementById("button4").onclick = function breakerOnclick4() {
buttonOnclick(4);
}
document.getElementById("button5").onclick = function breakerOnclick5() {
buttonOnclick(5);
}
I would like to achieve this affect with a for loop instead of so manually. I know there is probably a more object oriented oriented or simple approach I'm missing being green to JavaScript.
How can this affect be achieved more programmatically?
Solution: Just to be clear on the answer to this question. The following produces the correct results quickly and reliably. All though, I'm sure there are other relevant suggestions below.
for (var i = 1; i < NUM_ENTRIES; i++){
document.getElementById("button" + i).onclick = function(){
var replacement = document.getElementById("dialog" + this.id[this.id.length-1]).innerHTML;
document.getElementById("dialog0").innerHTML = replacement;
}
}