Form validation issue in HTML - java

People, I am having a problem in my HTML form validation. Currently I am using JSP (at the back end) to extract the form data and jquery to validate the data in my HTML file. Problem is that when i run my HTML on server (apache tomcat), my jquery validation snippet doesn't work and data simply gets passed to the JSP file. Only if I remove the action attribute from form tag then the validation code runs but JSP doesn't get called. Here are my HTML and JSP scripts.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,javax.mail.*"%>
<%# page import="javax.mail.internet.*,javax.activation.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# page import = "java.util.regex.Pattern,java.util.regex.Matcher,java.util.regex.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Yay!</title>
</head>
<body>
<%
//-------------->
String first = request.getParameter("firstname");
String last = request.getParameter("lastname");
String Username = request.getParameter("username");
String Email = request.getParameter("email");
String day = request.getParameter("date");
String month = request.getParameter("month");
String year = request.getParameter("year");
String pass1 = request.getParameter("password");
String pass2 = request.getParameter("confirmpassword");
String date = day + '/'+ month + '/' + year ;
%>
<%= first %><br>
<%= last %><br>
<%= Username %> <br>
<%= Email%> <br>
<%= date%> <br>
<%= pass1%> <br>
<%= pass2%> <br>
</body>
</html>
<!-- HTML file-->
<form class = ".form-inline"
method = "POST" action = "process.jsp"
onSubmit="return validate(this);" name="form" >
<lable><b>Name:</b></lable>
<input type = "text" placeholder = "first"
id = "firstname"
name = "firstname"></input>
<input type = "text" placeholder = "last"
id = "lastname"
name = "lastname"></input><br><br>
<label>Birthday:</label>
<div class = "date">
<input type = "text" placeholder = "dd"
id = "date" name = "date"></input>
<input type = "text" placeholder = "mm"
id = "month" name = "month"></input>
<input type = "text" placeholder = "yy"
id = "year" name="year"></input>
<br><br>
</div>
<div class="form-group ">
<label><b>User Name:</b></label>
<input type = "text"
class = "form-control"
id = "username" name="username"></input>
<br>
<label for="password">Password:</label>
<input type="password"
class="form-control"
id="password" name = "password">
<br>
<label for="confirmpassword">
Confirm Password:</label>
<input type="password"
class="form-control"
id="confirmpassword" name = "confirmpassword">
<label for="email">Email:</label>
<input type="email"
class="form-control" id="email" name ="email">
<br>
<button type="submit"
class="btn btn-primary btn-block"
id = "submission"
value ="submit">Submit</button>
<script type="text/javascript">
/*global $*/
$(function(){ // JS form validation snippet.
// variables are used to
store different types of
regex expressions.
var ck_name = /^[A-Za-z0-9 ]{3,20}$/;
var ck_email
= /^([\w-]+ (?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-] {0,66})
\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i ;
var ck_username =
/^[A-Za-z0-9_] {1,20}$/;
var ck_password =
/^[A-Za-z0-9!##$%^&*()_]{6,20}$/;
var flag;
$("#submission").on("click",
function validate(form){
var day = $("#date").val();
var month = $("#month").val();
var year = $("#year").val();
if ((day >= 1 && day <= 31 ) &&
(month >= 1 && month <= 12) &&
(year >= 1930)) {
//alert("correct date ");
}
else {
//alert("wrong date");
}
//alert("submission active");
// variable extracts
the specific user input from the form.
var firstname = $("#firstname").val();
var lastname = $("#lastname").val();
var email = $("#email").val();
var username = $("#username").val();
var password = $("#password").val();
var confirmpassword = $("#confirmpassword").val();
var errors = [];
if (!ck_name.test(firstname)) {
errors[errors.length] = "Your valid first Name .";
}
if (!ck_name.test(lastname)) {
errors[errors.length] = "Your valid last Name .";
}
if (!ck_email.test(email)) {
errors[errors.length] =
"Yor must enter a valid email address.";
}
if(!ck_username.test(username)) {
errors[errors.length] =
"Your valid UserName no special char .";
}
if (!ck_password.test(password) ) {
errors[errors.length] =
"Your must enter a valid Password ";
}
if (!ck_password.test(confirmpassword) ||
password !== confirmpassword) {
errors[errors.length] = "password doesn't match ";
}
if (errors.length > 0) {
reportErrors(errors);
return false;
}
//$.get("process.jsp", [firstname, lastname, email, username,
password, confirmpassword, day, month, year]);
//alert(".get() executed");
return true;
function reportErrors(errors){
var msg = "Please Enter Valide Data...\n";
for (var i = 0; i<errors.length; i++) {
var numError = i + 1;
msg += "\n" + numError + ". " + errors[i];
}
//alert(msg);
}
});
});
</script>
</div>
</form>

there is a syntax error in your javascript please check your code properly
if i remove all your javscript code then i am able to do validation.
check my code you will get an idea.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import="java.io.*,java.util.*,javax.mail.*"%>
<%# page import="javax.mail.internet.*,javax.activation.*"%>
<%# page import="javax.servlet.http.*,javax.servlet.*" %>
<%# page import = "java.util.regex.Pattern,java.util.regex.Matcher,java.util.regex.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Yay!</title>
</head>
<body>
<%
//if(request.getParameter("btnsubmit")!=null){
//-------------->
String first = request.getParameter("firstname");
String last = request.getParameter("lastname");
String Username = request.getParameter("username");
String Email = request.getParameter("email");
String day = request.getParameter("date");
String month = request.getParameter("month");
String year = request.getParameter("year");
String pass1 = request.getParameter("password");
String pass2 = request.getParameter("confirmpassword");
String date = day + '/'+ month + '/' + year ;
// }
%>
<%= first %><br>
<%= last %><br>
<%= Username %> <br>
<%= Email%> <br>
<%= date%> <br>
<%= pass1%> <br>
<%= pass2%> <br>
</body>
</html>
<!-- HTML file-->
<script type="text/javascript">
function validate(form) {
alert('hi');
}
</script>
<form class = ".form-inline"
method = "POST" action ="index.jsp"
onSubmit="return validate(this);" name="form" >
<lable><b>Name:</b></lable>
<input type = "text" placeholder = "first"
id = "firstname"
name = "firstname"></input>
<input type = "text" placeholder = "last"
id = "lastname"
name = "lastname"></input><br><br>
<label>Birthday:</label>
<div class = "date">
<input type = "text" placeholder = "dd"
id = "date" name = "date"></input>
<input type = "text" placeholder = "mm"
id = "month" name = "month"></input>
<input type = "text" placeholder = "yy"
id = "year" name="year"></input>
<br><br>
</div>
<div class="form-group ">
<label><b>User Name:</b></label>
<input type = "text"
class = "form-control"
id = "username" name="username"></input>
<br>
<label for="password">Password:</label>
<input type="password"
class="form-control"
id="password" name = "password">
<br>
<label for="confirmpassword">
Confirm Password:</label>
<input type="password"
class="form-control"
id="confirmpassword" name = "confirmpassword">
<label for="email">Email:</label>
<input type="email"
class="form-control" id="email" name ="email">
<br>
<button type="submit"
class="btn btn-primary btn-block"
id = "submission"
value ="submit" name='btnsubmit'>Submit</button>
</div>
</form>

Related

Why random checkbox choosing giving error,not in serial-wise in JSP page?

I am trying to make a basic shop-billing JSP project. now when i type random product quantity with checkbox it giving error like below image. but when i checked-value with serial wise, it is not giving the error, it giving me the result what i desiring. I have also check it is empty or not. but can't able to get out of this error. how can i get rid out of it?
Code:
<%--
Document : order
Created on : Jun 15, 2019, 3:11:06 PM
Author : Riddhi
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*" %>
<!DOCTYPE html>
<html lang="en">
<%# include file="header.jsp" %>
<h2 class="text-center"> ShopBilling </h2>
<p><br/></p>
<%
String Host = "jdbc:mysql://localhost:3306/shopbilling";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
PreparedStatement ps=null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(Host, "root", "");
StringBuilder sb = new StringBuilder();
%>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="row">
<div class="col-md-6"><h3>Product Details</h3></div>
<div class="col-md-6 text-right">
Back to Home
</div>
</div>
<p></p>
<form action="" method="post">
<%
String products[] = request.getParameterValues("products");
String items[] = request.getParameterValues("item_no");
int sum=0;
if (products!= null && items!= null && products.length != 0 && items.length != 0) {
for (int i = 0; i < products.length; i++) {
%> <%
statement = connection.createStatement();
String u=request.getParameter("u");
int num=Integer.parseInt(products[i]);
String Data = "select * from products_tbl where id='"+num+"'";
rs = statement.executeQuery(Data);
while (rs.next()) {
%>
<input type="hidden" name="id" value='<%=rs.getString("id")%>'/>
<div class="form-group">
<label for="product_name">Product Name: <%=rs.getString("product_name")%></label>
<input type="hidden" class="form-control" id="product_name" name="product_name" value='<%=rs.getString("product_name")%>'>
</div>
<div class="form-group">
<label for="product_price">Product Single Price: <%=rs.getString("product_price")%></label>
<input type="hidden" class="form-control" id="product_price" name="product_price" value='<%=rs.getString("product_price")%>'>
</div>
<div class="form-group">
<label for="product_name">Item Quantity: <% out.println(items[i]); %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<div class="form-group">
<label for="product_name">Product Total Price: <%
int num1=Integer.parseInt(items[i]);
int propri=Integer.parseInt(rs.getString("product_price"));
out.println(num1 * propri); int gtotal= num1 * propri; %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<hr>
<% sum= sum + gtotal; %>
<%
}
}
}
%>
<div class="form-group">
<label for="product_name">Grand Total: <%
out.println(sum); %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>
<button type="print" onclick="window.print();" class="btn btn-warning">Print</button>
</form>
</div>
</div>
<%# include file="footer.jsp" %>
</html>
I think the problem in your code is with <input type="text" name="item_no" /> because every row in your above code has checkbox , when you submit your form only selected checkbox is passed , but all <input type="text" name="item_no" /> is passed even the null where you didn't give any value , so when you iterate you get null value with that as well .Now ,to solve this do like below :
//give value to your check-box i.e id of that row
<input type="checkbox" name="products" value ='<%=rs.getString("id")%>' />
//pass that id with your input type i.e item_no_1 ..etc
<input type="text" name='item_no_<%=rs.getString("id")%>' />
And then to get only particular value of Product Quantity where you have selected Checkbox do like below :
String products[] = request.getParameterValues("products");
if (products!= null && items!= null && products.length != 0 && items.length != 0) {
for (int i = 0; i < products.length; i++) {
//your code
<div class="form-group">
<label for="product_name">Product Total Price: <%
//getting item value of that selected checkbox
int item_no=Integer.parseInt(request.getParameter("item_no_" + products[i]));
int propri=Integer.parseInt(rs.getString("product_price"));
out.println(num1 * propri); int gtotal= num1 * propri; %></label>
<input type="hidden" class="form-control" id="item_no" name="item_no" value='items[j]'>
</div>

Exception Occured java.lang.NumberFormatException: null

I am getting following error in JSP page
SELECT * FROM books WHERE id =1001
Exception Occuredjava.lang.NumberFormatException: null
while running below code.
I doubt this is due to
input type='text' size='3' value='1' name='qty'<%=id% in JSearch.jsp is not properly linked to
int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id)); in JOrder.jsp.
Can any one please help me on this.
Code: JSearch.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Search Page</title>
</head>
<body>
<% try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#//XXXXX.XXX:1521/xe", "sai", "harisai");
Statement stmt=conn.createStatement();
// Retrieve and process request parameters: "author" and "search"
String author = request.getParameter("author");
boolean hasAuthorParam = author != null && !author.equals("Select...");
String searchWord = request.getParameter("search");
boolean hasSearchParam = searchWord != null && ((searchWord = searchWord.trim()).length() > 0);%>
<h2>Query Results</h2>
<%if (!hasAuthorParam && !hasSearchParam) { %> <%--No params present--%>
<h3>Please select an author or enter a search term!</h3>
<p><a href='Entryscreen.jsp'>Back to Select Menu</a></p>
<% }
else {
// Form a SQL command based on the param(s) present
StringBuilder sqlStr = new StringBuilder(); // more efficient than String
sqlStr.append("SELECT * FROM books WHERE qty > 0 AND (");
if (hasAuthorParam) {
sqlStr.append("author = '").append(author).append("'");
}
if (hasSearchParam) {
if (hasAuthorParam) {
sqlStr.append(" OR ");
}
sqlStr.append("author LIKE '%").append(searchWord)
.append("%' OR title LIKE '%").append(searchWord).append("%'");
sqlStr.append(") ORDER BY author, title");
}//
out.println(sqlStr); // for debugging
ResultSet rset = stmt.executeQuery(sqlStr.toString());
if (!rset.next()) { %> <%--// Check for empty ResultSet (no book found)--%>
<h3>No book found. Please try again!</h3>
<p><a href='start'>Back to Select Menu</a></p>
<%}
else {%>
<%--// Print the result in an HTML form inside a table--%>
<form method='get' action='JOrder.jsp'>
<table border='1' cellpadding='6'>
<tr>
<th> </th>
<th>AUTHOR</th>
<th>TITLE</th>
<th>PRICE</th>
<th>QTY</th>
</tr>
<%-- // ResultSet's cursor now pointing at first row--%>
<% do {
// Print each row with a checkbox identified by book's id
String id = rset.getString("id");%>
<tr>
<td><input type='checkbox' name='id' value='<%=id%>' /></td>
<td><%=rset.getString("author")%></td>
<td><%=rset.getString("title")%></td>
<td>$<%=rset.getString("price")%></td>
<td><input type='text' size='3' value='1' name='qty'<%=id%>/></td>
</tr>
<%} while (rset.next()); %>
</table><br/>
<%--// Ask for name, email and phone using text fields (arranged in a table)--%>
<table>
<tr><td>Enter your Name:</td>
<td><input type='text' name='cust_name'/></td></tr>
<tr><td>Enter your Email (user#host):</td>
<td><input type='text' name='cust_email' /></td></tr>
<tr><td>Enter your Phone Number (8-digit):</td>
<td><input type='text' name='cust_phone' /></td></tr></table><br />
<%-- // Submit and reset buttons--%>
<input type='submit' value='ORDER' />
<input type='reset' value='CLEAR' /></form>
<%
}
}
}
catch (Exception e){
out.println("Exception Occured:" +e);
} %>
</body>
</html>
Code:
JOrder.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# page import = "java.sql.*" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Order Confirmation</title>
</head>
<body>
<h1>Order Confirmation</h1>
<% try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection ("jdbc:oracle:thin:#//XXXXX.XXX.LOCAL:1521/xe", "sai", "harisai");
Statement stmt=conn.createStatement();
// Retrieve and process request parameters: id(s), cust_name, cust_email, cust_phone
String[] ids = request.getParameterValues("id"); // Possibly more than one values
String custName = request.getParameter("cust_name");
boolean hasCustName = custName != null && ((custName = custName.trim()).length() > 0);
String custEmail = request.getParameter("cust_email").trim();
boolean hasCustEmail = custEmail != null && ((custEmail = custEmail.trim()).length() > 0);
String custPhone = request.getParameter("cust_phone").trim();
boolean hasCustPhone = custPhone != null && ((custPhone = custPhone.trim()).length() > 0);
// Validate inputs
if (ids == null || ids.length == 0) {%>
<h3>Please Select a Book!</h3>
<% } else if (!hasCustName) {%>
<h3>Please Enter Your Name!</h3>
<% } else if (!hasCustEmail || (custEmail.indexOf('#') == -1)) {%>
<h3>Please Enter Your e-mail (user#host)!</h3>
<%} else if (!hasCustPhone || (custPhone.length() != 8)) {%>
<h3>Please Enter an 8-digit Phone Number!</h3>
<%} else {%>
<%--// Display the name, email and phone (arranged in a table)--%>
<table>
<tr><td>Customer Name:</td><td><%=custName%></td></tr>
<tr><td>Customer Email:</td><td><%=custEmail%></td></tr>
<tr><td>Customer Phone Number:</td><td><%=custPhone%></td></tr></table>
<%--// Print the book(s) ordered in a table--%>
<br/>
<table border='1' cellpadding='6'>
<tr><th>AUTHOR</th><th>TITLE</th><th>PRICE</th><th>QTY</th></tr>
<% float totalPrice = 0f;
for(String id : ids) {
String sqlStr = "SELECT * FROM books WHERE id ="+ id;
out.println(sqlStr);
// for debugging
ResultSet rset = stmt.executeQuery(sqlStr);
rset.next();
int qtyAvailable = rset.getInt("qty");
String title = rset.getString("title");
String author = rset.getString("author");
float price = rset.getFloat("price");
int qtyOrdered = Integer.parseInt(request.getParameter("qty"+id));
sqlStr = "UPDATE books SET qty = qty -"+ qtyOrdered +" WHERE id =" + id;
out.println(sqlStr); // for debugging
stmt.executeUpdate(sqlStr);
sqlStr = "INSERT INTO ORDER_RECORDS VALUES ("+ id + ", " + qtyOrdered + ", '" + custName + "', '"
+ custEmail + "', '" + custPhone + "')";
out.println(sqlStr); // for debugging
stmt.executeUpdate(sqlStr);%>
<%-- // Display this book ordered--%>
<tr>
<td><%=author%></td>
<td><%=title%></td>
<td><%=price%></td>
<td><%=qtyOrdered%></td></tr>
<% totalPrice += price * qtyOrdered;
}%>
<tr><td colspan='4' align='right'>Total Price: $
</td> <%out.println(totalPrice);%> </tr>
</table>
<h3>Thank you.</h3>
<%out.println("<p><a href='JEntryScreen.jsp'>Back to Select Menu</a></p>");
}
}
catch (Exception e) {
out.println("Exception Occured" +e);
}
finally {
}%>
</body>
</html>
What is a NumberFormatException?
Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.
-[Documentation][2]
NumberFormatException extends IllegalArgumentException. It tells us that it's more specialized IllegalArgumentException. Indeed, it's used for highlighting that although, the argument type was correct (String) the content of the String wasn't numeric (a,b,c,d,e,f are considered digits in HEX and are legal when needed).
Ad. 2.
When you see, that instead of "For input string:" and the input, there is a null (not "null") it means, that you tried to pass the null reference to a number. If you actually want to treat is as 0 or any other number, you might be interested in my another post on StackOverflow. It's available [here][3].
The description of solving unexpected nulls is well described in a topic [What is a NullPointerException and how can I fix it?][4].
The answer is taken from this topic - I couldn't mark it as a duplicate because I have raised another flag before the question was edited.

Calling a JSP Function from another jsp file

I have create a simple application on jsp..
In my global function jsp file, I have created functions as follows:
<%! public double calcB(double w, double h){
double B = 0;
return B = (w / (h * h));
}
public String calcClassif(double B){
String classifi = null;
if(B >= 30)
classif = "Obese";
else if(B >= 25)
classif = "Overweight";
else if(B >= 18.5)
classif = "Normal";
else
classif = "Underweight";
return classif;
}
%>
Now in my my index.jsp file, I have written the following:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= calcBMI(we, he) %> <br> <br>
Classification: <%= classification %>
</form>
When I execute the application, the classification is not working.. How do I call the method to display me the correct classification ?
Please help.. Thanks
You are never assign a value into classification. You may try this:
<%#include file = "globalFunctions.jsp" %>
<% Boolean submitted = Boolean.parseBoolean(request.getParameter("isSubmitted"));
double we = 0, he = 0;
if(submitted){
weight = Double.parseDouble(request.getParameter("w"));
height = Double.parseDouble(request.getParameter("h"));
bmi = calcBMI(we, he);
classification = calcClassif(bmi);
}
%>
<h3>BMI Calculator</h3>
<form action = "index.jsp" method = "post">
<input type ="hidden" name = "isSubmitted" value = "true">
Weight: <input type = "text" name = "w"> <br> <br>
Height: <input type = "text" name = "h"> <br> <br>
<input type = "submit" value = "Compute"> <br> <br>
BMI: <%= bmi %> <br> <br>
Classification: <%= classification %>
</form>
Whenever your JSP is compiled by your servlet container, it is compiled under different names every time. This makes it hard to use a JSP page function in another JSP page. I would recommend you to start using servlets and POJOs for your data processing needs.
Anyway, you don't have any variable named classification (index.jsp:21), therefore it is not displayed and the server logs an error to the console, and not to the client like PHP.

Embedding JavaScript code in JSP won't call the JS function

Given the following code :
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title>Bank application</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Web Bank application</th></tr>
</table>
<br/>
<script>
function verifyEmptyString()
{
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
return !(username == null || username == "" || password == null || password == "");
}
</script>
<fieldset>
<legend>Login Page - please enter your Username and Password</legend>
<form id="loginForm" action="loginPage" onsubmit="verifyEmptyString()" >
<p style="font-size:15px"> <span style="color:red;font-weight:bold;">*</span> Username: <input type="text" name="username"><br> </p>
<p style="font-size:15px"><span style="color:red;font-weight:bold;">*</span> Password : <input type="password" name="password"><br> </p>
<input type="submit" value="Login">
</form>
</fieldset>
<br/>
<br/>
<br/>
<br/>
<br/><br/><br/><br/><br/><br/>
</body></html>
I'm trying to call the JS function verifyEmptyString() , but the JSP doesn't call the function.
Any idea what's wrong with the code ?
The function is being called (I added an alert to verify). But you want to return the value of the function in the onclick event:
<form id="loginForm" action="loginPage" onsubmit="return verifyEmptyString(this)" >
Try something like this : http://jsfiddle.net/daguru/RBYnc/1/
var myForm = document.getElementById('loginForm');
myForm.addEventListener("submit", function(ev) {
ev.preventDefault(); // to stop the form from submitting
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
if(!(username == null || username == "" || password == null || password == "")){
this.submit(); // If all the validations succeeded
alert("submiting")
}
});
Here is the solution :
<form onsubmit="return verifyEmptyString(this)" id="loginForm" action="loginPage" >
For anyone who might encounter this problem in the future , you need to change the onsubmit ...
From this :
onsubmit="verifyEmptyString()"
To this :
onsubmit="return verifyEmptyString(this)"
I do not quite understand why we need to pass thisas a parameter to the function, because it is not accepted in the actual function definition function verifyEmptyString() . You are directly referring the form elements inside the function.
On the otherhand, if your code is similar to the below scenario,
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm(obj) {
var x = obj["firstname"].value;
alert(x);
if (x == null || x == "") {
alert("First name must be filled out");
return false;
}
}
</script>
</head>
<body>
<form name="myForm" action="action.jsp"
onsubmit="return validateForm(this)" method="post">
First name: <input type="text" name="firstname"> <input
type="submit" value="Submit">
</form>
</body>
</html>
In this scenario, we are making use of the passed parameter this.
It refers to the current context, In our case, it is the form whose name is myForm
But in your original scenario, you are directly referring the form inside the javascript function by calling document.forms["loginForm"]["username"].value.

Find whether check boxes are checked inside a servlet

I have several check box in a form I just wanna way to check whether they are checked or not .
If checked i need to store their id in the database(that i can do it ) . But my question is how to determine whether are checked or not instead of checking for each check box on at a time . I need to check whether its checked or not inside a servlet.
This is my code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Role Id<input type="text" name="roll_id"/><br>
Role Name<input type="text" name="roll_name"/><br>
Role Description<textarea name="roll_desc"></textarea><br>
<br>
<br>
Screen1<br>
tab1<br>
<input type="checkbox" name="s1_t1_view" value="s1_t1_view" >view<br>
<input type="checkbox" name="s1_t1_add" value="s1_t1_add" >add<br>
<input type="checkbox" name="s1_t1_edit" value="s1_t1_edit" >edit<br>
<input type="checkbox" name="s1_t1_delete" value="s1_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s1_t2_view" value="s1_t2_view" >view<br>
<input type="checkbox" name="s1_t2_add" value="s1_t2_add" >add<br>
<input type="checkbox" name="s1_t2_edit" value="s1_t2_edit" >edit<br>
<input type="checkbox" name="s1_t2_delete" value="s1_t2_delete" >delete<br>
Screen2<br>
tab1<br>
<input type="checkbox" name="s2_t1_view" value="s2_t1_view" >view<br>
<input type="checkbox" name="s2_t1_add" value="s2_t1_add" >add<br>
<input type="checkbox" name="s2_t1_edit" value="s2_t1_edit" >edit<br>
<input type="checkbox" name="s2_t1_delete" value="s2_t1_delete" >delete<br>
tab2<br>
<input type="checkbox" name="s2_t2_view" value="s2_t2_view" >view<br>
<input type="checkbox" name="s2_t2_add" value="s2_t2_add" >add<br>
<input type="checkbox" name="s2_t2_edit" value="s2_t2_edit" >edit<br>
<input type="checkbox" name="s2_t2_delete" value="s2_t2_delete" >delete<br>
<input type="submit" name="sumbit" text="submit">
</body>
</html>
But in my code I have several check boxes . I need to hardcode that for every check box . Is there way so that i put it in a loop and check for all check boxes ?
To be simple, you can use the name attribute to get the data since you are using different name for each checkbox.
In Servlet :
String[] s1_t1_view = request.getParameterValues("s1_t1_view");
String[] s1_t1_add = request.getParameterValues("s1_t1_add");
If you want to use group of checkbox to give the user a choice between multiple values, you will need to iterate over the group in the servlet. You can use this :
In HTML : (same name = same group)
<input type = "checkbox" name = "s1_t1" value = "s1_t2_view" >View <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_add" >Add <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_edit" >Edit <br>
<input type = "checkbox" name = "s1_t1" value = "s1_t2_delete" >Delete<br>
In Servlet :
String[] results = request.getParameterValues("s1_t1");
for (int i = 0; i < results.length; i++) {
System.out.println(results[i]);
}
You can use
String[] checked = request.getParameterValues("checkboxName");
and then check the checked value
For me this one worked.
String[] selecttype=request.getParameterValues("selectType");
//selectType is the name of checkbox in jsp page.
This will return selected checkbox values.
Create hidden fields as
Now in your servlet as: String[] names = request.getParameterValues("checkbox");
PrintWriter pw = new PrintWriter(new File("/Desktop/sticker.txt"));
for(int i=0; i < names.length; i++) {
if(i + 1 < names.length && names[i].equals(names[i+1])) {
pw.write(names[i] + ",true\n");
++i;
} else {
pw.write(names[i]+",false\n");
}
}
pw.close();

Categories