I need to be able to add a decimal from input to a decimal in a div. Here’s my code below. Right now, it’s just concatenating the two number next to each other. Thanks.
EDITED: Working code
<div id="addme">5.01</div>
<input type="text" id="anumber" value="">
<button id="add">Add Number to div</button>
$('#add').click(function() {
var number = parseFloat($('#anumber').val()) || 0;
//alert(number);
$('#addme').html(function(i, val) {
return (parseFloat(val) + number).toFixed(2);
});
});
Old Non-Working Code Below:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<div id="addme">5.01</div>
<input type="text" id="anumber" value="" />
<button id="add">Add Number to div</button>
<script type="text/javascript">
$('#add').click(function(){
var number = $('#anumber').val();
if(number=='undefined' || number==''){
var number=0;
}
//alert(number);
$('#addme').html(function(i, val) {return val*1+number });
});
</script>
Since you’re dealing with decimal numbers, use
parseFloat():http://jsfiddle.net/mblase75/47t7x/
UPDATE
Since you might introduce floating-point math errors (try inputing “0.6”), you should round it to a suitable number of decimal places before returning (2 if dealing with dollars and cents; 7 or more if dealing with other measurements):
http://jsfiddle.net/mblase75/47t7x/1/