Skip to content Skip to sidebar Skip to footer

Jquery Add/remove Divs Count, Track And Limit The Number Added/removed

I'm building a form that wants to capture a veteran's military deployment history. The form will default to one deployment. They can add up to 3. What I want to do is when you clic

Solution 1:

I'm not really sure what part you are stuck with, but this should do it:

http://jsfiddle.net/mmilleruva/9C6Lw/

var remaining = 2;

functionUpdateRemaining(isAdd){
if(isAdd){
    remaining = remaining - 1;
}
else{
    remaining = remaining + 1;
}

$('#remaining').text(remaining);
if(remaining == 0){
    $('#btn').prop("disabled",true);
} else{
       $('#btn').prop("disabled",false);
 }
}

$('.add').click(function () {
  $(this).before('<div>Location deployed: <input type="text" placeholder="Location deployed" size="15" > Date deployed: <input type="text" placeholder="Date deployed" size="15" > Date returned: <input type="text" placeholder="Date returned" size="15" >&nbsp;<span class="remove"><button type="button"> Remove </button> </span></div>');

UpdateRemaining(true);
});

 $(document).on('click', '.remove', function () {
  $(this).parent('div').remove();
   UpdateRemaining(false);      
});

Solution 2:

Try check the value of the span and validate in both .click() like:

  $('.add').click(function () {
      var $remind = parseInt($('#remaining').text());
      if($remind != 0){
      $(this).before('<div>Location deployed: <input type="text" placeholder="Location deployed" size="15" > Date deployed: <input type="text" placeholder="Date deployed" size="15" > Date returned: <input type="text" placeholder="Date returned" size="15" >&nbsp;<span class="remove"><button type="button"> Remove </button> </span></div>');
          $remind = $remind - 1
          $('#remaining').text($remind);

      }
      else{
      console.log('All added');
          $('.add').prop('disabled', true);
      }
  });

  $(document).on('click', '.remove', function () {
      $(this).parent('div').remove();
      var $remind = parseInt($('#remaining').text());
      $remind = $remind + 1
      $('#remaining').text($remind);
      if$('.add').prop('disabled', false);

  });

Live Demo

Solution 3:

You need to keep track of the deployments, which it seems like you're doing in the span. You can grab this by selecting $("#remaining").val() and then incrementing it and decrementing it based on the user clicks.

In your remove function, you increment the span, in your add function, you decrement said span. In your add function you have an if conditional to see if the val of the #remaining span is 0, if so, you disable add button $('.add).attr('enabled', false) or something like that. In your remove function, you do the same thing, except check to see if it has been incremented to 1, and then set enabled to true.

Post a Comment for "Jquery Add/remove Divs Count, Track And Limit The Number Added/removed"