1

I write function for manipulation with DOM objects. This function must find element with specific ID and add new child element to element with specific ID:

<html>
<head>
    <title> Text </title>
     <meta charset="utf-8">
</head>
<body id="tbody">
  <script>
    function add(){
       el = document.getElementById("testform");
       var nf=document.createElement("input");
       nf.type="text";
       el.appendChild(nf);
    }
  </script>

   <p>
     <form id="testform">
       <button onclick="add();"> create</button>
      </form>
   </p>


</body>
</html>

Element of text input doesn't create on page,but same code is placed in script tag without function-work

1
  • I think this problem related with local\global variable in JS function and scope Commented Dec 14, 2012 at 10:41

2 Answers 2

7

You're reloading the page, and need to return false when clicking the button to stop the form from being submitted :

<html>
    <head>
        <title> Text </title>
        <meta charset="utf-8">
    </head>
    <body id="tbody">
        <script type="text/javascript">
            function add(){
                el = document.getElementById("testform");
                var nf=document.createElement("input");
                nf.type="text";
                el.appendChild(nf);
            }
       </script>
       <p>
       <form id="testform">
           <button onclick="add();return false;"> create</button>
       </form>
       </p>
   </body>
</html>​

Also, sticking a form inside a paragraph seems unnecessary ?

FIDDLE

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

2 Comments

+1 The page is reloading because the default type of the <button > element is submit.
Thanks for adeneo and Matt
1

Since the Default action of button element type is submit so it submits every time you click. You can do a return false or create a label tag instead of button something like:

<html>
    <head>
    <title> Text </title>
     <meta charset="utf-8">
    </head>
    <body id="tbody">
    <script>
    function add(){
        el = document.getElementById("testform");
        var nf=document.createElement("input");
        nf.type="text";
        el.appendChild(nf);
    }
    </script>

   <p>
   <form id="testform">
   <label onclick="add();"> create</label>
   </form>
   </p>


   </body>
   </html>

DEMO

Comments

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.