Search code examples
jqueryattributesclonecss-selectors

Changing multiple attributes on multiple selectors does not work?


I am trying to learn and understand jquery and I'm having some trouble with multiple selectors. I can't seem to update the attributes, id and name, when I have a cloned jquery object in one of my selectors.

HTML

<div class="File">
    Choose a file:
<input id="File0" name="File0" type="file" />
</div>

<input id="AddFile" type="button" value="Add a File" />

<div id="div1"></div>
<div id="div2"></div>

Jquery

 var lastId = 0;
$(document).ready(function () {
        $("#AddFile").click(function () {
            var id = "File" + ++lastId;
            var myInput = $(".File:first").clone(true);

            // Why doesn't this update the input of type 'file' 
            // on the page when selecting multiple selectors?
            $("input:file", myInput ).attr({ id: id, name: id });

             //But if you have omit 'myInput' like this, it will work.
             // $("input:file").attr({ id: id, name: id });

             //This will also work
             //$('#div1, #div2').attr({ id: id, name: id });

             //If I add in the cloned object at the end, it will only
             //modify the input element and not the div with class=File
             //imyInput.insertBefore("#AddFile");
        });
 });

When I run the code above. No matter how many times I click on the AddFile button, the dom still reads id="File0" name="File0" type="file"."


Solution

  • This is not valid in jQuery:

    $("input:file", myInput ).attr({ id: id, name: id });
    

    In the above, myInput will change attributes, but the first input element will not change.

    First add the cloned object to the DOM:

    var myInput = $(".File:first").clone(true).appendTo("body");
    

    Then change the attributes:

    myInput.attr({ id: id, name: id });