Kimberly Wright Kimberly Wright - 5 months ago 36
jQuery Question

jQuery addition and subtraction won't work properly

i have a fiddle here: https://jsfiddle.net/0br4crLe/2/

The goal here is to make each item for the + and - work independently.

Right now when you click on the + or - button on 1 item, it will affect all of the items from top to bottom. See screenshot below:

enter image description here

It must work independently. Let's say I click on the + button on 1 item, it must only work on that particular item w/o affecting the other items.

Here's my jQuery:

$('input[name="plus1"]').click(function(){
debugger;
var number_text = $('input[name="fname1"]').val();
if(number_text>=0){
number_text = Number(number_text);
number_text=number_text+1;
$('input[name="fname1"]').val(number_text);
}

});
$('input[name="minus1"]').click(function(){
debugger;
var number_text = $('input[name="fname1"]').val();
if(number_text>=1){
number_text = Number(number_text);
number_text=number_text-1;
$('input[name="fname1"]').val(number_text);
}

});


tried to work things, but doesnt work, any idea? can you show me the fiddle option to do it? Thanks!

Dar Dar
Answer

Not so clean but you can give each button a class (minus or plus), then call those using jQuery.

HTML:

      <input type="button" name="minus1" value="-" id="minus1" class="minus">
      <input type="text" name="fname1" value="2" class="value">
      <input type="button" name="plus1" value="+" id="plus1" class="plus">

Then use .prev() or .next() to get to the input textbox element and then its value.

JS:

$('.plus').click(function() {
  var number_text = $(this).prev(); // gets the input textbox element next to the plus button
  var number_value = number_text.val(); // gets the input textbox element's current value
  if (number_value >= 0) {
    number_value = Number(number_value);
    number_value = number_value + 1;
    number_text.val(number_value);
  }

});
$('.minus').click(function() {
  var number_text = $(this).next(); // gets the input textbox element next to the minus button
  var number_value = number_text.val(); // gets the input textbox element next to the minus button
  if (number_value >= 1) {
    number_value = Number(number_value);
    number_value = number_value - 1;
    number_text.val(number_value);
  }

});

https://jsfiddle.net/0br4crLe/3/

Comments