$(".input-sm").each(function() {
$(this).keyup(function() {
calculateStuff();
});
});
function calculateStuff() {
//add only if the value is number
if (!isNaN($('#pa').val()) && $('#pa').val().length != 0) {
pa = parseFloat(this.value);
}
if (!isNaN($('#de').val()) && $('#de').val().length != 0) {
de = parseFloat(this.value);
}
if (!isNaN($('#pr').val()) && $('#pr').val().length != 0) {
pr = parseFloat(this.value);
}
re = pa + de + pr;
stuff = ((pr - de) / (re)) * 100;
$("#value").html(stuff);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1 id="value" class="m-t-50">Stuff = 0</h1>
<input type="text" class="form-control input-sm" id="de">
<input type="text" class="form-control input-sm" id="pa">
<input type="text" class="form-control input-sm" id="pr">
答案 0 :(得分:1)
1st:您可以使用.keyup而无需.each
$(".input-sm").on('keyup',function() {
calculateStuff($(this));
});
第二名尝试在转到if statments
之前将变量定义为0 第3名 this.value
将不返回任何内容,因此将el传递给您的函数$(el).val()
并在keyup中使用
function calculateStuff(el) {
var pa = 0, de = 0, pr = 0 , re = 0, stuff = 0;
//add only if the value is number
if (!isNaN($('#pa').val()) && $('#pa').val().length != 0) {
pa = parseFloat($(el).val());
}
if (!isNaN($('#de').val()) && $('#de').val().length != 0) {
de = parseFloat($(el).val());
}
if (!isNaN($('#pr').val()) && $('#pr').val().length != 0) {
pr = parseFloat($(el).val());
}
re = pa + de + pr;
stuff = ((pr - de) / (re)) * 100;
$("#value").html(stuff);
}
答案 1 :(得分:0)