3

I am making an upload form and I want users to add more input file fields to the form if they require using jquery if they want to upload more than one file. This is the code I have so far below that isn't working. You can also see this on js fiddle: http://jsfiddle.net/benpaton/JUJxn/

Thanks in advance.

$(function () {
    $('#add-more-files').click(function() {
       var cloned = $(this).prev().clone();
       cloned.val(null);
       $(cloned).insertBefore($(this));
    });
});

<ul>
    <form enctype="multipart/form-data" action="" method="post">
        <li>Choose a file to upload:</li>
        <li><input name="uploadedfile" type="file" size="40" /></li>
        <li><a href="" id="add-more-files">Add file upload box</a></li>
        <li><input type="submit" value="Upload File" /></li>
    </form>
</ul>

2 Answers 2

3

You're not selecting the <li> element. Also, your anchor needs a hash to prevent it from trying to resolve a url

jsFiddle

HTML

<ul>
    <form enctype="multipart/form-data" action="" method="post">
        <li>Choose a file to upload:</li>
        <li><input name="uploadedfile" type="file" size="40" /></li>
        <li><a href="#" id="add-more-files">Add file upload box</a></li>
        <li><input type="submit" value="Upload File" /></li>
    </form>
</ul>

JS

$(function () {
   //clone file upload box
   $('#add-more-files').click(function() {
      var cloned = $(this).parent().prev().clone();
      cloned.val(null);
      $(cloned).insertBefore($(this).parent());
   });
});

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

Comments

1

It looks like you're trying to select something that doesn't exist. $('#add-more-files').prev() will be an empty jQuery object. $.prev() selects the previous sibling, of which there are none given the selector you've supplied.

I believe you want something like $(this).parent().prev().clone()

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.