jQuery的计算问题 [英] jquery calculation question

查看:76
本文介绍了jQuery的计算问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

<div>
    <input id="number" type="text" />

    <select id="Selection" name="D1"> 
    <option>Plus 1</option>
    <option>Minus 1</option>
    </select>

    <input id="result" type="text" />
    </div>

如何基于使用jQuery从选择控件中选择的值来计算输入到输入数字"中的任何数字? 例如,我想在输入数字"中输入5,如果我选择加号1",则在数字上加1,并在结果"输入中显示结果.如果选择减1",则将进行减法并显示新结果. 谢谢.

How could I calculate any number entered into the input "number" based on the value chosen from the select control using jQuery? For example I would like to enter 5 in the input "number" and if I choose "Plus 1" then add 1 to the number and show the result in the "result" input. If I choose "Minus 1" then I will do a substraction and show the new result. thank you.

推荐答案

您可以这样做:

$('#Selection').change(calc); //update result when changing the number
$("#number").keyup(calc);     //update result when select changes

function calc() {
  $('#result').val(
    parseInt($('#number').val(), 10) + parseInt($("#Selection").val(), 10)
  );
}

在此处尝试,重要的部分是

Give it a try here, the important part is the parseInt() your input (you should also add a numbers-only filter, etc.) Otherwise .val() from either input is a string, think of it this way:

  • 1 + 1 == 2
  • "1" + "1" = "11"
  • 1 + 1 == 2
  • "1" + "1" = "11"

这篇关于jQuery的计算问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆