Itai Yasur
Itai Yasur

Reputation: 109

Using JS loops to send unique vars from HTML buttons to function

Beginner here. I have a loop that creates 26 buttons with unique ID's and values. What I'm struggling with is figuring out the proper way to send the button's ID to a function so that I can store unique vars for each button independently without creating more than one function. I currently have an array with the 26 items I need for my buttons and the following loop:

function makeButtons() {
for (var i = 0; i < 26; i++) {
    document.getElementById("whereButtonsGo").innerHTML += "<input type = 'button' value = '" + items[i] + "' id = 'button" + items[i] + "' onclick = doThing(button" + items[i] + ")'>";  
} 
}

I want the argument in the onclick function to be sent to a function such as:

function doThing(id) {
document.getElementById("'" + id.value + "'").style.color = "pink"; 
}

But so far I haven't been able to get this to work. Any help would be greatly appreciated!

Upvotes: 1

Views: 289

Answers (2)

Erick Lanford Xenes
Erick Lanford Xenes

Reputation: 1572

Maybe this is what you are looking for:

makeButtons();

function makeButtons() {
	for (var i = 0; i < 26; i++) {
		document.getElementById("whereButtonsGo").innerHTML += "<input type = 'button' value = '" + i + "' onclick = doThing(this)>";
	}
}

function doThing(currentButton) {
    currentButton.style.color = "pink"; 
}
<div id="whereButtonsGo"/>

Try to keep the IDs as simple as possible

Upvotes: 1

Dave
Dave

Reputation: 4412

I recommend against using innerHTML for creating elements that you actually want to do something. Even if it works, your code will be amazingly unclear. Instead, write code that demonstrates that you're actually creating and adding elements:

var items = [1,2,3,4,5,6];

function makeButtons() { 
  var container = document.getElementById("whereButtonsGo");
  for (var i = 0; i < items.length; i++) {
    var button = document.createElement("button");
    button.type = 'button';
    button.value = items[i];
    button.innerText = items[i];
    button.id = 'button'+items[i];
    button.onclick = doThing;
    container.append(button)
  }
}

function doThing() {
  console.log('click of ' + this.id);
}

makeButtons();

Note that you don't need to pass the id in the function call for the event - the button that was clicked will be available as this.

Here is a fiddle.

Upvotes: 1

Related Questions