JQuery - Simple Separation of Two Values
I am trying to get different values ββfrom my input fields, divide them and show the result like this:
<input type="text" class="ad-title calculate form-control" name="budget" id="budget" value="" placeholder="Enter a daily budget in USD">
<input type="text" class="form-control calculate" id="ppc" name="ppc" value="" placeholder="">
My simple jQuery:
$(document).ready(function() {
$(".calculate").bind("keyup change", function(e) {
var budget = parseFloat($("#budget").val());
var ppc = parseFloat($("#ppc").val());
var value = ppc / budget;
$("#sum").text(value);
});
});
However, in my div, #sum
all I can see is:NaN
What am I doing wrong?
source to share
You could like this:
$(document).ready(function() {
$(".calculate").bind("keyup change", function(e) {
var budget = parseFloat($("#budget").val()) || 0;
var ppc = parseFloat($("#ppc").val()) || 0;
var value = ppc / budget;
if (!isNaN(value) && value !== Infinity) {
$("#sum").text(value);
}
});
});
You may need to modify it to suit your needs. For example, we'll get NaN
or Not a Number when dividing by zero to handle this. Maybe you never want to show 0, so maybe handle that or make it the default for budget 1
. It depends on how you want it to work.
JSFiddle: http://jsfiddle.net/f0t45c7x/1
source to share
Convert your values ββto numbers with the +
unary operator instead of using parseFloat
:
$(document).ready(function () {
$(".calculate").bind("keyup change", function (e) {
var budget = +$("#budget").val();
var ppc = +$("#ppc").val();
if(!budget || !ppc) return false; // Wait till both values are set
var value = ppc / budget;
$("#sum").text(value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input type="text" class="ad-title calculate form-control" name="budget" id="budget" value="" placeholder="Enter a daily budget in USD">
<input type="text" class="form-control calculate" id="ppc" name="ppc" value="" placeholder="">
<div id="sum"></div>
source to share
You don't need to bind the "change" event, this should do,
$(document).ready(function() {
$(".calculate").bind("keyup", function(e) {
var budget = parseFloat($("#budget").val()) || 0;
var ppc = parseFloat($("#ppc").val()) || 0;
var value = (ppc / budget);
// alert(value);
if (!isNaN(value) && value != Infinity) {
$("#sum").text(value);
}
else{
$("#sum").text("0")
}
});
});
source to share