Search code examples
javascriptappenddisable

stop/disable button after x amount of clicks


I have a table and you add rows using append. How do I stop or disable the button after 5 clicks or 5 append rows or any amount needed?

this is the code:

<input class="btn btn-primary" type="button" id="addbutton" value="More names" 
title="Add more names">

<script type="text/javascript">
  var i = 1; 
$("#addbutton").click(function () {
    $("#table").append('<tr>'+
     '<td><input class="form-control input-lg" type="text" name="name" required />'+ 
'</td>'+
    '<td><button type="button" class="removebutton" title="Remove this row">X</button> 
</td></tr>').find("input").each(function () {
});
i++;
});;

$(document).on('click', 'button.removebutton', function () {
    $(this).closest('tr').remove();
    return false;
});
</script>

Solution

  • You want to disable the button so there is an attribute in HTML, we can use that. The thing is, you should keep the value of i == 0 instead of 1.

    if(i == 5){
    $("#addbutton").attr('disabled','disabled');
    }
    

    This is how you can add a disabled attribute. Hope this would help you.