0

I'm trying to build a calculator that does some simple math based on a number you input and a radio button you select.

I want to pre-populate the number and pre-select the radio button and show a sample outcome.

When I hard code the value of the text field it works until I try and change the new number then my output value flashes correctly and goes away. I know this is almost working but I can't seem to finish it off.

My thought is maybe I should be pre-populating the text field using jQuery but I'm not sure.

$(function() {
$(".calculate").change(function(){
var valone = $('#ms').val();
var valtwo = $('input:radio[name=ValTwo]:checked').val();

var total = ((valone * 1) * (valtwo * 1));
$('#Total').text(total);
});
}); 

<form>
        <dl>
            <dt><label for="spending">Monthly Spending</label></dt>
            <dd><input name="ValOne" id="ms" type="text" value="2500"></dd>
            <br /><br />
            <dt><label for="balance">Is your balance typically<br />above $5,000?</label></dt>
            <dd>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                Yes <input name="ValTwo" type="radio" value=".02" class="calculate" checked='checked'>
                No  <input name="ValTwo" type="radio" value=".01" class="calculate">
            </dd>
        </dl>
        <div class="clear"></div>
        <input type="image" id="enter" value="open an account" src="images/btn-go.png">    
    </form>

<span  id="Total">50</span>
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • Not related to your problem. Using unary `+` operator is faster than `*`. See http://stackoverflow.com/questions/2665984/is-minus-zero-some-sort-of-javascript-performance-trick and http://www.jibbering.com/faq/faq_notes/type_convert.html#tcNumber – James Wiseman Oct 05 '10 at 12:59
  • Can you put this up somewhere that we can take a look. – Lazarus Oct 05 '10 at 13:03
  • I have it loaded up at http://maligndesign.com/calc/ – foroctfralion Oct 05 '10 at 15:19

2 Answers2

0

Changing your code to

function reCalc()
{
    var valone = $('#ms').val();
    var valtwo = $('input:radio[name=ValTwo]:checked').val();

    var total = ((valone * 1) * (valtwo * 1));
    $('#Total').text(total);
}

$('#ms').keyup(reCalc);
$('.calculate').change(reCalc);

will recalculate the total on each keypress in the spending field, and also on each change of the radio button.

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
0

Try to change

$('#Total').text(total);

to

$('#Total').html(total);
Tee Wu
  • 569
  • 2
  • 9