1

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!

3

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, youre right, I just wanted you to take the idea ;)
Sorry, didn't see that you'd used (this) here. Deleted my post to make this my answer pick. Thanks!
1

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.

1 Comment

Thanks for all the info, I did not know there was an alternative to innerHTML but I've always wanted one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.