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>
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").
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.
onclick = function () { alert("hi jaavscript"); };
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
.
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