0

I am creating a conversion table which requires two user inputs however, what I am trying to do is make sure that the user only inputs an integer, so in my conversion table function I used a built in function in javascript called isNan which means is not a number, however, the message does not show up when the user inputs a negative number or a letter.

<html>
<head>
<script type = "text/javascript">

function conversion(n) {
<!--if(n<1);-->
return (n/0.62137).toFixed(2);
}

function conversionTable(rangeStart, rangeEnd) {
if(atLeastOneRadio()) {
    divStr="<table border=1><tr><td>Miles</td><td>Kilometres</td></tr>";
    if(isNaN(i)){document.write("Please input an integer")}
    else {
    for(i=rangeStart;i<=rangeEnd;i++) {
        divStr+="<tr><td>" + i + "</td><td>" + conversion(i) + "</td></tr>";
  }
    document.getElementById("divResult").innerHTML=divStr;
}}
}

function getnputValue() {
return parseInt(document.getElementById("rangeTxt").value);
}

function check() {
var radios = document.getElementsByName("choice");

for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
    return true;
}
}

return false;
}

function atLeastOneRadio() {
return ($('input[type=radio]:checked').length > 0);
}
</script>
</head>
<body>
<p>
Start : <input type=textbox id=rangeTxt value=""/>
Finish : <input type=textbox id=rangeTxt2 value=""/>
<input type=radio name="convert" id="mtokm" value ="Miles to Kilometre"/>     Miles to Kilometre
<input type=radio name="convert" id="kmtom" value ="Kilometre to Miles"/>   Kilometre to Miles
<br>
<br>
<button       onClick="conversionTable(getnputValue(),parseInt(document.getElementById('rangeTxt2').value))">Convert</button>
</p>
<div id="divResult">
</div>
</body>
</html>
JayJay Simpson
  • 155
  • 3
  • 15
  • In your function conversion table, where is declare the variable "i"?, or what are you trying to compare with "i"? – dexhering Feb 01 '16 at 18:28
  • Not exactly related, but HTML comments are not the best practice in JS code. ``, and will throw an error, if it was met in the code (not when in a comment ofcourse). – Teemu Feb 01 '16 at 18:29

1 Answers1

1
Function checkIfValidInteger(var input)
    var isValid = false;
    If(input>=0)
         IsValid = true;
return isValid;

isValid will remain false if the input is a string containing something else than number ( i.e. "0csh" ) or if it's lower than 0. It will be true if the input is greater or equals to 0, or a string made of number only ( i.e. "0182" )

Jorel Amthor
  • 1,264
  • 13
  • 38