uneeb meer uneeb meer - 4 months ago 18
jQuery Question

add percentage of value to a result

i want to calculate the percentage from a entered field.The first field will have a static value in the second field the user should enter a percentage value and this code should get the first value(static) calculate the percentage entered by the user according to the first static value and add that final value to the final result that is total.Here is some of the code i done but this is just basically adding two numbers whereas i want to add the percentage of second field entered by the user to the first one and display it in the final total title

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>
<body>
<input style="max-width: 100px; type="number" min="0" type="text" id="quantity1" value="100" />
<input style="max-width: 100px; type="number" min="0" type="text" id="quantity2" />

<h5 class="total" id="total" value="$123"></h5>

</body>
<script>
$('#quantity2').on('keyup',function(){

var val=$('#quantity1').val();
alert(val);
//alert(val);
var tot = +$(this).val()+ +$('#quantity1').val() ;
alert(tot);
$('.total').html("$"+tot);
});
</script>
</html>

Answer

Try this:

$('#quantity2').on('change',function(){ // use .change() event instead of keyup
    var val1 = parseInt($('#quantity1').val()); // use parseInt() to convert string to integer value
    var val2 = parseInt($(this).val());
    var tot = val1 + (val1 * (val2 / 100)); // it will add percentage value to first value
    console.log(tot);
    $('.total').html("$"+tot);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input style="max-width: 100px;" type="number" min="0" type="text" id="quantity1" value="100" />
<input style="max-width: 100px;" type="number" min="0" type="text" id="quantity2" />

<h5 class="total" id="total" value="$123"></h5>

Comments