Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to programmatically create separate permutations of the same function?

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;
    }
}
like image 688
Paul Beaudet Avatar asked Dec 28 '25 02:12

Paul Beaudet


1 Answers

Well, first off, assigning a DOM element to another element's innerHTML is just going to produce "[object HTMLDivElement]" or similar depending on the element. Perhaps you want

function buttonOnclick(whichButton) {
 document.getElementById("dialog0").innerHTML = document.getElementById("dialog" + whichButton.toString()).outerHTML;
 //which would make the innerHTML be `<div>stuff</div>`
}

As for your other issue, just use a query, iterate to assign, and pass the button's id number along

var buttons = document.querySelectorAll("[id^=button]");
for(var i = 0; i < buttons.length; i++){
 buttons[i].onclick = function(){
  buttonOnclick(this.id[this.id.length-1]);
 };
}
like image 53
Travis J Avatar answered Dec 30 '25 16:12

Travis J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!