Reputation: 103
I have validated a number as a positive number but it is not giving correct answer i.e it is accepting negative numbers also. Where did I go wrong?
<script type="javascript">
function validatenumber(){
var class1=document.getElementById("class");
if((parseInt)class1.value<0){
alert("Please enter positive integer");
return false;
}
}
</script>
<form name="addbook" action="addbook.php" method="get" onsubmit="validatenumber();">
Code:<br/><input type="text" name="code"><br/>
Class:<br/><input type="number" name="class"><br/>
title:<br/><input type="text" name="title"><br/>
price:<br/><input type="number" name="price"><br/>
quantity:<br/><input type="number" name="quantity"><br/>
category:<br/><input type="text" name="category"><br/>
<input type="submit" value="submit"><br/>
</form>
Upvotes: 0
Views: 113
Reputation: 115488
this:
(parseInt)class1.value<0
should be:
parseInt(class1.value, 10) < 0
The 10 will force it to be evaluated as base 10 and not allow JavaScript to "guess" as to which base it thinks it is. In previous versions of ECMAScript, having a string with a "0" at the start will trick parseInt into thinking that the number should be interpreted as octal.
You are also trying to get the element by id, and you have specified by name.
Class:<br/><input type="number" name="class"><br/>
you can either give the element an id, or you can use
var class1=document.getElementsByName("class")[0];
instead of:
var class1=document.getElementById("class");
and
you have type="javascript"
and it should be language="javascript"
https://jsfiddle.net/wvapgjs6/1/
Upvotes: 3