Kesiena Sowho Kesiena Sowho - 3 months ago 9
jQuery Question

Set a limit to upload box onClick jquery

I have the following code to add a simple upload box, however, I want to limit the number of uploads onClick of + . How can I add this to the addFile function? I know I need to add a counter of sorts and put the query in an if loop to deny access if the + button is clicked more than 5 times. But how do I do this in jquery?

<div style="overflow: hidden">
<table class="adminformlist" id="uploading">
<tr><td align="left">Upload Images(Maximum of 5 images):
<input type="hidden" size="40" class="inputbox" value="" id="getyoutube" name="youtubevalue">
<input type="hidden" size="40" class="inputbox" value="" id="getyoutubeurl" name="youtubevalueurl">
</td>
<td></td>
</tr>
<tr><td><input type="file" name="images[]"></td>
<td><a href="#" class="button" onclick="return addFile(this)">+</a></td>
</tr>
</table>
</div>
<script type="text/javascript">

function addFile(el){
jQuery(el).parent().append('<a href="#" class="button" onclick="return removeFile(this)">x</a>');
jQuery(el).remove();
jQuery("#uploading").append('<tr><td><input type="file" name="images[]"></td><td><a href="#" class="button" onclick="return addFile(this)">+</a></td></tr>');
return false;
}
</script>

Answer

Try this,

function addFile(el){
  var allowedNumberofTR = 6;
  if($('#uploading tr').length < allowedNumberofTR){
      //your code
  }
}

Remind you, since upload already has a tr, allowedNumberofTR should always be +1;

function addFile(el){
        if($("#uploading tr").length < 6){
        jQuery(el).parent().append('<a href="#" class="button" onclick="return removeFile(this)">x</a>');
        jQuery(el).remove();
        jQuery("#uploading").append('<tr><td><input type="file" name="images[]"></td><td><a href="#" class="button" onclick="return addFile(this)">+</a></td></tr>');
        return false;
          }
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="overflow: hidden">
    <table class="adminformlist" id="uploading">
        <tr><td align="left">Upload Images(Maximum of 5 images):
            <input type="hidden" size="40" class="inputbox" value="" id="getyoutube" name="youtubevalue">
            <input type="hidden" size="40" class="inputbox" value="" id="getyoutubeurl" name="youtubevalueurl">
            </td>
            <td></td>       
        </tr>   
        <tr><td><input type="file" name="images[]"></td>
            <td><a href="#" class="button" onclick="return addFile(this)">+</a></td>
        </tr>
    </table>
    </div>