Reputation: 9647
hoping some one can shed some light on my problem. I have three input fields which calculate a formula when all three fields are filled. I used the keyup function to detect when the fields have content, but for the life of me, I can't get it to work. Any help will be most appreciated.
$(".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">
Upvotes: 3
Views: 528
Reputation: 740
I tried your code. You're using (this.value) inside the control statements and "this" is undefined you actually didn't refer from where it is coming from. Replace your (this.value) with the respective id's of your input element just like this => ($('#pa').val()).
//e.g.
pa = parseFloat($('#pa').val());
I tested it and it's working fine.
Upvotes: 0
Reputation: 24001
1st: you can use .keyup without need to .each
$(".input-sm").on('keyup',function() {
calculateStuff($(this));
});
2nd: try to define your variables with 0 before going to if statments
3rd: this.value
will return nothing so pass el to your function $(el).val()
and use it in 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);
}
Upvotes: 1