【问题标题】:jquery multiply 2 textboxs then show the solutionjquery乘以2个文本框然后显示解决方案
【发布时间】:2013-02-16 19:51:00
【问题描述】:

我有这段代码不工作。我正在尝试将 2 个文本框相乘并显示解决方案,但是当我单击时它不显示任何内容。我到目前为止的代码是这样的......下面的代码有什么问题?

<script type="text/javascript">
    $('#AddProduct').click(function() {
        var totalPrice = $('#debt').val() * $('#income').val();
        $('#solution').val() = totalPrice;
    });
</script>

<form name="form" method="post" action="">
    <table>
        <tr>
            <td><input type="text" name="income" id="income" /></td>
            <td><input type="text" name="debt" id="debt" /></td>
            <td><input type="text"  id="solution"  name="solution" /> </td>
        </tr>
  </table>
</form>

【问题讨论】:

    标签: javascript jquery multiplication


    【解决方案1】:

    你的 jQuery 需要是:

    $('#AddProduct').click(function() {
       var totalPrice = parseInt($('#debt').val()) * parseInt($('#income').val()); // you can't multiply strings
       $('#solution').val(totalPrice); // This is how you use .val() to set the value.
    });
    

    【讨论】:

    • 我正要写。 +1。
    【解决方案2】:

    这是您设置解决方案文本框值的方式:

    $('#solution').val(totalPrice);
    

    另外,您的页面上是否真的有一个 id 为“AddProduct”的元素?

    【讨论】:

    • 是的,我在提交时这样做了,我只是让我的代码更干净,不小心把它删除了。
    【解决方案3】:
    var totalPrice = $('#debt').val() * $('#income').val();
    $('#solution').val(totalPrice);
    

    Demo

    【讨论】:

      【解决方案4】:

      之后,您将 jquery 添加到您的页面,如下所示

      <script src="http://code.jquery.com/jquery-latest.js"></script>
      

      您可以执行以下操作:

      $('#AddProduct').click(function() {
      var totalPrice = parseInt($('#debt').val(),10) * parseInt($('#income').val(),10);
      $('#solution').val(totalPrice);
      });
      

      您必须告诉它您想要目标输入的value。 此外,始终向parseInt 提供第二个参数(基数)。它试图过于聪明,如果不提供它会自动检测它,并可能导致意想不到的结果。

      提供10 假设您想要一个以 10 为基数的数字。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-10-26
        • 1970-01-01
        • 1970-01-01
        • 2011-04-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多