views:

155

answers:

2

I would like to multiply the values from two text boxes (txtBox1 should contain an Integer value, txtBox2 should contain a Float value) and place the result in a third text box. My code is below, but it doesn't work. The javascript function is called, otherwise it fails. Can someone please help me to code this correctly :\ ? Thank you

       //the javascript function   
       function CalculateTotal(id1, id2) {
            var txt1 = document.getElementById(id1);
            var txt2 = document.getElementById(id2);

            var total = txt1 * txt2;
            document.getElementById("txtTotal").value = parseFloat(total);
        }

        //c# code, programmatically adding attribute
        txtBox1.Attributes.Add("onBlur", "CalculateTotal('txtBox1, txtBox2')");
+4  A: 

You should change

var total = txt1 * txt2;

to

var total = txt1.value * txt2.value;

txt1 and txt2 are the input element itself, not the value they contain.

In your line further down you use .value yourself to set the parameter ;)

[Edit]

As noted by @Dan Dumitru you can use parseFloat/parseInt, but this is more useful if your input fields contains additional text, missing digits before a decimal marker, exponential notation etc.

Mikael Svenson
+4  A: 

I think you also have a problem with getting the text boxes' IDs, having separate apostrophes for each variable:

//the javascript function   
function CalculateTotal(id1, id2) {
    var txt1 = document.getElementById(id1);
    var txt2 = document.getElementById(id2);

    var total = parseInt(txt1.value) * parseFloat(txt2.value);
    document.getElementById("txtTotal").value = total;
}

//c# code, programmatically adding attribute
txtBox1.Attributes.Add("onblur", "CalculateTotal('txtBox1', 'txtBox2')");
Dan Dumitru
And when using parseInt you almost always want to pass the second parameter indicating the base: parseInt(txtBox1.value,10)
HS
"If there is only one argument, the number base is detected according to the general JavaScript syntax for numbers. Strings that begin with 0x or -0x are parsed as hexadecimals; strings that begin with 0 or -0 are parsed as octal numbers. All other strings are parsed as decimal numbers." So if you're worried about inputs like 077 or 0023, yes, you should use the second parameter. But I wouldn't bother with it.
Dan Dumitru