I am new to javascript and php and programming so pls bear with me.
I am trying to create javascript function to check if the user enters a float value or not. The event is keypressed so it will check every character.
What happens is that if the first character is a float it say its float for the rest of the input even if the following characters are already non numeric. Also if the first character is non numeric it will say not float even if the there are some non numeric characters. It seems to me that it only checks the first character. Pls help…
index.php
<script type="text/javascript" src="javascript.js"> </script>
<form action="index.php" method="get">
Integer 1: <input type="text" id="num1" name="num1" onkeypress="checkInput(this);" /> <br />
Integer 2: <input type="text" id="num2" name="num2" onkeypress="checkInput(this);" /> <br />
<input type="submit" value="Compute" />
</form>
javascript.js
function checkInput(obj) {
if(!parseFloat(obj.value)) {
alert("Not Float");
} else {
alert("Float");
}
}
parseFloatis meant to extract a number from a string, starting from the first character.To check if the entirety of a string represents a number, convert it to a
Number, and check if the result isNaN(Not a Number):