admin管理员组

文章数量:1390803

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: /

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>

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/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>
Share Improve this question asked May 31, 2012 at 23:38 Ben PatonBen Paton 1,4429 gold badges37 silver badges60 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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());
   });
});

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()

本文标签: javascriptClone file upload input filed in form with jqueryStack Overflow