Number Format Exception JSP Page with cookies - java

I wrote this small code for handling cookies.However,when i click on the "next" button it throws a
java.lang.NumberFormatException: For input string: "current"
Code:
<%#page import="java.util.*"%>
<%
int current=0;
Cookie[] cookies = request.getCookies();
Cookie cookie = null;
if(cookies != null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("last"))
cookie = cookies[i];
}
}
if(cookie != null){
String btn = request.getParameter("button");
if(btn != null){
if(btn.equals("next"))
current = Integer.parseInt(cookie.getValue()) + 1;
else
current = Integer.parseInt(cookie.getValue()) - 1;
}
}
response.addCookie(new Cookie("last",String.valueOf("current")));
out.println(current);
%>
<html>
<head>
</head>
<body>
<form method="post">
<input type="submit" name="button" value="prev" />
<input type="submit" name="button" value="next" />
</form>
</body>
</html>

You set the cookie to value "current"
String.valueOf("current")
but you want
String.valueOf(current)

Related

Liferay 6.2 Media Gallery

<%--
/**
* Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2.1 of the License, or (at your option)
* any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
* details.
*/
--%>
<%# include file="/html/portlet/image_gallery_display/init.jsp" %>
<%
Folder folder = (Folder)request.getAttribute(WebKeys.DOCUMENT_LIBRARY_FOLDER);
long defaultFolderId = GetterUtil.getLong(portletPreferences.getValue("rootFolderId", StringPool.BLANK), DLFolderConstants.DEFAULT_PARENT_FOLDER_ID);
long folderId = BeanParamUtil.getLong(folder, request, "folderId", defaultFolderId);
boolean defaultFolderView = false;
if ((folder == null) && (defaultFolderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
defaultFolderView = true;
}
if (defaultFolderView) {
try {
folder = DLAppLocalServiceUtil.getFolder(folderId);
}
catch (NoSuchFolderException nsfe) {
folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
}
}
long repositoryId = scopeGroupId;
if (folder != null) {
repositoryId = folder.getRepositoryId();
}
int status = WorkflowConstants.STATUS_APPROVED;
if (permissionChecker.isContentReviewer(user.getCompanyId(), scopeGroupId)) {
status = WorkflowConstants.STATUS_ANY;
}
long portletDisplayDDMTemplateId = PortletDisplayTemplateUtil.getPortletDisplayTemplateDDMTemplateId(displayStyleGroupId, displayStyle);
%>
<c:choose>
<c:when test="<%= portletDisplayDDMTemplateId > 0 %>">
<%
String[] mediaGalleryMimeTypes = DLUtil.getMediaGalleryMimeTypes(portletPreferences, renderRequest);
List fileEntries = DLAppServiceUtil.getGroupFileEntries(scopeGroupId, 0, folderId, mediaGalleryMimeTypes, status, 0, SearchContainer.MAX_DELTA, null);
%>
<%= PortletDisplayTemplateUtil.renderDDMTemplate(pageContext, portletDisplayDDMTemplateId, fileEntries) %>
</c:when>
<c:otherwise>
<%
String topLink = ParamUtil.getString(request, "topLink", "home");
long assetCategoryId = ParamUtil.getLong(request, "categoryId");
String assetTagName = ParamUtil.getString(request, "tag");
boolean useAssetEntryQuery = (assetCategoryId > 0) || Validator.isNotNull(assetTagName);
PortletURL portletURL = renderResponse.createRenderURL();
portletURL.setParameter("struts_action", "/image_gallery_display/view");
portletURL.setParameter("topLink", topLink);
portletURL.setParameter("folderId", String.valueOf(folderId));
request.setAttribute("view.jsp-folder", folder);
request.setAttribute("view.jsp-defaultFolderId", String.valueOf(defaultFolderId));
request.setAttribute("view.jsp-folderId", String.valueOf(folderId));
request.setAttribute("view.jsp-repositoryId", String.valueOf(repositoryId));
request.setAttribute("view.jsp-viewFolder", Boolean.TRUE.toString());
request.setAttribute("view.jsp-useAssetEntryQuery", String.valueOf(useAssetEntryQuery));
request.setAttribute("view.jsp-portletURL", portletURL);
%>
<portlet:actionURL var="undoTrashURL">
<portlet:param name="struts_action" value="/document_library/edit_entry" />
<portlet:param name="<%= Constants.CMD %>" value="<%= Constants.RESTORE %>" />
</portlet:actionURL>
<liferay-ui:trash-undo portletURL="<%= undoTrashURL %>" />
<liferay-util:include page="/html/portlet/document_library/top_links.jsp" />
<c:choose>
<c:when test="<%= useAssetEntryQuery %>">
<liferay-ui:categorization-filter
assetType="images"
portletURL="<%= portletURL %>"
/>
<%
SearchContainer searchContainer = new SearchContainer(renderRequest, null, null, "cur2", SearchContainer.DEFAULT_DELTA, portletURL, null, null);
OrderByComparator orderByComparator = DLUtil.getRepositoryModelOrderByComparator("modifiedDate", "desc");
searchContainer.setOrderByComparator(orderByComparator);
long[] classNameIds = {PortalUtil.getClassNameId(DLFileEntryConstants.getClassName()), PortalUtil.getClassNameId(DLFileShortcut.class.getName())};
AssetEntryQuery assetEntryQuery = new AssetEntryQuery(classNameIds, searchContainer);
assetEntryQuery.setEnablePermissions(true);
assetEntryQuery.setExcludeZeroViewCount(false);
int total = AssetEntryServiceUtil.getEntriesCount(assetEntryQuery);
searchContainer.setTotal(total);
List results = AssetEntryServiceUtil.getEntries(assetEntryQuery);
searchContainer.setResults(results);
String[] mediaGalleryMimeTypes = null;
request.setAttribute("view.jsp-mediaGalleryMimeTypes", mediaGalleryMimeTypes);
request.setAttribute("view.jsp-searchContainer", searchContainer);
%>
<liferay-util:include page="/html/portlet/image_gallery_display/view_images.jsp" />
</c:when>
<c:when test='<%= topLink.equals("home") %>'>
<aui:row>
<c:if test="<%= folder != null %>">
<liferay-ui:header
localizeTitle="<%= false %>"
title="<%= folder.getName() %>"
/>
</c:if>
<%
SearchContainer searchContainer = new SearchContainer(renderRequest, null, null, "cur2", SearchContainer.DEFAULT_DELTA, portletURL, null, null);
String[] mediaGalleryMimeTypes = DLUtil.getMediaGalleryMimeTypes(portletPreferences, renderRequest);
int foldersCount = DLAppServiceUtil.getFoldersCount(repositoryId, folderId, true);
int total = DLAppServiceUtil.getFoldersAndFileEntriesAndFileShortcutsCount(repositoryId, folderId, status, mediaGalleryMimeTypes, true);
int imagesCount = total - foldersCount;
searchContainer.setTotal(total);
List results = DLAppServiceUtil.getFoldersAndFileEntriesAndFileShortcuts(repositoryId, folderId, status, mediaGalleryMimeTypes, true, searchContainer.getStart(), searchContainer.getEnd(), searchContainer.getOrderByComparator());
searchContainer.setResults(results);
request.setAttribute("view.jsp-mediaGalleryMimeTypes", mediaGalleryMimeTypes);
request.setAttribute("view.jsp-searchContainer", searchContainer);
%>
<aui:col cssClass="lfr-asset-column lfr-asset-column-details" width="<%= showFolderMenu ? 75 : 100 %>">
<div id="<portlet:namespace />imageGalleryAssetInfo">
<c:if test="<%= folder != null %>">
<div class="lfr-asset-description">
<%= HtmlUtil.escape(folder.getDescription()) %>
</div>
<div class="lfr-asset-metadata">
<div class="lfr-asset-icon lfr-asset-date">
<%= LanguageUtil.format(pageContext, "last-updated-x", dateFormatDate.format(folder.getModifiedDate())) %>
</div>
<div class="lfr-asset-icon lfr-asset-subfolders">
<%= foldersCount %> <liferay-ui:message key='<%= (foldersCount == 1) ? "subfolder" : "subfolders" %>' />
</div>
<div class="lfr-asset-icon lfr-asset-items last">
<%= imagesCount %> <liferay-ui:message key='<%= (imagesCount == 1) ? "image" : "images" %>' />
</div>
</div>
<liferay-ui:custom-attributes-available className="<%= DLFolderConstants.getClassName() %>">
<liferay-ui:custom-attribute-list
className="<%= DLFolderConstants.getClassName() %>"
classPK="<%= (folder != null) ? folder.getFolderId() : 0 %>"
editable="<%= false %>"
label="<%= true %>"
/>
</liferay-ui:custom-attributes-available>
</c:if>
<liferay-util:include page="/html/portlet/image_gallery_display/view_images.jsp" />
</div>
</aui:col>
<c:if test="<%= showFolderMenu %>">
<aui:col cssClass="lfr-asset-column lfr-asset-column-actions" last="<%= true %>" width="<%= 25 %>">
<div class="lfr-asset-summary">
<liferay-ui:icon
cssClass="lfr-asset-avatar"
image='<%= "../file_system/large/" + ((total > 0) ? "folder_full_image" : "folder_empty") %>'
message='<%= (folder != null) ? HtmlUtil.escape(folder.getName()) : LanguageUtil.get(pageContext, "home") %>'
/>
<div class="lfr-asset-name">
<h4><%= (folder != null) ? HtmlUtil.escape(folder.getName()) : LanguageUtil.get(pageContext, "home") %></h4>
</div>
</div>
<%
request.removeAttribute(WebKeys.SEARCH_CONTAINER_RESULT_ROW);
%>
<liferay-util:include page="/html/portlet/document_library/folder_action.jsp" />
</aui:col>
</c:if>
</aui:row>
<%
if (folder != null) {
IGUtil.addPortletBreadcrumbEntries(folder, request, renderResponse);
if (!defaultFolderView && portletName.equals(PortletKeys.MEDIA_GALLERY_DISPLAY)) {
PortalUtil.setPageSubtitle(folder.getName(), request);
PortalUtil.setPageDescription(folder.getDescription(), request);
}
}
%>
</c:when>
<c:when test='<%= topLink.equals("mine") || topLink.equals("recent") %>'>
<%
long groupImagesUserId = 0;
if (topLink.equals("mine") && themeDisplay.isSignedIn()) {
groupImagesUserId = user.getUserId();
}
SearchContainer searchContainer = new SearchContainer(renderRequest, null, null, SearchContainer.DEFAULT_CUR_PARAM, SearchContainer.DEFAULT_DELTA, portletURL, null, null);
String[] mediaGalleryMimeTypes = DLUtil.getMediaGalleryMimeTypes(portletPreferences, renderRequest);
int total = DLAppServiceUtil.getGroupFileEntriesCount(repositoryId, groupImagesUserId, defaultFolderId, mediaGalleryMimeTypes, status);
searchContainer.setTotal(total);
List results = DLAppServiceUtil.getGroupFileEntries(repositoryId, groupImagesUserId, defaultFolderId, mediaGalleryMimeTypes, status, searchContainer.getStart(), searchContainer.getEnd(), searchContainer.getOrderByComparator());
searchContainer.setResults(results);
request.setAttribute("view.jsp-mediaGalleryMimeTypes", mediaGalleryMimeTypes);
request.setAttribute("view.jsp-searchContainer", searchContainer);
%>
<aui:row>
<liferay-ui:header
title="<%= topLink %>"
/>
<liferay-util:include page="/html/portlet/image_gallery_display/view_images.jsp" />
</aui:row>
<%
PortalUtil.addPortletBreadcrumbEntry(request, LanguageUtil.get(pageContext, topLink), currentURL);
PortalUtil.setPageSubtitle(LanguageUtil.get(pageContext, topLink), request);
%>
</c:when>
</c:choose>
</c:otherwise>
</c:choose>
i m using Liferay 6.2 and using Media Gallery Portlet to display the images which is placed in Multiple folders. i have multiple folders which contain multiple images but the folders are arranged according to alphabetical order but my requirement is to arrange the folders which are recently updated (i,e the recently updated folder must come at the top) so can anybody please provide solution how to achieve this.
thanks in Advance.
Over-ride view.jsp of /html/portlet/image_gallery_display by either hook or ext and add following two lines below the initialization of SearchContainer object at about line# 115:
OrderByComparator orderByComparator =
DLUtil.getRepositoryModelOrderByComparator("modifiedDate", "desc");
searchContainer.setOrderByComparator(orderByComparator);
This will order your Media Gallery's folders and images descending by modified date.
Update:
If you want to control this behavior from preferences, then:
Declare and initialize these properties in init.jsp:
String sortByCol = portletPreferences.getValue("sortByCol", "title");
String sortByOrder = portletPreferences.getValue("sortByOrder", "desc");
Add following drill-downs for value selection in
configuration.jsp:
<div class="aui-column left-selector-column">
<aui:select label="Sort By" name="preferences--sortByCol--">
<aui:option label="Title" value="title"
selected="<%= sortByCol.equals("title") %>" />
<aui:option label="Create Date" value="creationDate"
selected="<%= sortByCol.equals("creationDate") %>"/>
<aui:option label="Modified Date" value="modifiedDate"
selected="<%= sortByCol.equals("modifiedDate") %>" />
</aui:select>
</div>
<div class="aui-column right-selector-column">
<aui:select label="Order" name="preferences--sortByOrder--">
<aui:option label="Ascending" value="asc"
selected="<%= sortByOrder.equals("asc") %>"/>
<aui:option label="Descending" value="desc"
selected="<%= sortByOrder.equals("desc") %>"/>
</aui:select>
</div>
Add these two lines in view.jsp below the
initialization of SearchContainer:
OrderByComparator orderByComparator =
DLUtil.getRepositoryModelOrderByComparator(sortByCol, sortByOrder);
searchContainer.setOrderByComparator(orderByComparator);

Form validation issue in HTML

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>

Tag <c:if> doesn't work

I have method to get Cookies, and compare returned boolean with , but it doesn't work. Both condition doesn't work.
static public boolean isUserAuth(HttpServletRequest request){
String cookieName = "forum_login";
Cookie cookies [] = request.getCookies ();
Cookie myCookie = null;
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
if (cookies[i].getName().equals (cookieName)) {
myCookie = cookies[i];
return true;
}
}
}
return false;
}
JSP page:
<%# page import="db_Proccesing.Users_processing" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
boolean test = Users_processing.isUserAuth(request);
%>
<!DOCTYPE html>
<header>
<a class="header-logo"></a>
<div id="form_text" class="form">
<c:if test = "${test == true}">
<p>TRUE</p>
</c:if>
<c:if test = "${test == false}">
<p>FALSE</p>
</c:if>
</div>
</header>
So, doesn't printed TRUE and FALSE
I fix it, using:
<c:if test = "<%= !Users_processing.isUserAuth(request) %>">
Thank's all.

How to send variable in action java class to jquery?

When I click on the button will be equal to the amount of undefind while the amount is equal to 1
in jsp page :
<%
String err1 = (String) request.getAttribute("err2");
int code = 0;
if (err1 != null){
code = Integer.parseInt(err1);
System.out.println(" code " + code);
}
%>
<button type="button" id="btnok">ok</button>
<br />
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
<br />
in jquery code:
$(document).ready(function() {
$("#btnok").click(function(event) {
var xxx = $("#txtcode").val();
alert("xxx 1 test + " + xxx);
});
});
The most likely reason is that the condition:
<%if(code == 3){ %>
<input id="txtcode" type="hidden" value="1" />
<%}%>
is not being met and the input is not being inserted to the DOM. Reload the page and view the page source to see if the input is inserted.

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.

Categories