java script doesn't get the data from jsp - javascript

It's about search and paging functions.
this shows keyWord and keyField well on console when i search keyWord .
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
System.out.println(keyWord);
System.out.println(keyField);
%>
but this doesn't work.
address appear like this. didn't get data from javascript code.
http://localhost:8090/mvcBoard/list.do?page=2&keyWord=&keyField=
function PageMove(page){
var keyWord = '<%request.getParameter("keyword");%>';
var keyField = '<%request.getParameter("keyField");%>';
console.log(keyWord);
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
but it works!
location.href = "list.do?page="+page;
this is list.jsp
<!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=UTF-8">
<title>Insert title here</title>
<%
String keyWord = (String)request.getParameter("keyWord");
String keyField = (String)request.getParameter("keyField");
System.out.println(keyWord);
System.out.println(keyField);
%>
<script>
function searchCheck(frm){
//검색
if(frm.keyWord.value ==""){
alert("검색 단어를 입력하세요.");
frm.keyWord.focus();
return;
}
frm.submit();
}
function PageMove(page){
var keyWord = '<%request.getParameter("keyword");%>';
var keyField = '<%request.getParameter("keyField");%>';
console.log(keyWord);
if(keyWord){
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
location.href = "list.do?page="+page+"&keyWord=" + keyWord + "&keyField=" + keyField;
}
</script>
</head>
<body>
<table width="800" cellpadding="0" cellspacing="0" border="1">
<tr>
<td>번호</td>
<td>이름</td>
<td>제목</td>
<td>날짜</td>
<td>조히수</td>
</tr>
<c:forEach items="${list}" var="dto">
<tr>
<td>${dto.bId}</td>
<td>${dto.bName}</td>
<td>
<c:forEach begin="1" end="${dto.bIndent}">-</c:forEach>
${dto.bTitle}</td>
<td>${dto.bDate}</td>
<td>${dto.bHit}</td>
</tr>
</c:forEach>
<tr>
<td colspan="5">
<form action="list.do" method="post" name="search">
<select name="keyField">
<option value="bTitle">글 제목</option>
<option value="bContent">글 내용</option>
<option value="bName">작성자</option>
</select>
<input type="text" name="keyWord">
<input type="button" value="검색" onclick="searchCheck(form)">
<input type="hidden" id=keyField value="${paging.keyField}">
<input type="hidden" id=keyWord value="${paging.keyWord}">
</form>
</td>
</tr>
<tr>
<td colspan="5"> 글작성 </td>
</tr>
</table>
<%-- <%=PageAction.pageNumber() %>
--%>
<div class="toolbar-bottom">
<div class="toolbar mt-lg">
<div class="sorter">
<ul class="pagination">
<li>맨앞으로</li>
<li>앞으로</li>
<c:forEach var="i" begin="${paging.startPageNo}" end="${paging.endPageNo}" step="1">
<c:choose>
<c:when test="${i eq paging.pageNo}">
<li class="active">${i}</li>
</c:when>
<c:otherwise>
<li>${i}</li>
</c:otherwise>
</c:choose>
</c:forEach>
<li>뒤로</li>
<li>맨뒤로</li>
</ul>
</div>
</div>
</div>
</body>
</html>

For a start this code looks wrong
<input type="hidden" value="${paging.getkeyField()}">
<input type="hidden" value="${paging.getKeyWord()}">
change to the same format as paging.nextPageNo
<input type="hidden" value="${paging.keyField}">
<input type="hidden" value="${paging.keyWord}">
next you either add an id to this hidden fields (and get the value using Javascript or jquery)
<input type="hidden" id="kf" value="${paging.keyField}">
or use the same parameter passing as paging.nextPageNo to PageMove
javascript:PageMove(${paging.nextPageNo}, ${paging.keyField}); // etc

Related

How to return values from external javascript function

I have a function in an external java script file and I dont know how to call and return the value that my function returns in text properly. When I click place order, I want the values to be calculated by my function and then the final value to be displayed underneath the place order box. I can get my function to alert if I enter nothing but I can't get it to return my final value- what am I doing wrong?
function sum2()
{
var one = document.getElementById("book_1").value;
var two = document.getElementById("book_2").value;
var three = document.getElementById("book_3").value;
if ((one == "")||(two == "")||(three == ""))
{
alert ('Error', 'values missing');
}
else
{
var sum1 = one * 19.99;
var sum2 = two * 86.00;
var sum3 = three * 55.00;
var sum = sum1 + sum2 + sum3;
document.getElementById('output').value = sum;
document.write(sum);
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Work</title>
<script type="text/javascript" src="ex4.js"></script>
</head>
<body>
<div id="container">
<h2>Order Books Online</h2>
<form action="" method="post" id=”frm”>
<fieldset>
<table border="0">
<tr>
<th>Book</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Basics of C++</td>
<td><input type="text" size="3" id="book_1" /></td>
<td>$19.99</td>
</tr>
<tr>
<td>Program Development in Perl</td>
<td><input type="text" size="3" id="book_2" /></td>
<td>$86.00</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td><input type="text" size="3" id="book_3" /></td>
<td>$55.00</td>
</tr>
</table>
<br /><br />
<input type="submit" onclick="sum2(); return false;" value="Place Order" id="sub" />
</fieldset>
</form>
</div>
</body>
</html>
Try this, its working, output is displaying on last.
function sum2()
{
var one = document.getElementById("book_1").value;
var two = document.getElementById("book_2").value;
var three = document.getElementById("book_3").value;
if ((one == "")||(two == "")||(three == ""))
{
alert ('Error', 'values missing');
}
else
{
var sum1 = one * 19.99;
var sum2 = two * 86.00;
var sum3 = three * 55.00;
var sum = sum1 + sum2 + sum3;
document.getElementById('output').innerHTML = sum;
// document.write(sum);
}
}
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Work</title>
<script type="text/javascript" src="ex4.js"></script>
</head>
<body>
<div id="container">
<h2>Order Books Online</h2>
<form action="" method="post" id=”frm”>
<fieldset>
<table border="0">
<tr>
<th>Book</th>
<th>Quantity</th>
<th>Price</th>
</tr>
<tr>
<td>Basics of C++</td>
<td><input type="text" size="3" id="book_1" /></td>
<td>$19.99</td>
</tr>
<tr>
<td>Program Development in Perl</td>
<td><input type="text" size="3" id="book_2" /></td>
<td>$86.00</td>
</tr>
<tr>
<td>Advanced JavaScript</td>
<td><input type="text" size="3" id="book_3" /></td>
<td>$55.00</td>
</tr>
</table>
<br /><br />
<input type="submit" onclick="sum2(); return false;" value="Place Order" id="sub" />
</fieldset>
</form>
</div>
<div id="output"></div>
</body>
</html>
The use of document.write() doesn't seem to be what you'd want here. (And, honestly, should be avoided in general anyway.)
However, this will do what you want:
document.getElementById('output').value = sum;
All you need is an HTML input element which has that id (which your HTML is currently missing):
<input type="text" id="output" />
(Additionally, your JavaScript is missing a closing }, which is a syntax error.)
Once you have that HTML element and remove the document.write() call, this should be outputting the value correctly.
If you want to output to something other than another input element, then you wouldn't use .value but something more like .innerHTML instead:
document.getElementById('output').innerHTML = sum;
with an element such as:
<span id="output"></span>
As an aside regarding terminology, this isn't "returning" the value from the function. "Return" has a very specific meaning when it comes to functions, it's when the function itself results in a value using the return keyword, passing that value back up the stack to the code which called the function.
This function is writing a value to the HTML, but it's not returning anything.

Dynamic Button call JavaScript Function

I have a script and a Dinamic created Button and event OnClick doesn't work
I need to pass Id and inQuantidade to ValidarEstoqueVenda.htm and JavaScript is the only way i think its possible
page import="usuario.usuario"%>
<%#page import="DAO.DAO"%>
<%#page import="java.util.ArrayList"%>
<%#page import="produto.produto"%>
<%#page import="java.util.List"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<% usuario Usuario = (usuario) session.getAttribute("Usuario");%>
<script>
function clickVender(){
var Id = document.getElementById('Id');
var inQuantidade = document.getElementById('inQuantidade');
if(Id.value != "")
alert("You entered: " + Id.value)
else
alert("Would you please enter some text?")
document.location.href="ValidarEstoqueVenda.htm?Id="+Id.value+"&inQuantidade="+inQuantidade;
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="css/materialize.css">
<!-- Include CSS File Here -->
<script src="js/materialize.js"></script>
<title>Estoque Online - Estoque</title>
</head>
<body>
<div class="navbar-fixed">
<nav id="nav_f" class="default_color" role="navigation">
<div class="container">
<div class="nav-wrapper">
Controle de Estoque
<ul class="right hide-on-med-and-down">
<li>Estoque</li>
<%if (Usuario.getTipo() == 2){%>
<li>CadastroEstoque</li>
<li>Cadastro Tipo</li>
<li>Tipo</li>
<li>Usuario</li>
<%}%>
<li>Sair</li>
</ul>
<ul id="nav-mobile" class="side-nav">
<li>Estoque</li>
<%if (Usuario.getTipo() == 2){%>
<li>Cadastro Tipo</li>
<ul id='dropdown2' class='dropdown-content'>
<li>Usuario</li>
</ul>
<%}%>
<li>Sair</li>
</ul>
<i class="mdi-navigation-menu"></i>
</div>
</div>
</nav>
</div>
<form action="ValidarEstoque" method="get">
<table class="striped responsive-table black-text teal darken-1">
<thead>
<tr>
<th data-field="id">Id</th>
<th data-field="nome">Descricao</th>
<th data-field="email">Quantidade</th>
<th data-field="Alterar">Alterar</th>
<th data-field="Excluir">Exlcuir</th>
</tr>
</thead>
<tbody>
<tr>
<% List<produto> produtos = new ArrayList<produto>();
DAO dao = new DAO();
produtos = dao.listarEstoque();%>
<%for(produto produto : produtos){%>
<td><%=produto.getId()%></td>
<td><%=produto.getDescricao()%></td>
<td><input type="text" id="inQuantidade" name="inQuantidade" value="<%=produto.getQuantidade()%>"></td>
<% if(Usuario.getId() != 0){%>
<td>Alterar</td>
<td>Excluir</td>
<td><a class="btn waves-effect waves-light col s12" onclick="clickVender()">Vender</a></td>
<%
}
%>
</tr>
<%
}
%>
</tbody>
</table>
</form>
</body>
</html>
The last tag have the onCLick function.
Please Help me
Your code don't have id named 'Id'.
and you should don't use inline event handler.
You should refer to my code.
[HTML]
<td>
<input type="text" id="Id" name="MYID" value="my dummy Id">
</td>
<td>
<input type="text" id="inQuantidade" name="inQuantidade" value="getQuantidade">
</td>
<td><a class="govender">Vender</a></td>
[JavaScript]
function clickVender() {
var id = document.getElementById("Id");
var inQuantidade = document.getElementById("inQuantidade");
alert(id.value + ":" + inQuantidade.value);
}
document.querySelector(".govender").onclick = clickVender;
//or you can use addEventListener.
https://jsfiddle.net/nigayo/n81hd5f3/
[# additional explanation]
you can see error messages on console tab of Chrome developer tools.
https://developer.chrome.com/devtools/docs/console

I want to pop up a confirmation message after all message after submitting

This my jsp page and i'm doing Employee management work now and i want to popup a confirmation message after all my validations are successful or true and it should ask user yes or no. for the submission of the form.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%# page session="false" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Employee Management System</title>
<link href="CSS/style.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/smoothness/jquery-ui.css" />
<script language="javascript" type="text/javascript">
function checkform(pform1){
var str=pform1.bloodGroup.value;
var email = pform1.email.value;
var phone = pform1.phoneNumber.value;
var cleanstr = phone.replace(/[\(\)\.\-\ ]/g, '');
var err={};
var validemail =/^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
var income = pform1.annualIncome.value;
var Id = pform1.employeeId.value;
var salary = income.replace(/[\(\)\.\-\ ]/g, '');
var Eid = Id.replace(/[\(\)\.\-\ ]/g, '');
//check required fields
//password should be minimum 4 chars but not greater than 8
if (((str.length < 1) || (str.length > 3))&& (!(str.notequals("")))) {
err.message="Invalid blood group";
err.field=pform1.bloodGroup;
}
//validate email
else if( (email != "") && !(validemail.test(email))){
err.message="Invalid email";
err.field=pform1.email;
}
//check phone number
else if (isNaN((cleanstr))) {
err.message="Invalid phone number";
err.field=pform1.phoneNumber;
}
else if (isNaN((salary))) {
err.message="Invalid Annual Income";
err.field=pform1.annualIncome;
}
else if (isNaN((Eid))) {
err.message="Invalid EmployeeID";
err.field=pform1.annualIncome;
}
if(err.message)
{
document.getElementById('divError').innerHTML = err.message;
err.field.focus();
alert(err.message);
return false;
}
else
{
return true;
}
}
</script>
<script>
$(function() {
$( "#dateOfBirth" ).datepicker({
showOn: "button",
buttonImage: "Pictures/calendicon.jpg" ,
buttonImageOnly: true,
buttonText: "Select date",
/* dateFormat: 'dd/mm/yy ' */
});
});
</script>
</head>
<body><center>
<h2>Employee Management System</h2>
<form:form method="POST" action="./add.html" modelAttribute ="employee" onsubmit="return checkform(this);" >
<div id="errmsgbox">
<div id="divError"></div>
</div>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td width="14%">Employee ID<span class="mandatory" >*</span></td>
<td width="35%"> <form:hidden path="ID" />
<form:input path="employeeId" required = "required"/></td>
<td width="16%">Employee Name<span class="mandatory" >*</span></td>
<td width="35%"><form:input path="employeeName" required = "required" /></td>
</tr>
<tr>
<td>DOB<span class="mandatory" >*</span></td>
<td><form:input path ="dateOfBirth" required = "required" id="dateOfBirth"></form:input></td>
<style>
img.ui-datepicker-trigger {
width: 15px;
height: 15px;
}
</style>
<td>Blood group </td>
<td><form:input path="bloodGroup" /></td>
</tr>
<tr>
<td>Annual Income </td>
<td><form:input path ="annualIncome" /></td>
<td>Qualification</td>
<td><form:input path ="qualification" /></td>
</tr>
<tr>
<td>Pan No.</td>
<td><form:input path="panNumber" /></td>
<td>Phone No. </td>
<td><form:input path="phoneNumber" /></td>
</tr>
<tr>
<td>Sex</td>
<td><form:radiobutton path="sex" value="m"/>Male
<form:radiobutton path="sex" value="f"/>Female</td>
<td>Email</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Address</td>
<td colspan="3"><textarea name="" cols="" rows="2"></textarea></td>
</tr>
</table>
<div>
<input name="submit2" type="submit" title="Submit" value="Submit" />
<input type="button" name="reset_form" value="Reset" onclick="this.form.reset();"/>
<input name="submit3" type="button" title="Reset" value="View All"/>
</div>
</form:form>
</center>
</body>
</html>
Replace you else block by following code in checkform():
if(confirm("Your question here?")) {
return true;
} else {
return false;
}
You can use alert() in the javascript.

datetime comparision in javascript is not working

I want to validate dateTime input fields in form and it need to give alert message if not entered and if "FromDate"(ex:17-12-2013 19:14:58) > than the "CurrentDate" it need to give alert message in the same way "ToDate" > than the "CurrentDate" it need to give mes and if "FromDate">"ToDate" in that cse also it need to give some alert message i written code for it but it is not working can any one help me?
Code wiill be like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://displaytag.sf.net" prefix="display" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Preva Tracking Systems</title>
<link rel="icon" href="pictures/preva_logo.png" />
<link rel="stylesheet" href="css/screen.css" type="text/css">
<link rel="stylesheet" href="css/site.css" type="text/css">
<link href="css/sty.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="js/datetimepicker.js"></script>
<script type="text/javascript" src="js/overspeedvalidate.js" >
</script>
</head>
<body>
<form name="myForm" onsubmit="return validateForm()" action="ReportGenerator?action=OverspeedEventDBReport" method="post">
<table width=100% border="1">
<tr bgcolor=#075A99 >
<td width=100% align=left><b><font color=white>OverSpeed Event Report</font></b></td>
</tr>
</table>
<table cellpadding="0" cellspacing="0" width="100%" class="reportSearchBorder">
<tr><td> </td></tr>
<tr>
<td width="100%">
<table width="100%" cellpadding="0" cellspacing="0" border=0>
<tr>
<td align="left" id="VehicleIdDescDiv" valign="middle">Vehicle Number</td>
<td >
<table align=left border=0>
<tr>
<td align=left>
<select name="vehicleId" class="txtbig" ><option value="">Select vehicle number</option>
<c:forEach var="vehiclelist" items="${devicelists}">
<option value="${vehiclelist.deviceID}">${vehiclelist.description}</option>
</c:forEach></select>
</td>
</tr>
<tr><td align="center"></td></tr>
<tr>
<td valign="middle"></td>
</tr>
</table>
</td><td id="VehicleIdDescDiv" valign="middle">Show overspeed instances more than</td>
<td >
<select name="speed" class="txtbig" >
<option value="">Select</option>
<option value=">100km">>100km</option>
<option value=">90km">>90km</option>
<option value=">80km">>80km</option>
<option value=">70km">>70km</option>
<option value=">60km">>60km</option>
<option value=">50km">>50km</option>
<option value=">40km">>40km</option>
<option value=">30km">>30km</option>
<option value=">20km">>20km</option>
<option value=">10km">>10km</option>
</select> </td>
</tr></table>
<table>
<tr><td> </td></tr>
<tr>
<td width="60%">
<table>
<tr><td>From Date</td>
<td>
<input type="Text" name="AnotherDate" id="demo1" maxlength="25" size="25"><img src="pictures/cal.gif" width="16" height="16" border="0" alt="select">
<br>(eg:- 17-12-2013 19:14:58)
</td>
<td>To Date</td>
<td>
<input type="Text" id="demo2" name="ADate" maxlength="25" size="25"><img src="pictures/cal.gif" width="16" height="16" border="0" alt="select">
<br>(eg:- 17-12-2013 19:14:58)
</td>
</tr>
</table>
</td>
</tr>
<tr><td> </td></tr>
<tr>
<td width="60%"><table width="100%" cellpadding="0" cellspacing="0">
<tr>
<td align="right"><input type="submit" value="Show Report" class="button1"></td>
</tr>
</table></td>
</tr>
<tr><td> </td></tr>
</table>
</td>
</tr>
</table>
</form>
</body>
</html>
overspeedvalidate.js Code wiil be like this:
function validateForm() {
var todayDate = new Date();
var fromDate=document.myForm.AnotherDate.value;
var toDate=document.myForm.ADate.value;
var fromparts = fromDate.split(" ");
var fromdate= fromparts[0];
var fromtime=fromparts[1];
var fromdayfield = fromdate.split("-")[0];
var frommonthfield = fromdate.split("-")[1];
var fromyearfield = fromdate.split("-")[2];
var fromhourfield = fromtime.split(":")[0];
var fromminfield = fromtime.split(":")[1];
var fromsecfield = fromtime.split(":")[2];
var toparts = toDate.split(" ");
var todate= toparts[0];
var totime=toparts[1];
var todayfield = todate.split("-")[0];
var tomonthfield = todate.split("-")[1];
var toyearfield = todate.split("-")[2];
var tohourfield = totime.split(":")[0];
var tominfield = totime.split(":")[1];
var tosecfield = totime.split(":")[2];
var fromDate = new Date(fromyearfield, frommonthfield-1, fromdayfield,fromhourfield,fromminfield,fromsecfield);
var toDate = new Date(toyearfield, tomonthfield-1, todayfield,tohourfield,tominfield,tosecfield);
if(document.myForm.vehicleId.selectedIndex ==0 ){
alert("Please select vehicle number");
document.myForm.vehicleId.focus();
return false;
}else if (document.myForm.speed.selectedIndex == 0){
alert("Please select Speed");
return false;
}else if (document.myForm.AnotherDate.value == null || document.myForm.AnotherDate.value == ""){
alert("Please select FromDate");
document.myForm.AnotherDate.focus();
return false;
}else if (fromDate.getTime()>todayDate.getTime()){
alert("Please select FromDate lessthan CurrentDate");
document.myForm.AnotherDate.focus();
return false;
}
else if (document.myForm.ADate.value == null || document.myForm.ADate.value == ""){
alert("Please select ToDate");
document.myForm.ADate.focus();
return false;
}else if(toDate.getTime()>todayDate.getTime()){
alert("Please select ToDate lessthan CurrentDate");
document.myForm.ADate.focus();
return false;
}else if (fromDate.getTime()>toDate.getTime()){
alert("Please select FromDate lessthan ToDate");
document.myForm.AnotherDate.focus();
return false;
}
return true;
}
when i consider only upto date it is working fine but when i consider both date and time it is not working can any solve my problem
I've tried a javascript function as in the following fiddle it works for me.
Just comapare two date variables with date-time format it will works
http://jsfiddle.net/fNPvf/1307/
function change(){
// new Date(Year, Month, Date, Hr, Min, Sec);
var dateOne = new Date(2012, 04, 20, 14, 55, 59);
var dateTwo = new Date(2012, 04, 20, 12, 10, 20);
//Note: 04 is month i.e. May
if (dateOne > dateTwo) {
alert("Date One is greather then Date Two.");
}else {
alert("Date Two is greather then Date One.");
}
}

JavaScript White Space Validation not working

I have written JSP code and I need to check white space validation, But it is not working can someone tell me the reason. While clicking submit button it must validate for white space and characters.
JSP Code
<%--
Document : LapsePeriodicFeedBack
Created on : Dec 7, 2012, 2:50:28 PM
Author : Admin
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%# page import="java.util.*" %>
<%#page import="PeriodicFeedBack.PeriodicType"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>LapsePeriodicList</title>
<script>
function validateForm(){
var selectindex=document.forms["lapse"]["periodmenu"].selectedIndex;
var whitespace = new RegExp("^\w*$");
var x= document.forms["lapse"]["lapsedays"].value;
var textlength=document.forms["lapse"]["lapsedays"].length;
if(x==""){
alert("Days Cant Be Empty");
return false;
}
if(x==whitespace){
alert("White Spaces are not Allowed");
return false;
}
if(selectindex==0){
alert("Please select Days from menu");
}
}
if(x=="/\\s"){
alert('Sorry, you are not allowed to enter any spaces');
x.value=x.value.replace(/\s/g,'');
}
</script>
</head>
<body>
<form method="post" name="lapse" onsubmit="return validateForm()">
<table width="500px" border="1" align="center" style='border-collapse: collapse;font: 13px Arial, Helvetica, sans-serif;' bordercolor='#000000'>
<tr style="color:'#ffffff';background-color:#CA1619;background-repeat:repeat-x;font: 13px Arial, Helvetica, sans-serif;">
<td colspan="4" align="center">
<font color="#ffffff" > <b>Periodic Feedback List</b></font></td></tr>
<tr>
<td align="center">
Periodic Feedback Days</td>
<td align="center">
<select id="periodmenu">
<option> Select</option>
<%
PeriodicType p = new PeriodicType();
ArrayList periodicList = p.getPeriodicType();
for (int i = 0; i < periodicList.size(); i++) {%>
<option>
<% out.println(periodicList.get(i));
}%>
</option>
</select></td>
</tr>
<tr>
<td align="center">
Lapse Days </td>
<td align="center">
<p>
<input name="lapsedays" type="text" id="lapsedays" onkeyup="nospaces(this)"/></p>
<input name="Submit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
<p>
</p>
</body>
</html>
You can't use x==whitespace to check x against a regular expression. Use the following:
whitespace.test(x);
That'll return true or false.
In addition, you should not use new RegExp for this, you should instead use the literal operators:
var whitespace = /^\w*$/;

Categories

Resources