2010-08-20 23 views
1

我想将两个文本框中的值相乘(txtBox1应该包含整数值,txtBox2应该包含浮点值),并将结果放在第三个文本框中。我的代码在下面,但它不起作用。 javascript函数被调用,否则失败。有人可以帮助我正确地编码:\?谢谢如何将文本框值与javascript相乘

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

很难选择一个正确答案时都非常相似。还有一个问题是我在C#代码中遇到的问题。虽然文本框是这样创建的:TextBox txtBox1 = new TextBox();我需要做的还是为ID添加一个值,如下所示:txtBox1.ID =“txtBox1”;感谢您的帮助! – brookmarker 2010-08-20 14:09:44

回答

5

你应该改变

var total = txt1 * txt2; 

var total = txt1.value * txt2.value; 

txt1txt2是输入元素本身,而不是它们所包含的值。

在你行进一步下跌你用.value自己设置参数;)

[编辑]

正如@丹杜米特鲁注意,您可以使用parseFloat/parseInt,但如果这是比较有用的输入字段包含额外的文本,在小数点前标记缺失数字,指数表示法等

4

我认为你也有一个问题,获取文本框的ID,每个变量具有单独的撇号:

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

当使用parseInt时,您几乎总是要传递第二个参数来指示基数:parseInt(txtBox1.value,10) – 2010-08-20 07:47:28

+1

“如果只有一个参数,则根据数字的一般JavaScript语法检测数字基数。以0x或-0x开始的数据将被解析为十六进制数字;以0或-0开头的字符串将被解析为八进制数字,其他所有字符串将被解析为十进制数字。所以如果你担心输入像077或0023,是的,你应该使用第二个参数。但我不会为此而烦恼。 – 2010-08-20 07:51:46

0

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')"); 
相关问题