简体   繁体   English

jquery - 计算输入的多个数字

[英]jquery - calculate multiple numbers on input

I was able to convert the output text field into a plain text using below code:我能够使用以下代码将输出文本字段转换为纯文本:

 $("#input2,#input1").keyup(function() { $('#output').val($('#input1').val() * $('#input2').val()); $('#output').replaceWith(function() { return this.value || this.innerHTML; }); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" name="input1" id="input1" value="2"> <input type="text" name="input2" id="input2" value=""><br><br> You get back $<input type="text" name="output" id="output" value="">.00

But the issue is the script is only working for single digit numbers (0-9) and not multiple numbers.但问题是该脚本仅适用于单个数字 (0-9) 而不是多个数字。 How to make this work for multiple numbers.如何使其适用于多个数字。 Also how to make this dynamic.还有如何使这个动态。 Please advise.请指教。

You replace the #output input with the result of your first calculation.您用第一次计算的结果替换#output输入。 Meaning that it's not there any more (because it got replaced)这意味着它不再存在(因为它被替换了)

So for the second number there is nothing to replace, which means it stays the same.所以对于第二个数字没有什么可以替换的,这意味着它保持不变。

To change it: Update the value only and don't replace the whole element.更改它:仅更新值而不替换整个元素。

 $("#input2,#input1").keyup(function() { $('#output').val($('#input1').val() * $('#input2').val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <input type="hidden" name="input1" id="input1" value="2"> <input type="text" name="input2" id="input2" value=""><br><br> You get back $<input type="text" name="output" id="output" value="">.00

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM