简体   繁体   中英

jQuery - Increase/Decrease value of span

I have this:

            <ul class="deposit" style="float:left;list-style-type:none;">
                <a href="javascript:void(0)" id="inc"><li class="first">+</li></a>
                <a href="javascript:void(0)" id="dec"><li class="second">-</li></a>
            </ul>

<div class="left deposit_amount">$<span id="amountSpan"></span></div>

I want to do, so whenever I click the #inc the #amountSpan will increase by 5. And whenever the #dec is clicked, the value will be decreased by 5. I also wish to have, so the value cannot go below 0.

Currently I have this:

  $(function(){
    $("#inc").click(function(){
      $("#amountSpan").val( Number($("#amountSpan").val()) + 5 );
    });
    $("#dec").click(function(){
      $("#amountSpan").val( Number($("#amountSpan").val()) - 5 );
    });
  });

But this does not work. How can I obtain this?

Thanks in advance.

Update:

I try to set a max number, with this:

$("#inc").click(function(){
  $("#amountSpan").text( Math.max(20, Number($("#amountSpan").text()) + 5) ) 
});

But it just goes past 20.

Instead of .val() (which is for form input elements), use .text() . Oh, and when you're incrementing, you'll need to make sure the value is forced to be a number first. (oh wait you already are :-)

$(function(){
    $("#inc").click(function(){
      $("#amountSpan").text( Number($("#amountSpan").text()) + 5 );
    });
    $("#dec").click(function(){
      $("#amountSpan").text( Number($("#amountSpan").text()) - 5 );
    });
  });

To keep the amount greater than or equal to zero:

    $("#amountSpan").text( Math.max(0, Number($("#amountSpan").text()) - 5) )

for date also you can in year as per below example

<script type="text/javascript">
    function increment1(myInput) {

        myInput.value = Math.min(31, (+myInput.value + 1) || 0);
    }
    function decrement1(myInput) {
        myInput.value = Math.max(1, (myInput.value - 1) || 0);
    }
    /*myInput.value = (myInput.value - 1) || 0;*/

</script>

<img src="Icalorieimage/account/increase_menu.png"
     width="25" height="20" id="target" style="float:left; cursor:pointer;" align="left"
     onclick="increment(this.parentNode.getElementsByTagName('input')[0]);"/>
<img src="Icalorieimage/account/decrease_menu.png" width="25" height="20" style="float:left; cursor:pointer;"
     align="left"
     onclick="decrement(this.parentNode.getElementsByTagName('input')[0]);"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM