validation - Javascript: Ensure Input is Numbers Only -


i have unit conversion script; html contains radio buttons (to pick units), input field, output field , button.

here's sample of javascript file:

[...]  window.addeventlistener("load", function(){     document.getelementbyid("convert").addeventlistener("click", function(){         var initial = document.getelementbyid("initial").value;         document.getelementbyid("answer").innerhtml = convertobj.converted(initial);         });  [...]  });  function convertclass(){}  convertclass.prototype.converted = function(initialamount){     if(document.getelementbyid("kilograms").checked) {         this.calculation = this.multiply(initialamount, 2.2046);     } else if(document.getelementbyid("pounds").checked) {         this.calculation = this.divide(initialamount, 2.2046);     }     return this.calculation.tofixed(2); }  [...]  var convertobj = new convertclass(); 

i add ensures a) empty input field isn't considered "0", , b) other number doesn't display "nan" answer. in both cases, i'd output return nothing (blank). don't want do nothing, in case user submits blank field or invalid value after correct number submission (which think result in previous answer still being displayed.)

how write that? i'm assuming should use conditions, don't know ones. did bit of research , apparently using isnan() isn't entirely accurate, @ least not in context.

where put code, in function triggered page load or 1 triggered button?

i'm still learning so, if possible, i'd appreciate explanations along edited code. thank you!

inside convertclass.prototype.converted @ beginning of function, add:

// coerces number instead of string // or nan if can't convert number initialamount = initialamount.length > 0 ? +initialamount : 0/0;  // if not number, return empty string if (isnan(initialamount)) {     return ""; } 

if input empty string 0/0 evaluates nan.


Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -