最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery increment or decrement variable by 1 - Stack Overflow

programmeradmin5浏览0评论

I have simple plus and minus button on either side of input field as in the code below

<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />&nbsp;
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />&nbsp;
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />

with aim to add or subtract rooms while adding rooms and the jquery functions as

function add() {
    var a = $("#noOfRoom").val();
    a++;
    if (a => 1) {
        $("#subs").removeAttr("disabled");
    }
    $("#noOfRoom").val(a);
};

function subst() {
    var b = $("#noOfRoom").val();
    if (b.length > 0 && b >= 1) {
        b--;
        $("#noOfRoom").val(b);
    }
    else {
        $("#subs").attr("disabled", "disabled");
    }
};

but the following problems are shown

  1. when i click on subtract (-) button at the initial phase -1 is shown in input box, where by default the subtract (-) button should be disabled to make rooms number negative.
  2. Each time when I click on PLUS or MINUS buttons the numbers are added or subtracted by 2. How could I solve it?

I have simple plus and minus button on either side of input field as in the code below

<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%" onclick="subst()" />&nbsp;
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="<?php echo set_value('noOfRoom'); ?>" name="noOfRoom" />&nbsp;
<input type="button" value="+" id="adds" onclick="add()" class="btn btn-default" />

with aim to add or subtract rooms while adding rooms and the jquery functions as

function add() {
    var a = $("#noOfRoom").val();
    a++;
    if (a => 1) {
        $("#subs").removeAttr("disabled");
    }
    $("#noOfRoom").val(a);
};

function subst() {
    var b = $("#noOfRoom").val();
    if (b.length > 0 && b >= 1) {
        b--;
        $("#noOfRoom").val(b);
    }
    else {
        $("#subs").attr("disabled", "disabled");
    }
};

but the following problems are shown

  1. when i click on subtract (-) button at the initial phase -1 is shown in input box, where by default the subtract (-) button should be disabled to make rooms number negative.
  2. Each time when I click on PLUS or MINUS buttons the numbers are added or subtracted by 2. How could I solve it?
Share Improve this question edited Feb 5, 2016 at 8:50 Rory McCrossan 338k41 gold badges320 silver badges351 bronze badges asked Feb 5, 2016 at 8:47 user3518741user3518741 5
  • 3 You have wrong expression, => should be >=. – Bhojendra Rauniyar Commented Feb 5, 2016 at 8:50
  • @BhojendraNepal corrected that, and still the same problem. – user3518741 Commented Feb 5, 2016 at 8:54
  • Your code works fine, however I suggest not using inline onclick= handlers with jQuery and use prop and not attr for properties: jsfiddle/k7nyv84b/1 – iCollect.it Ltd Commented Feb 5, 2016 at 9:00
  • Also the if (a => 1) { is unnecessary as the value can never go below 0 – iCollect.it Ltd Commented Feb 5, 2016 at 9:04
  • Thank you all for your response, but when I tried with the provided fiddles, I got it working on fiddle, but the same as my problem in my project. UPDATE When I rename function to anything that is not present in my project, the code seems working. – user3518741 Commented Feb 5, 2016 at 9:37
Add a ment  | 

6 Answers 6

Reset to default 4

Update add a fiddle https://fiddle.jshell/n7ug52dr/

Each time you click will only add and sub by 1, and it never show the -1


You can edit code like this:

function add() {
    var a = $("#noOfRoom").val();
    a++;
    if (a && a >= 1) {
        $("#subs").removeAttr("disabled");
    }
    $("#noOfRoom").val(a);
};

function subst() {
    var b = $("#noOfRoom").val();
    // this is wrong part
    if (b && b >= 1) {
        b--;
        $("#noOfRoom").val(b);
    }
    else {
        $("#subs").attr("disabled", "disabled");
    }
};

Moving ments to answer as no-one took onboard the suggestions:

  • I suggest not using inline onclick= handlers with jQuery. They separate the event handler from the event code for no reason and don't allow for the extra features of jQuery event handlers.
  • Use prop and not attr for DOM element properties (like disabled). This has the extra advantage of taking a boolean value.
  • You can then simply use !a to control the disabled state (as you are only checking for 0).
  • As a good habit always select DOM elements once and save the selector.

e.g.

$('#adds').click(function add() {
    var $rooms = $("#noOfRoom");
    var a = $rooms.val();
    a++;
    $("#subs").prop("disabled", !a);
    $rooms.val(a);
});
// Set initial disabled state
$("#subs").prop("disabled", !$("#noOfRoom").val());

$('#subs').click(function subst() {
    var $rooms = $("#noOfRoom");
    var b = $rooms.val();
    if (b >= 1) {
        b--;
        $rooms.val(b);
    }
    else {
        $("#subs").prop("disabled", true);
    }
});

JSFiddle: https://jsfiddle/k7nyv84b/4/

Here you go, champ! Made your code a little cleaner as well

See the working example below

$(function(){

  $('#adds').on('click',add);
  $('#subs').on('click',remove);

});


function add(){

  var input = $('#noOfRoom'),
      value = input.val();
      
  input.val(++value);
  
  if(value > 0){
    $('#subs').removeAttr('disabled');
  }

}


function remove(){

   var input = $('#noOfRoom'),
       value = input.val();
      
   if(value > 0){
     input.val(--value);
   }else{
     $('#subs').attr('disabled','disabled');
  }

}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="-" id="subs" class="btn btn-default pull-left" style="margin-right: 2%"/>&nbsp;
<input type="text" style="width: 410px;text-align: center; margin: 0px;" class="onlyNumber form-control pull-left" id="noOfRoom" value="0" name="noOfRoom" />&nbsp;
<input type="button" value="+" id="adds" class="btn btn-default" />

take a look at this solution

<input type="button" value="-" id="subs" onclick="subst()" disabled>
 <input type="text" id="noOfRoom">
<input type="button" value="+" id="adds" onclick="add()">



function add() {
var a = $("#noOfRoom").val();
a++;
if (a >= 1) {
    $("#subs").removeAttr("disabled");
}

alert(a);
$("#noOfRoom").val(a);
}

function subst() {
var b = $("#noOfRoom").val();
if (b.length > 0 && b >= 1) {
    b--;
  alert(b);
    $("#noOfRoom").val(b);
}
else {
    $("#subs").attr("disabled", "disabled");

}

//alert('works well'); }

The simplest way is to use DOM to navigate through elements and get its current value and then increase/decrease them.

I extended the code to make sure when minus button is clicked value isn't reduce below zero.

<input type="button" value="-" class="qtyminus" field="quantity"> 
<input type="number" class="input-lg" id="quantity" name="quantity" value="1" min="1" style="padding:0px;height:30px;">
<input type="button" value="+" class="qtyplus" field="quantity">
<input type="submit" name="add" id="add" class="btn btn-large btn-border btn-dark" value="GET IT NOW" style="opacity: 1;">


<script src="https://ajax.googleapis./ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function(){
    // This button will increment the value
    $('.qtyplus').click(function(e){
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('input[name='+fieldName+']').val());
        // If is not undefined
        if (!isNaN(currentVal)) {
            // Increment
            $('input[name='+fieldName+']').val(currentVal + 1);
        } else {
            // Otherwise put a 0 there
            $('input[name='+fieldName+']').val(0);
        }
    });
    // This button will decrement the value till 0
    $(".qtyminus").click(function(e) {
        // Stop acting like a button
        e.preventDefault();
        // Get the field name
        fieldName = $(this).attr('field');
        // Get its current value
        var currentVal = parseInt($('input[name='+fieldName+']').val());
        // If it isn't undefined or its greater than 0
        if (!isNaN(currentVal) && currentVal > 0) {
            // Decrement one
            $('input[name='+fieldName+']').val(currentVal - 1);
        } else {
            // Otherwise put a 0 there
            $('input[name='+fieldName+']').val(0);
        }
    });
});
          
</script>

<button onClick="myfun()">+</button>
<!--<button onClick="myfun()" id="pluse">+</button>-->
<input type="text" id="pluse" >
<button onClick="myfun1()">_</button>


var a = 0;
function myfun(){
    a++;
    document.getElementById('pluse').value = a;
    //document.getElementById('pluse').innerHTML = a;
}
function myfun1(){
    a--;
    document.getElementById('pluse').value = a;
}
发布评论

评论列表(0)

  1. 暂无评论