使用jQuery自动更新带有数学运算的输入字段? [英] Automatically updating input field with math using jquery?
问题描述
好吧,我需要一些帮助,我有一个在线计算器,在这里我必须从两个输入字段中获取线性表.当他们输入数据时,我需要此功能是自动的.我不知道该怎么做.任何编码帮助将不胜感激!这是html:
Ok I need some help, I have an online calculator where I have to get the lineal meter from two input fields. I need this to be automatic as they input the data. I have no idea how to do this.. any coding help would be greatly appreciated! Here is the html:
<input type="text" name="ancho" />
<input type="text" name="alto" />
<input type="text" name="material" />
我需要它才能输出到该字段:
I need it to output into this field:
<input type="text" name="ml" />
这是它的数学方面的方程式: (材料/100)/((alto/100)*(ancho/100))
Here is the equation for the math side of it: (material/100) / ((alto/100) * (ancho/100))
在此先感谢您的帮助!
推荐答案
感叹在解决方案中,我在此处看不到很多错误检查,所以我认为我会发布再多一个 ...
Sigh I don't see a lot of error checking on here in the solutions, so I thought I'd post just one more...
// locate all the input fields on the page
$(':input')
// bind to anything change related (down to keyboard changes so the element
// won't need to lose focus, or the user won't have to press enter)
.bind('keypress keydown keyup change',function(){
// retrieve the values of the inputs (we also call parseFloat to confirm
// we are dealing with numeric values)
var acho = parseFloat($(':input[name="acho"]').val(),10),
alto = parseFloat($(':input[name="alto"]').val(),10),
matl = parseFloat($(':input[name="material"]').val(),10);
// default the end result to an empty string (you'll see
// why with the following statement)
var v = '';
// confirm that all three values that go in to the equation are
// all numbers before we try to perform any math functions. If
// all goes well, "v" above will have the actual resulting value.
// if any number is invalid, the "Result" field (ml) gets emptied
if (!isNaN(acho) && !isNaN(alto) && !isNaN(matl)){
// your math function
v = (matl / 100) / ((alto / 100) * (acho / 100));
}
// replace the value of "ml" with our new calculated value
$(':input[name="ml"]').val(v.toString());
});
... 通过演示
这篇关于使用jQuery自动更新带有数学运算的输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!