开发者

How to multiply text box values with javascript

开发者 https://www.devze.com 2023-01-12 03:56 出处:网络
I would like to multiply the values from two text boxes (txtBox1 should contain an Integ开发者_Go百科er value, txtBox2 should contain a Float value) and place the result in a third text box. My code i

I would like to multiply the values from two text boxes (txtBox1 should contain an Integ开发者_Go百科er 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')");


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.


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')");


Replace to below code

  //the javascript function   
   function CalculateTotal(id1, id2) {
        var txt1 = document.getElementById("id1").value;
        var txt2 = document.getElementById("id2").value;
        var total = txt1 * txt2;
        document.getElementById("txtTotal").value = parseFloat(total);
    }

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

精彩评论

暂无评论...
验证码 换一张
取 消