Ravi kumar Ravi kumar - 7 months ago 12
Javascript Question

Text box value don't become negative values



$(document).ready(function() {
var label = parseInt($("#label1").html());
alert(label);
$("#Incre").click(function() {
$("#number").val(parseInt($("#number").val()) + label);
});
$("#Decre").click(function() {
$("#number").val(parseInt($("#number").val()) - label);
});
});

<label id='label1'>50</label>
<input id='number' value=0></input>
<button id='Incre'>Incre</button>
<button id='Decre'>Decre</button>





i have this code it's working. but when textbox value is Zero . if i click on the decrement button the textbox value is become negitive values. how to control this one.

Answer

You can use this code:-

<script>
$(document).ready(function () {
 var label=parseInt($("#label1").html());
 alert(label);
            $("#Incre").click(function () {          
                $("#number").val(parseInt($("#number").val())+label);    
            });
            $("#Decre").click(function () { 
                var final_number = parseInt($("#number").val())-label;
                if(final_number>=0) {
                    $("#number").val(parseInt($("#number").val())-label);    
                }

            });
});
</script>
<label id='label1'>50</label>
<input id='number' value=0></input>
<button  id='Incre'>Incre</button>
<button  id='Decre'>Decre</button>