简体   繁体   中英

How to add multiple input boxes with different names

I am trying to make a button to add another input box every time it is clicked but I also want it to add an increasing number the end of the input name. I have this code to add more inputs.

<script type="text/javascript">
function addInput()
{
    var x = document.getElementById("inputs");
    x.innerHTML += "<input type=\"file\" name=\"photo\" />";
}
</script>

What can I do to make it so that every time a new form is added it will add a higher number to the end of name="photo" so that I can process images with my php script correctly?

default the form is:

 <input type="file" name="photo">

but I would like to add a number to the end of photo every time a new input is made to have an output like this.

 <input type="file" name="photo">
 <input type="file" name="photo2">
 <input type="file" name="photo3">
 <input type="file" name="photo4">

etc

You can use [] in your form name, then your php script will automatically convert those inputs into an array, that way you don't even have to worry about appending numbers anymore.

<input type="file" name="photo[]">

If you want to do it using javascript, easiest way is to have a variable that keeps track of the number of inputs

var inputNumber = 0;
function addInput()
{
    var x = document.getElementById("inputs");
    x.innerHTML += "<input type=\"file\" name=\"photo\"" + inputNumber + " />";
    inputNumber++;
}

Declare a count and initialize it to 0, then increase it in every call.

<script type="text/javascript">
var count=0;
function addInput()
{
    var x = document.getElementById("inputs");
    x.innerHTML += '<input type=\"file\" name=\"photo\"'+count+' />;
    count++;
}
</script>

andeas's answer is probably best for this specific situation. But in general if you want a counter that will increase every time a function is called, try:

(function {
    var counter = 0;
    window.myfunction = function() {
        // do stuff, use counter if needed
        counter++;
    }
})();

counter can be treated as if it were a static variable in this context.

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