Kishan Patel
Kishan Patel

Reputation: 509

input with plus and minus button

I've created the input box with plus and minus button, to increase and decrease the value of input box while clicking the button.

I'm adding attribute 'disabled' to minus button when input value is set to zero, but the problem is that when page loads the input has value zero by-default but i need to click the minus button one time to add the attribute 'disabled' which is not i'm looking for, what i want is when the value of input is zero, i want minus button to have attribute set to be disabled by default and when i click the plus button it'll remove the 'disabled' attribute form minus button.

Even i tried adding attribute on button with window load but with no luck like this:

$( window ).load(function() {
  $('.minus').attr('disabled', true)
})

Here's the jsFiddle link for the same.

Hope you understand this. Thanks in advance for the help.

Upvotes: 1

Views: 3756

Answers (3)

Milan Chheda
Milan Chheda

Reputation: 8249

Here is the working code for you. I just added a function which gets called on document.ready and on every click of + or - sign:

$(".plus").click(function(e) {
  e.preventDefault();
  var $this = $(this);
  var $input = $this.siblings('input');
  var value = parseInt($input.val());
  if (value < 30) {
    value = value + 1;
  } else {
    value = 30;
  }
  $input.val(value);
  checkAndDisable();
});

$(".minus").click(function(e) {
  e.preventDefault();
  var $this = $(this);
  var $input = $this.siblings('input');
  var value = parseInt($input.val());
  if (value > 1) {
    value = value - 1;
    $(this).removeAttr('disabled');
  } else {
    value = 0;
    $(this).attr('disabled', true);
  }
  $input.val(value);
  checkAndDisable();
});

$(document).ready(function() {
  checkAndDisable();
});

$("#inputField").on('change', function(){
  if($(this).val() <= 0)
    $(this).val(0);
  checkAndDisable();
});

function checkAndDisable() {
  $(".minus").removeAttr('disabled');
  if ($("#inputField").val() == 0) {
    $(".minus").attr('disabled', true);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="change_qty minus cursor_hover">&#45;</button>
<input type="number" style="height:26px;width:40px;text-align:center;" value="0" id="inputField">
<button class="change_qty plus cursor_hover">&#43;</button>

Upvotes: 1

RAUSHAN KUMAR
RAUSHAN KUMAR

Reputation: 6006

use document.ready to disable the button as

$(document ).ready(function() {
   $('.minus').attr('disabled', 'disabled')
})

Upvotes: 0

Nir Tzezana
Nir Tzezana

Reputation: 2342

Just add the disabled property on the input

<button disabled class="change_qty minus cursor_hover">&#45;</button>

Upvotes: 4

Related Questions