48

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>
2
  • $("body").append(r); needs to go IN the function. Commented Aug 14, 2013 at 8:28
  • Please refer to this answer stackoverflow.com/a/6205324/3530081 Commented Mar 30, 2016 at 14:52

6 Answers 6

57

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.

Sign up to request clarification or add additional context in comments.

2 Comments

sorry i can't catch up wht u say
you should use your .append() function INSIDE of your test() function, because you want the new input to be appent to your body each time your click the button, it means each time your run your function, that's why you should put your line $("body").append(r); in your function instead of putting it after.
7

To add dynamic button on the fly;

<!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 newButtonClickListener() {
            alert("Hello World");
        }
        function test() {
            var r = $('<input/>').attr({
                type: "button",
                id: "field",
                value: "New Button",
                onclick: "newButtonClickListener()"
            });
            $("body").append(r);
        }
    </script>
</head>
<body>
    <button onclick="test()">Insert after</button><br/> 
</body>
</html>

1 Comment

This would be more useful as a runnable snippet, that way anyone can see how it works immediately.
4

the $("body").append(r) statement should be within the test function, also there was misplaced " in the test method

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

Demo: Fiddle

Update
In that case try a more jQuery-ish solution

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

Demo: Plunker

6 Comments

I want to be the first to thank you for making that code readable... It was really badly formatted
how can we add value to this button??
ok thanks.. how to append this button only "once" on a button click insertafter
and giv me a solution to append button on a div when the page load.
<!DOCTYPE html> <html> <head> <script src="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>
|
2

Try this:

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>

3 Comments

button should be appended only once how we can do this
@user2236221 check updated answer if input with id field is not exist than it append it to body other wise not..
how we can pass id, value etc through function like this_app.CreateButton (id, text, primaryIcon, secondaryIcon, className);
-2

Try this

function test()
{
   $("body").append("<input type='button' id='field' />");
}

Comments

-2

Working plunk here.

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").append(r);
  });
});

[... source stripped here ...]

<body>
    <button id="insertAfterBtn">Insert after</button>
</body>

[... source stripped here ...]

To make it work in w3 editor, copy/paste the code below into 'source code' section inside w3 editor and then hit 'Submit Code':

<!DOCTYPE html>
<html>

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
  </head>

  <body>
    <button id="insertAfterBtn">Insert only one button after</button>
    <div class="myClass"></div>
    <div id="myId"></div>
  </body>

<script type="text/javascript">
$(document).ready(function()
{
  // when dom is ready, call this method to add an input to 'body' tag.
  addInputTo($("body"));

  // when dom is ready, call this method to add an input to a div with class=myClass
  addInputTo($(".myClass"));

  // when dom is ready, call this method to add an input to a div with id=myId
  addInputTo($("#myId"));

  $("#insertAfterBtn").one("click", function(e)
  {
    var r = $('<input/>', { type: "button", id: "field", value: "I'm a button" });

    $("body").append(r);
  });
});

function addInputTo(container)
{
  var inputToAdd = $("<input/>", { type: "button", id: "field", value: "I was added on page load" });

  container.append(inputToAdd);
}
</script>

</html>

9 Comments

@user2236221 Have you checked that plunk? it's working fine on my side, clickin the button will add a new button each time. What browser are you using? Have you tried the code and it gave any errors?
please giv me a solution to append button on a div when the page loads
@user2236221 can I ask you why you're using w3 editor? Anyway, check my first answer, you don't need script.js :)
ur first ans is working fine but this code not working can u please give me script.js file.. what is included in that file
please let me know how to put an alert on this button click without changing the code
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.