Dynamic button javascript
Solution 1
Something like this...?
<html>
<head>
<script type="text/javascript">
var arrayToModify = [];
window.onload = function () {
var i, buttonsToCreate, buttonContainer, newButton;
buttonsToCreate = ['button1','button2','button3','button4','button5'];
buttonContainer = document.getElementById('this_element_contains_my_buttons');
for (i = 0; i < buttonsToCreate.length; i++) {
newButton = document.createElement('input');
newButton.type = 'button';
newButton.value = buttonsToCreate[i];
newButton.id = buttonsToCreate[i];
newButton.onclick = function () {
alert('You pressed '+this.id);
arrayToModify[arrayToModify.length] = this.id;
};
buttonContainer.appendChild(newButton);
}
};
</script>
</head>
<body>
<div id='this_element_contains_my_buttons'></div>
<input type='button' onclick='alert(arrayToModify);' value='Show the buttons I have clicked' />
</body>
</html>
EDIT: I have just added some functionality to track button presses in an array, as requested in the comment above
Solution 2
I would advise you use jQuery for this. It would make it a lot simpler.
Firstly, to create the buttons from an array of button ids you could do something along the lines of the following:
var buttons = ['start', 'stop', 'foo', 'bar'];
for(var i = 0; i < buttons.length; i++){
$('<button>')
.attr('id', buttons[i])
.text(buttons[i])
.appendTo('div');
}
Next, to listen for the button clicks, you could modify the above as follows:
var buttons = ['start', 'stop', 'foo', 'bar'];
var clicks = [];
for(var i = 0; i < buttons.length; i++){
$('<button>')
.attr('id', buttons[i])
.text(buttons[i])
.appendTo('div')
.click(function(){
clicks.push(this.id);
});
}
I'm not quite sure what you want to do on-click. Could you elaborate?
Here's a jsFiddle demonstrating the solution.
myol
Updated on June 04, 2022Comments
-
myol almost 2 years
had a look for a guide on this but couldn't really find anything specific on it, and thought you guys could help.
I have a javascript file which performs various tasks onLoad. Currently I have 5 buttons in an HTML page but what I would like to do is to is read from an array in the js file and dynamically create a number of buttons depending what was in the array.
Similarly I want the buttons on click to be 'listened' for (alter an array in the js)
I have an idea that I want to read the array elements and set them as the button IDs and create them. Likewise I want to listen to what button has been clicked by its ID and have it alter an array. But how do I actually go about that process?
Cheers
-
myol over 12 yearsThanks for that, but I will have to take @DaveRandom's version
-
myol over 12 yearsI can use this with a bit of playing about as I now see what is going on. Thanks.