Help with Javascript in JSP page
I have a JSP which gets a value called sum from the DB...
String sum= request.getAttribute("s").toString();
int s = Integer.parseInt(sum);
I have a field in a form called weight who's value cannot exceed sum.
So on clicking submit i'm running a function called validate. Which would check if field is greater than or equal to sum but it keeps giving me the warning all the time.
<script type="text/javascript">
function validate()
{
v开发者_开发技巧ar x= document.getElementById("s");
if(document.getElementById("weight").value>x)
{
alert("Weight exceeds maximum limit...!!!");
return false;
}
return true;
}
</script>
Would appreciate the help..
This has nothing to do with JSP. You need to parse the values into numbers using parseInt()
or parseFloat()
before comparing. This is because the .value
attribute is always a string. You are also comparing an element's value with an element, which does not make sense.
Try this:
function validate()
{
var weight = parseFloat(document.getElementById("weight").value),
maxWeight = parseInt(document.getElementById("s").value, 10);
if(weight > maxWeight)
{
alert("Weight exceeds maximum limit...!!!");
return false;
}
return true;
}
s
is a Java variable so you cannot reference it through document
.
Try something like:
var x = <%=Integer.parseInt(sum); %>
if (document.getElem...
精彩评论