Garrett Garrett - 2 months ago 6
HTML Question

jQuery: Help re-activating button when limit is reduced

Currently I have built this simple application where you can add input boxes using a button. Then when the limits reached it prevents you adding more and it has a maximum input box message displayed. You also have the option to remove the boxes you've just added. The problem I'm having is I don't know how to re-active the add button when the user has removed some of the input boxes. I'm pretty new to jQuery so if theres a better way of writing the code then I'm all ears. I have re-created my example in JSfiddle: http://jsfiddle.net/jTh3v/367/.

The way I was looking to do it was when you clicked a remove button like such:

$("#remove").click(function(e){
$("#MAX").hide('<p>MAX</p>');
});

Answer

Inside your

$("#Input").on("click","#remove", function(e){

In order to reenable the add button you need:

$("#add").prop("disabled",false);

To remove the MAX message you can:

$("#MAX p:first").remove();

The updated fiddle.

Here the snippet:

$(document).ready(function() {
  var max_fields = 5;
  var x = 1;

  $("#add").click(function(e){
    e.preventDefault();
    if(x < max_fields){
      x++;
      $("#Input").append(
        '<div><input type="text" name="mytext[]"/><a href="#" id="remove">Remove</a></div>'
      );
    } else if(x == max_fields){
      $("#MAX").append('<p>MAX</p>');
      $(this).prop("disabled",true);
    }
  });

  $("#Input").on("click","#remove", function(e){
    e.preventDefault(); 
    x--;
    $("#add").prop("disabled",false);
    $(this).parent('div').remove(); 
    $("#MAX p:first").remove();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<button id="add">Add</button><hr>
<input type="text" name="mytext[]">
<div id="Input"></div>
<div id="MAX"></div>

Comments