With this code there’s the possibility that the user would enter either a 0 or nothing at all in the ‘numeric’ form fields.
Is there a ‘catch all’ so that if the user does this the NaN or resulting 0.0000% is just replaced with 0?
I think this needs two logics(?) one for the NaN replacement and one to change the .appendTo result so that it only shows 0 rather than 0.00000%
here’s a JSFiddle – http://jsfiddle.net/sturobson/xTEKm/39/
and here’s the jquery –
$(document).ready(function() {
$(function(){
$("#result").submit(function(e) {
e.preventDefault();
var ele = $("#element").val(),
target = $("#target").val(),
context = $("#context").val(),
border = $("#border").val(),
margin = $("#margin").val(),
padding = $("#padding").val();
console.log(ele, target, context, border, margin, padding);
var DoubleMargin = parseInt(margin, 10) * 2;
var DoublePadding = parseInt(padding, 10) * 2;
var DoubleBorder = parseInt(border, 10) * 2;
var ActualTarget = parseInt(target, 10) - parseInt(DoubleBorder, 10) - parseInt(DoubleMargin, 10) - parseInt(DoublePadding, 10) * 1;
var result3 = parseInt(target, 10) - parseInt(DoubleMargin, 10) * 1;
var MarginResult = ((parseInt(margin, 10) / parseInt(target, 10)) * 100).toFixed(5);
var PaddingResult = ((parseInt(padding, 10) / parseInt(target, 10)) * 100).toFixed(5);
var OriginalResult = ((parseInt(ActualTarget, 10) / parseInt(context, 10)) * 100).toFixed(5);
var BorderResult = parseInt(target, 10) - parseInt(border, 10) * 1;
//$(".result").append(ele + " " + result + "%");
$("<p></p>", {
html: ele + " {<br><span>width: " + OriginalResult + "%;" + " /* " + ActualTarget + " (originally " + target + ") / " + context + " */ " + "<br>border: " + border + "px; " + "<br>margin: " + MarginResult + "%; " + "<br>padding: " + PaddingResult+ "%;" + "<br> </span>}"
}).hide().appendTo("#code-results").fadeIn();
});
});
});
any ideas?
Convert once at the getter:
Also see your updated example.
=== UPDATE ===
With toFixed(x) you get exactly
xdecimals. If you want to get up to maxxdecimals, you can use following function instead:Also see your updated example.
=== UPDATE ===
The next problem is, that a denominator of a fraction has to be a non-zero value. You can add a division function which returns zero instead of NaN, if the denominator is zero:
Also see your updated example.
=== UPDATE ===
If you want the code a little smaler, you can combine it with T.J. Crowder answer; the source code could be:
Also see your updated example.