简体   繁体   中英

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()
{
    var 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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM