tags:

views:

16

answers:

1

I found this code somewhere else on this site. I'm in the process of adapting it, but since I'm new to Javascript, I have no idea how to get the total sum to appear only after you click some kind of "Calculate" button. I've tried to do it myself, but the numbers calculate automatically, and I need a solution so that it doesn't do that.

<script type="text/javascript">
    function DisplayPrice(price){
                    var val1 = 0;
                    for( i = 0; i < document.form1.price.length; i++ ){
                            if( document.form1.price[i].checked == true ){
                                    val1 = document.form1.price[i].value;
                            }
                    }

                    var val2 = 0;
                    for( i = 0; i < document.form2.price2.length; i++ ){
                            if( document.form2.price2[i].checked == true ){
                                    val2 = document.form2.price2[i].value;
                            }
                    }

                    var sum=parseInt(val1) + parseInt(val2);
        document.getElementById('totalSum').value=sum;
    }
</script>

Choose a number:

159
259

Choose another number:<br>
<form name="form2" id="form2" runat="server">
    <br>
    <input id="rdo_1" type="radio" value="345" name="price2" onclick="DisplayPrice(this.value);">345
    <br>
    <input id="rdo_2" type="radio" value="87" name="price2" onclick="DisplayPrice(this.value);">87
    <br>
</form>

A: 

Put onclick="DisplayPrice();" in another Calculate button (input type button or submit), remove onclicks from the two radio buttons, and modify DisplayPrice to sum the values of the form elements.

Detect
"modify DisplayPrice to sum the values of the form elements." Can you show me how to do this part?
Lola
basically something like document.getElementById('totalSum').value = parseInt(document.getElementById('rdo_1').value) + parseInt(document.getElementById('rdo_2').value)
Detect
OK, I got it working. The code you gave me didn't work. It kept adding the entire sum of form 1 and form 2, so I used this instead (in case this helps someone else in the future): var sum=parseInt(val1) + parseInt(val2); document.getElementById('totalSum').value=sum; } </script> And then for the button it's: <input type="button" value="Calculate" onclick="DisplayPrice();"> <input type="text" name="totalSum" id="totalSum" value="" size="2" onclick="DisplayPrice();"> Thanks!
Lola