Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Java Servlet – Checking Input of input field

I want to check in a Java Servlet if the user entered code10 in a input field, after he pressed the submit button. If thats the case, the form should just go to the next page, if something else then code10 there should just be an alert, and the user should stay on the same page to enter a new Code, or leave the input field blank.

These are the important snippets out of my code:

    out.println("<head><script type=\"text/javascript\">");
    out.println("function check() {");
    out.println("var inputDiscountValue = document.getElementById(\"discount\").value;");
    out.println("if (inputDiscountValue == 'code10' OR inputDiscountValue == '') {");
    out.println("return true;");
    out.println("} else {");
    out.println("alert('Code not valid');");
    out.println("return false;");
    out.println("}");
    out.println("}");
    out.println("</script>");
    out.println("</head>");
    ...
    out.println("<form action=\"Servlet2\" method=\"post\">");
    out.println("<input type=\"String\" name=\"discount\">");
    out.println("<input type=\"submit\" onclick='return check()' value=\"Go\" /> </form>");

Anyone got an idea, why this isnt working?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are using document.getElementById("discount") but you did not create an element with that ID.

Change

<input type="String" name="discount">

to

<input type="text" name="discount" id="discount">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading