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("<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?

>Solution :

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


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


<input type="text" name="discount" id="discount">

Leave a Reply