html - jquery on change event strange behaviour -


i m having form upload files using these tags

 <form id="uploadpic" action="../image_shout" enctype="multipart/form-data" method="post">     <input type="file" multiple="true" id="file1" class="choose-file" name="choose-file"/>     </form> 

now want on choosing file new file upload input should inserted.

i tried jquery using on change event handler using code -

$('.choose-file').on("change", function(e) {                    $(this).after("<input type=\"file\" multiple=\"true\" id=\"file1\" class=\"choose-file\" name=\"choose-file\" />");                 });  

to dismay got bonded first element of input field. on choosing files on subsequent inputs generated not add new input fields.

the fiddle here

to work had complicated -

$(document).ready(function() {     function add_input($t) {             $t.after("<input type=\"file\" multiple=\"true\" id=\"file1\" class=\"choose-file\" name=\"choose-file\" />");             $('.choose-file').on("change", function(e) {         var $t = $(this);                 add_input($t);     });         }  $('.choose-file').on("change", function(e) {            var $t = $(this);             add_input($t);         });    }); 

the fiddle here

any explanation , solution if can done in easier , cleaner way.

thanks

you'll need delegate event dynamic elements, , make sure id unique

$(document).ready(function () {     $('#uploadpic').on('change', '.choose-file', function (e) {         $('<input />', {             type     : 'file',             multiple : 'multiple',             id       : 'file' + ($('.choose-file').length + 1),             'class'  : 'choose-file',             name     : 'choose-file'         }).insertafter(this);     }); }); 

fiddle


Comments

Popular posts from this blog

PHPMotion implementation - URL based videos (Hosted on separate location) -

c# - Unity IoC Lifetime per HttpRequest for UserStore -

I am trying to solve the error message 'incompatible ranks 0 and 1 in assignment' in a fortran 95 program. -