Click here to Skip to main content
15,895,667 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
How will I add the value of my checkbox to the value in my textbox? If the checkbox is checked, then it's value is added to the stotal, if not it will be ignored?

HTML
HTML
<input type="text" id="sff" value="10.57"/>
<input type="text" id="osf" value="100.25"/>
<input type="checkbox" id="cb1" value="35.00"/>
<input type="text" id="total"/>


JavaScript
function subtotal(){
	var a = $("#sff").val();
	var b = $("#osf").val();
	
	var stotal = parseFloat(a, 10)+ parseFloat(b, 10)+ parseFloat(cbtotal, 10);
    $('#total').val('$' + stotal.toFixed(2));
}
Posted

Try this:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>

<input type="text" id="sff" value="10.57" >
<input type="text" id="osf" value="100.25" >
<input type="checkbox" id="cb1" value="35.00">
<input type="text" id="total" >

<script>
$('#cb1').click(function(){
	var a = $("#sff").val();
	var b = $("#osf").val();
        var stotal = parseFloat(a)+ parseFloat(b);
    
    if($(this).is(':checked')){
       stotal = stotal + parseFloat($('#cb1').val());
    }

    $('#total').val('$' + stotal.toFixed(2));
})

</script>
</body>
</html>
 
Share this answer
 
JavaScript
function subtotal() {
    var a = $("#sff").val();

    var b = $("#osf").val();
    var c = 0;
    if ($('#cb1').is(":checked")) {
        c = parseFloat($("#cb1").val(), 10);
    }
    var stotal = parseFloat(a, 10) + parseFloat(b, 10) + c ;

    $('#total').val('$' + stotal.toFixed(2));
}
 
Share this answer
 
C#
//If the checkbox is checked, then it's value is added to the stotal, if not it will be blank.

function subtotal(){
    var a = $("#sff").val();
    var b = $("#osf").val();

    var stotal = parseFloat(a, 10)+ parseFloat(b, 10);
    $('#total').val('$' + stotal.toFixed(2));
}

$(document).ready(function(e){
    $('#cb1').change(function() {
        $('#total').val('');
        if($(this).is(":checked")) {
            subtotal();
        }
    });
});
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900