0

I have started a new project and on of the first things that I worked on has really been a pain. I am making a form in which a person can upload many "attachments." Th problem with it is when the person presses "Add an Attachment" all the attachments get reset.

Code:

        ...

        function addAttachment() {
            var list = document.getElementById("attachments");

            var index = 1;

            for(; index < 6;index++) {
                if(document.getElementById("attachment" + index) == null) {
                    break;
                } else if(document.getElementById("attachment" + index).value == "") {
                    index = -1;
                    break;
                }
            }
            if(index == 5) {
                alert ('You can only have a maximum of 5 attachments!');
            } else if(index == -1) {
                alert ('One of your attachments do not have a file in it! Put your file in there first!'); 
            } else {
                list.innerHTML += '<br /><input size="1" type="file" id="attachment' + index + '" name="attachment' + index + '"/>';
            }
        }

        ...

<li id="attachments">
           <label>Attachments:</label> (<a onclick="addAttachment()" href="#">Add an Attachment</a>)
           <br /><input size="1" type="file" id="attachment1" name="attachment1"/>
        </li>
        ...

I guess my question is... Is there any better way to do this?

Thanks for any help!

1 Answer 1

4

You should use DOM, and appendChild instead of setting innerHTML

    function addAttachment() {
        var list = document.getElementById("attachments");

        var index = 1;

        for(; index < 6;index++) {
            if(document.getElementById("attachment" + index) == null) {
                break;
            } else if(document.getElementById("attachment" + index).value == "") {
                index = -1;
                break;
            }
        }
        if(index == 5) {
            alert ('You can only have a maximum of 5 attachments!');
        } else if(index == -1) {
            alert ('One of your attachments do not have a file in it! Put your file in there first!'); 
        } else {
            var br = document.createElement("br");
            var newAttachment = document.createElement("input");
            newAttachment.size = 1;
            newAttachment.type = "file";
            newAttachment.id = "attachment"+index;
            newAttachment.name = newAttachment.id;

            list.appendChild(br);
            list.appendChild(newAttachment);
        }
    }
Sign up to request clarification or add additional context in comments.

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.