【问题标题】:How to multiply text box values with javascript如何将文本框值与 javascript 相乘
【发布时间】:2019-05-30 18:19:41
【问题描述】:

我想将两个文本框中的值相乘(txtBox1 应该包含一个整数值,txtBox2 应该包含一个浮点值)并将结果放在第三个文本框中。我的代码在下面,但它不起作用。 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')");

【问题讨论】:

  • 当两者非常相似时,很难选择正确的答案。我在 C# 代码中遇到了另一个问题。尽管文本框是这样创建的: TextBox txtBox1 = new TextBox();我需要做的也是为 ID 添加一个值,如下所示: txtBox1.ID = "txtBox1";感谢您的帮助!

标签: c# javascript asp.net


【解决方案1】:

你应该改变

var total = txt1 * txt2;

var total = txt1.value * txt2.value;

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

在您的行中,您自己使用.value 来设置参数;)

[编辑]

正如@Dan Dumitru 所说,您可以使用parseFloat/parseInt,但如果您的输入字段包含额外的文本、小数点前缺少的数字、指数符号等,这会更有用。

【讨论】:

    【解决方案2】:

    我认为您在获取文本框的 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')");
    

    【讨论】:

    • 而在使用 parseInt 时,您几乎总是希望传递指示基数的第二个参数:parseInt(txtBox1.value,10)
    • "如果只有一个参数,则根据数字的通用 JavaScript 语法检测数字基数。以 0x 或 -0x 开头的字符串被解析为十六进制;以 0 或 - 开头的字符串0 被解析为八进制数。所有其他字符串被解析为十进制数。”因此,如果您担心像 077 或 0023 这样的输入,是的,您应该使用第二个参数。但我不会打扰它。
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多