47

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>
Souparnika
  • 471
  • 2
  • 5
  • 11

6 Answers6

56

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.

Andrew Brooke
  • 12,073
  • 8
  • 39
  • 55
Robin Leboeuf
  • 2,096
  • 1
  • 13
  • 14
  • 2
    sorry i can't catch up wht u say – Souparnika Aug 14 '13 at 08:24
  • 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. – Robin Leboeuf Aug 14 '13 at 08:33
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>
Jonathan E. Landrum
  • 2,748
  • 4
  • 30
  • 46
Shubham Chandra
  • 109
  • 1
  • 4
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

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
2

Try this:

<script type="text/javascript">

function test()
{
    if($('input#field').length==0)
    {
       $('<input type="button" id="field"/>').appendTo('body');
     }
}
</script>
sangram parmar
  • 8,462
  • 2
  • 23
  • 47
-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>
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
  • 1
    @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? – Nicolae Olariu Aug 14 '13 at 08:36
  • please giv me a solution to append button on a div when the page loads – Souparnika Aug 14 '13 at 08:46
  • @user2236221 can I ask you why you're using w3 editor? Anyway, check my first answer, you don't need script.js :) – Nicolae Olariu Aug 14 '13 at 09:00
  • 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 – Souparnika Aug 14 '13 at 09:02
  • please let me know how to put an alert on this button click without changing the code – Souparnika Aug 14 '13 at 09:20
  • alert("my message here"); what do you mean by "put an alert on this button click without changing the code"? :-) – Nicolae Olariu Aug 14 '13 at 12:36
  • how we can pass id ,type etc as parameters in the function – Souparnika Aug 14 '13 at 12:51
  • how to change the above code like _app.CreateButton (id, text, primaryIcon, secondaryIcon, className); please help mee – Souparnika Aug 15 '13 at 03:56
  • the above code is for append only one button to a div if we want to append more than one button with different id to a div .. is there any solution for this by creating a simple function.???? please help me – Souparnika Aug 15 '13 at 04:39
-2

Try this

function test()
{
   $("body").append("<input type='button' id='field' />");
}
Eswara Reddy
  • 1,617
  • 1
  • 18
  • 28