简体   繁体   中英

JavaScript Add Textbox Dynamically when Button onClick

I am trying to add a new textbox when add button is onclick using JavaScript. Here is my HTML:

htmlStr += "<div id='filterContent' style='width:100%;text-align:center;'>";
htmlStr += "<input id='startLoc' type='text' />";
htmlStr += "<input id='endLoc' type='text' />";
htmlStr += "<input id='addLoc' type='button' value='Add' onClick='addTextBox()' />";
htmlStr += "</div><br/>";

And here is my JavaScript to add a new textbox when button is onClick:

function addTextBox(){
var element = document.createElement("input");

element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
//element.setAttribute("style", "width:200px");

var foo = document.getElementById("filterContent");
foo.appendChild(element);
}

It works perfectly to add as many textbox as I want. But somehow the textbox created share the same id. I wonder is that possible to add many textbox with different ID each time when the button is onClick?

Thanks in advance.

var aa=Math.random();   
 <input id='addLoc"+aa+"' type='text' />

User math.random to generate random id's for a textbox

Using your current setup you could keep track of an id increment in a global:

//outside function
var idIndex = 1;

function addTextBox(){
var element = document.createElement("input");

element.setAttribute("type", "text");
element.setAttribute("value", "");
element.setAttribute("name", "Test Name");
element.setAttribute("id", "addLoc" + idIndex++);
element.setAttribute("style", "width:200px");

element.onclick = function()
{
    //do something
 }


var foo = document.getElementById("filterContent");
foo.appendChild(element);
}

EDIT: To answer the question in this answer's comments. It is certainly possible to add a different onclick handler for every new textbox (although you're probably better off designing your handlers so you can use a single handler for all but if you wanted for some reason to use a different one you could bind an anonymous function to the handler, I have added an approach above).

EDIT2: Regarding the second question in the path there are two approaches you could use. Instead of calling the separate functions getFirstPath() getSecondPath() etc. individually, you could have a single function called getPath() and pass the index to it as a parameter:

var getPath = function(index) {

    switch(index)
    {
        case 1:
            return getFirstPath();
            break;
        case 2:
            return getSecondPath();
            break; //and so on.
    }
}

And then your onclick would look like this:

element.onclick = function()
{
    getPath(index);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM