I need to create 10 buttons dynamically with Jquery and set the text on them to be 1 -10, and add the same click event to all of them.
Should I be using dom create element or something other?
In vanilla JavaScript, you can use the document. createElement() method to programmatically create an HTML button element and set its required attributes. Then to append the button to a container, you can use the Node. appendChild() method.
Creating button object: The button object can be created using JavaScript. The document. createElement() method is used to create <button> element. After creating a button object use appendChild() method to append the particular element (such as div) to display it.
onclick = function () { alert("hi jaavscript"); };
$(document).ready(function() {
for(i = 1; i <=10; i++) {
$('<button/>', {
text: i, //set text 1 to 10
id: 'btn_'+i,
click: function () { alert('hi'); }
});
}
});
Hope it helps
try this:
var something = $('<input/>').attr({ type: 'button', name:'btn1', value:'a button' });
now append this to your div (in this example, it has the id "item"):
$("#item").append(something);
of course, for dynamic values, you need to do it inside a loop with iterated values of the name or ID field of the button..
hope explaining the concept helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With