Home > Net >  Adding a number with a plus button
Adding a number with a plus button

Time:02-07

I want to make a button that will ad a number to existing field. My code:

HTML:

<div >
    <div ><div>10</div></div>
    <div ><img src="images/plus.png" alt="Plus"></div>
    <div ><img src="images/minus.png" alt="Minus"></div>
    <input type="hidden" name="register-str" value="10">
</div>

JAVASCRIPT:

$(document).ready(function() {
    $('.str .stat-plus img').click(function() {
        var val = $('.str-img div').val();
        var new_val = parseInt($('.str-img div').val(),10)   1 ;
        $('.str-img div').val(new_val);
    });
});

CodePudding user response:

Use .text() to the get the div's text instead of .val() which is use to get the value of an element. Try this. I've completed the function with both increment and decrement capabilities.

$(document).ready(function() {
    $('.stat-plus, .stat-minus', '.str').click(function() {
        var $display = $('.str-img div');
        var new_val = parseInt($display.text())   ($(this).is('.stat-plus') ? 1 : -1);
        $display.text(new_val);
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    <div ><div>10</div></div>
    <div ><img src="images/plus.png" alt="Plus"></div>
    <div ><img src="images/minus.png" alt="Minus"></div>
    <input type="hidden" name="register-str" value="10">
</div>

CodePudding user response:

The val method is primarily used to get the values of form elements such as input, select and textarea.

Instead of val method, you can use text or html method on $('.str-img div') element, like this:

$(document).ready(
    function() {
        $('.str .stat-plus img').click(function() {
            var val = $('.str-img div').html();
            var new_val = parseInt(val,10)   1 ;
            $('.str-img div').html(new_val);
        });
    }
);
<div >
  <div >
    <div>10</div>
  </div>
  <div ><img src="images/plus.png" alt="Plus"></div>
  <div ><img src="images/minus.png" alt="Minus"></div>
  <input type="hidden" name="register-str" value="10">
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

  •  Tags:  
  • Related