Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically create buttons with Jquery

Tags:

jquery

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?

like image 542
james Avatar asked Jan 20 '12 04:01

james


People also ask

How to dynamically create a button in JavaScript?

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.

How to create button element in JavaScript?

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.

How can we call onclick function on dynamically created button in jquery?

onclick = function () { alert("hi jaavscript"); };


2 Answers


$(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

like image 63
Sudhir Bastakoti Avatar answered Sep 19 '22 12:09

Sudhir Bastakoti


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 :)

like image 43
sree Avatar answered Sep 22 '22 12:09

sree