How to create dynamic function in javascript?

How to uniquely name the texboxes created by javascript using some kind of loop..?

  • <html> <head> <title>Dynamic Form</title> <script language="javascript"> function changeIt() { my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'>" } </script> </head> <body> <form name="form" action="display.php" method="post"> <input type="text" name="text"> <div id="my_div"></div> <a href="#" onclick="changeIt()">Add textbox</a> <input type="submit" value="submit"> </form> </body> I want to name each textboxes created by the javascript uniquely like mytext1, mytext2, mytext3 and etc. whenever i click the link to create a new textbox by adding a variable to the name attribute of the textbox and the variable increments each click... Sry im new in javascript i dunno how to implement my idea ...

  • Answer:

    Altering the page with innerHTML is known to be a bad practice these days. It would be better to access/create the document object model with a little bit more Javascript. Replace everything in the <script> tags with this, and you should be all set! var count = 1; function changeIt() { var content = document.getElementById('my_div'); var input = document.createElement('input'); input.setAttribute('type', 'text'); input.setAttribute('name', 'myText' + count); content.appendChild(input); count++; }

WRex at Yahoo! Answers Visit the source

Was this solution helpful to you?

Other answers

Not a problem. We all started somewhere. Here's an example for you. http://pastebin.com/1jVWQtBK Hope it helps. - Dominic

Dominic

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.