Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a button dynamically using jquery

My task is to add button dynamically to the div.. here is the code that i follow to add button dynamically but its not working please give me a solution for this

<!DOCTYPE html>     <html>     <head>          <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>          <script type="text/javascript">              function test() {                 var r = "$('<input/>').attr({                              type: "button",                              id: "field"                         })";              }              $("body").append(r);          </script>     </head>     <body>          <button onclick="test()">Insert after</button>      </body>     </html> 

code to append button on div when page loads but its not working

<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script> <script> function test() {     var r=$('<input/>').attr({         type: "button",         id: "field"      });     test().append("#test");     } </script> </head> <body> <div id="test"></div>  <button id="insertAfterBtn" onclick="test()">Insert after</button> </body> </html> 
like image 919
Souparnika Avatar asked Aug 14 '13 08:08

Souparnika


People also ask

How to add button by jquery?

To add the new input just once, use the following code: $(document). ready(function() { $("#insertAfterBtn"). one("click", function(e) { var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" }); $("body").

How to add a button dynamically 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 can we call onclick function on dynamically created button in jquery?

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


1 Answers

Your append line must be in your test() function

EDIT:

Here are two versions:

Version 1: jQuery listener

$(function(){     $('button').on('click',function(){         var r= $('<input type="button" value="new button"/>');         $("body").append(r);     }); }); 

DEMO HERE

Version 2: With a function (like your example)

function createInput(){     var $input = $('<input type="button" value="new button" />');     $input.appendTo($("body")); } 

DEMO HERE

Note: This one can be done with either .appendTo or with .append.

like image 130
Robin Leboeuf Avatar answered Sep 18 '22 21:09

Robin Leboeuf