douzhong1730 2014-06-03 21:01
浏览 30
已采纳

根据使用javascript或PHP的输入自动减去没有按钮点击的数字

I have more than 2 inputs that can only accept numbers and there is a displayed number on the top. How could I subtract the numbers that I have entered just by changing the value on any of the input boxes? Please Help.

 <p id='Answer'> 100 </p>
 <input type='number' max='10' min='0' name='num1'>
 <input type='number' max='5' min='0' name='num2'>
  • 写回答

3条回答 默认 最新

  • dongmeiyi2266 2014-06-03 21:08
    关注

    Ok your question is a little ambiguous. Anyway I have assumed you want the following. You want the num1 to subtract automatically from num2 and be displayed in id='Answer'.

    Following is the code to that in jQuery.

    $(".sub").focusout(function() {
      $("#answer").html('');
      var num1 = $("#num1").val();
      var num2 = $("#num2").val();
      var answer = num1 - num2;
      $("#answer").html(answer);
    });
    

    You can view the demo here

    In case you want both input fields to subtract from 100. Following is the code.

    $(".sub").focusout(function() {
    $("#answer").html('');
    var num1 = $("#num1").val();
    var num2 = $("#num2").val();
    var answer = 100 - num1 - num2;
    $("#answer").html(answer);
    });
    

    And following is the link to demo

    Based on your question in last comment. Download jquery from here. Now include the downloaded script in your header. Or just use the following code.

    <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
    

    After you have included jquery you need to use your .focusout code like stated below

    <script type="text/javascript">
    $(document).ready(function() {
       $(".sub").focusout(function() {
         $("#answer").html('');
         var num1 = $("#num1").val();
         var num2 = $("#num2").val();
         var answer = 100 - num1 - num2;
         $("#answer").html(answer);
        });
    });
    </script>
    

    展开全部

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部