0

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

1
  • I could give you an answer using jQuery if you like? Commented Mar 30, 2012 at 9:09

3 Answers 3

2

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++;
}

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

Comments

2

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>

1 Comment

note: you don't need to escape " if you are wrapping your string around '
1

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.

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.