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>

Leave a Comment