How to access JavaScript built elements using jQuery?

I wanted to create a file upload feature in my application. Normally my form contains 1 file field. But I want to let users to have more if they need. So I created it in this way:

HTML

<div class="att" id="c1">
    <input type="file" name="c1" size="200" /><br>
    <input type="button" value="Add more files" id="more" />
</div>

jQuery

$('#more').on('click',function(){
    q = $('.att').length;
    c = $('#c1').html();
    n = q + 1;
    f = c.replace('c1','c'+n);
    $('#c'+q).after('<div>'+f+'</div>');
})

You can see my codes live demo here.

Up to now, everything is working well. But the problem I have is accessing to new JavaScript built elements for naming them. I need to have file fields with names like c1, c2, c3, ... But all new created elements are getting their names as "c2". It seems my code has some problems to calculate length of ".att" elements because just one of them are HTML native element, and others built with JavaScript.

Do you have any idea?

Answers 1

  • $('#more').on('click', function() {
      var q = $('.att').length;
      c = $('[name="c1"]').clone().get(0).outerHTML;
      n = q + 1;
      f = c.replace('c1', 'c' + n);
      $('#c' + q).after('<div class="att" id="c'+n+'">' + f + '</div>');
    });
    input[type=file] {
      border: 1px solid silver;
      margin-bottom:5px;
      padding: 5px
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <div class="att" id="c1">
      <input type="file" name="c1" size="200" />
      <br>
    
    </div>
    <input type="button" value="Add more files" id="more" />


Related Articles