0

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..

2
  • Just curious if you're doing things the right way: does validation also work if you turn off JavaScript in your browser? (i.e. you're also doing exactly the same validation in the server side). If not, you've got something to think about :) Commented Sep 4, 2011 at 15:38
  • Yes i'm doing the validation on the server side aswell.... Thanks :D Commented Sep 6, 2011 at 6:33

2 Answers 2

1

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;
} 
Sign up to request clarification or add additional context in comments.

7 Comments

it still excepts value's greater than weight
Is there an HTML element in the page with ID s? What is its value?
<input name="weight" id="weight" type="text"/>
I didn't ask about an element with ID weight, I asked about an element with ID s.
You need to make it accessible to JavaScript, then, as in @medopal's answer. Java runs on the server, JavaScript runs in the browser. There's no magic to make the two "see" each other.
|
1

s is a Java variable so you cannot reference it through document.

Try something like:

var x = <%=Integer.parseInt(sum); %>
if (document.getElem...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.