Search code examples
jqueryformsclonefield

jQuery clone form field till maximum count


I am allowing user to add more field on click. But I want allow user to add maximum 4 fields. How can I alter this code to make it works. So when user creates total 4 elements than Add Photo button should turns to disable mode or hide. I prefer disable but if it is hard than hide also would be fine.

Jquery code:

jQuery(document).ready(function(){

   jQuery('#add-photo-button').click(function(){

        var current_count = jQuery('input[type="file"]').length;
        var next_count = current_count + 1;

        jQuery('#file-upload').prepend('<input type="file" name="photo_' + next_count + '" />');    

   });

});

HTML Code:

<form id="file-upload" action="#" method="GET" enctype="multipart/form-data">
    <div id="image-uploader-box" class="group">           
        <div id="forms" class="add-photo-fields">
            <input type="submit" value="Upload" />
            <input type="button" id="add-photo-button" class="add-photo-button" value="Add Photo"/>
        </div>
    </div> 
</form>

Thanks a lot


Solution

  • try this

    Demo

    jQuery(document).ready(function(){
      $cnt = 1;
      jQuery('#add-photo-button').click(function(){
       if($cnt == 4){
         //$('#add-photo-button').hide();
         $('#add-photo-button').prop('disabled', true);
       }
       $cnt++;
       var current_count = jQuery('input[type="file"]').length;
       var next_count = current_count + 1;
       jQuery('#file-upload').prepend('<input type="file" name="photo_' + next_count + '"  />');    
    
     });
    
    });