Use a div as a submit button in JSP Servlets - java

I need a way to use a div as a submit button to send a form request to a Servlet, Or is there any other way to solve my problem. "logoutbutton" is the div.
<div class="logoutbutton">
<table width="100%">
<tr>
<td width="50px"><img src="img/usericon.png" width="44" height="44" /></td>
<td><a style="font-size:12px; font-family:Verdana, Geneva, sans-serif; color:#FFF"><% out.print(session.getAttribute("userid")); %></a><br />
<a style="font-size:20px; font-family:Verdana, Geneva, sans-serif; color:#FFF">Log Out</a>
</td>
</tr>
</table>
</div>

You need to call the your servlet which handles logout action for the link. You can do it using
Logout
After doing this, you can logout from doGet method of LogoutServet

I would use jquery for this and then listening for events on DOM obejcts is a peice of cake.
$(".logoutbutton").click(function () {
window.location.href = 'logout.url';
});
or
$(".logoutbutton").click(function () {
$.post( "logout.url" );
});

That's easy, use the 'onclick' event:
<div style="cursor:pointer;" onclick="submitForm();">...</div>
On the onclick you can also use
window.location.href='LogourServletUrlPattern';
if you don't want to call a function and invoke the sevlet directly

Wrap your DIV as part of your form and submit the form on clicking on DIV
<html>
<head>
<script>
function formSubmit()
{
document.getElementById("frm1").submit();
}
</script>
</head>
<body>
<form id="frm1" action="form_action">
First name: <input type="text" name="fname"><br>
Last name: <input type="text" name="lname"><br>
<div class="logoutbutton" onclick="formSubmit()">
<table width="100%">
<tr>
<td width="50px"><img src="img/usericon.png" width="44" height="44" /></td>
<td><a style="font-size:12px; font-family:Verdana, Geneva, sans-serif; color:#FFF"><% out.print(session.getAttribute("userid")); %></a><br />
<a style="font-size:20px; font-family:Verdana, Geneva, sans-serif; color:#FFF">Log Out</a>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Use jquery for achieving this with ease.
In the DOM
<div id="logout-button">Logout</div>
In javascript/jquery
$("#logout-button").click(function () {
alert("ajax call to end session");
});
Even if your not using jquery you could use the above to get a round about idea on how to achieve this.

You can use javascript to capture click event on the logoutbutton div and submit the form. Assuming you have a form with id 'myform':
<div class="logoutbutton" onclick="document.getElementById('myform').submit()">
Note that using this method the div isn't treated as a hyperlink by the browser, hence you can't do right-click-and-open-in-new-tab.
If your javascript gets complicated consider using library such as jquery.

Related

Print only html table using javascript

I have the following basic html table with a Java function to print only the table content However the Print button does nothing when clicked,I figure probably the java coding is the issue, however it is not working could I get a third pair of eyes to assist please
<html>
<body>
<table border="1" cellpadding="3" id="printTable">
<tbody><tr>
<th>First Name</th>
<th>Last Name</th>
<th>Points</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td>Adam</td>
<td>Johnson</td>
<td>67</td>
</tr>
</tbody></table>
<br />
<br />
<button>Print me</button>
<script>
function printData()
{
var divToPrint=document.getElementById("printTable");
newWin= window.open("");
newWin.document.write(divToPrint.outerHTML);
newWin.print();
newWin.close();
}
$('button').on('click',function(){
printData();
})
</script>
</body>
</html>
When working with javascript, it is often useful to look at your browser's console. After opening this page, mine has the error:
ReferenceError: $ is not defined
$ is a global variable inserted by jQuery. Try adding
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
to the code. This will include the jQuery library.
The call to the javascript function is not correct. When you're using the '$' symbol it means that you're using JQuery. You have 2 options:
1 - Include the jquery library to your page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
2 - Call the javascript function directly on the button on the 'onclick' event. This is the best option in your case:
<button onclick="printData()">Print me</button>
Change this var divToPrint=document.getElementById("printTable");
to this var divToPrint=document.getElementById("<%=printTable.ClientID>");
and add jquery library <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

How to pass text box values to next page using Hyper link in jsp

I Want to pass my text box values in the jsp through hyperlink .both the text box and Hyperlink are in the same jsp page.How can i achieve this
use <a> tag & using QueryString pass the value of textbox to other JSP page.
<a href="pass.jsp" onclick="addTextBoxData(this)">
<script>
function addTextBoxData(e){
e.href = e.href + "?textbox=" + document.getElementById('textboxID').value;
}
</script>
you just need to pass reference of tag using this.
then it ll append data ?textbox=textbox value
so it ll be /pass.jsp?textbox=txt
You use GET method, for example, Create file index.jsp
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title></title>
</head>
<body>
<form method="get" action="index.jsp">
<table>
<tr>
<td><label for="txtUserName">Username: </label></td>
<td><input type="text" id="txtUserName" name="txtUserName"/><br/></td>
</tr>
<tr>
<td><label for="emailUser">Email: </label></td>
<td><input type="email" id="emailUser" name="emailUser"></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
Go to: http://localhost:8080/index.jsp (I use default port 8080 with Tomcat)
When enter
username: myname
email: myname#example.com
and press Submit button. See browser's address bar:
http://localhost:8080/index.jsp?txtUserName=myname&emailUser=myname%40example.com

setting class and other attributes for spring form tag element

I have the following page and it does not load
<form:form action="/test.htm" method="post" commandName="demoForm" >
<div id="testSection" style="margin-top: 1.5%;margin-left: 3.5%;">
<span class="test-container">
<label>UserName</label>
<span class="test-container-right">
<form:input path="username" value="${UNAME}" class="text simpleTextField" maxlength="200" style="width:60%" disabled/>
</span>
</span>
<span style="width:auto; padding-left: 30%; padding-bottom: 4%; text-align:center; float:right; clear:both;">
<input type="submit" class="btn" style="width:auto;" value="Save" />
</span>
</div>
</form:form>
but when I change it to
...
<span class="test-container-right">
<form:input path="username" />
</span>
...
it works and loads correctly. Why am I not allowed to set html properties for form:input spring tag. How can I achieve this? On inspecting the element it expands to be
<input id="username" type="text" value="" name="username"></input>
I need to populate its value as well as provide it with a class and additional attributes like width.
Ok I resolved some part of it. Looks like tags used inside form:input tag are different than regular html tags. All of them are listed here. For ex style is cssStyle.
So I change my code to
<form:input path="username" cssClass="text simpleTextField" maxlength="200" cssStyle="width:60%" disabled="true"/>
and now it works..
I still don't know how to populate value in this input. These seems no equivalent of value keyword.
#Aniket You actually have an equivalent , consider in a case you have to populate the select box with the values from the model attribute . You can make use of items attribute.
For instance ,
<tr>
<td>City :</td>
<td><form:select path="city" items="${cityList}" /></td>
</tr>
It will generate the select with the the list of objects.
cityList here refers the object that has been sent from the server side.
Hope this helps !

How to add ajax action to jsp page?

I have to add ajax action to date field. When user choose appropriate date, it should show at table all free apartment.
How to implement this at jsp page. I'm newly at JavaEE.
Here is content of page:
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%# page errorPage="error/errHandler.jsp" %>
<jsp:include page="/WEB-INF/jspf/header.jspf" />
<html>
<head>
<title>Reservation an apartment</title>
<h1 align="left">Reservation an apartment</h1>
</head>
<body>
<form method="post" action="${pageContext.request.contextPath}/bookRoom">
<div class="reservation-group" align="left">
<label class="places-label">Couch places at room</label>
<span class="selections">
<select id="r_select">
<option>select</option>
<option>1 person</option>
<option>2 persons</option>
<option>3 persons</option>
<option>4 persons</option>
</select>
</span>
</div>
<br/><br/>
<div class="reservation-group" align="left">
<label>Star rating</label>
<select>
<option>select</option>
<option>2 stars</option>
<option>3 stars</option>
<option>4 stars</option>
<option>5 stars</option>
</select>
</div>
<br/><br/>
<div align="left">
<label>Check-in date</label>
<input type="date" placeholder="yy/mm/dd"/>
</div>
<br/><br/>
<div align="left">
<label>Check-out date</label>
<input type="date"/>
</div>
<br/><br/>
<div class="register-group" align="left">
<div class="selections">
<input type="reset" value="Reset" class="btn" />
<input type="submit" value="Register" class="btn" />
</div>
</div>
</form>
</body>
</html>
How does this ajax technologist works on jsp in general? Do we need to use javascript or jquery? If yes, how exactly will be right.
Looking of the page:
I want to understand this implementation. Any suggestions are appreciate.
Use onchange event as ,
<input type="date" placeholder="yy/mm/dd" onchange="sendAjax()" id="checkInDate" />
You jquery will be ,
<script type= "text/javascript">
$( document ).ready(function() {
});
function sendAjax() {
var checkInDate= $("#checkInDate").val();
//var checkOutDate= $("#checkOutDate").val();
$.ajax({
type: "POST",
url: "You URL path"
data: "checkInDate" + checkInDate,
dataType: "html",
success: function(response) {
//alert("Success : "+response);
if(response != null && response !="" && response !="null"){
//do you stuff here
}
},
error: function(e) {
alert('Error: ' + e.message);
},
});
}
</script>
This has nothing to do with the type of server-side view rendering technology you are using (in your case JSP), it's a question of having some JavaScript code react on a change in the date select box and then trigger a call to a server function that returns the available apartments given the entered date.
JQuery is JavaScript, it's a commonly used JavaScript framework. And yes, you could very well use it for this task. Just add an id to your date select box (for example "checkindate"):
<input id="checkindate" type="date" placeholder="yy/mm/dd"/>
and then use JQuery to attach code to the change event which calls your server with the selected date:
$(document).ready(function() {
$("#checkindate").change(function(event) {
var selectedDate = event.target.value;
$.get("/your/server/function?selectedDate=" + selectedDate, function(data) {
// populate list with data
}, "json");
});
});
Your server function will have to read the query parameter "selectedDate" and with that construct a list of available apartments in (for example) JSON format and return that to the client.
Use onChange event and and send the ajax call on onChange event.
You can use onClick,onblur() event too
<script>
function onDateChange(){
//Alert OnChange is Called
alert("Date Changed");
//Send ajax call
}
</script>

JavaScript in liferay portlets

Am using Liferay portal 6.1.1 CE.
In my liferay portlets jsp page - view.jsp, I have a form with 2 textfields and 2 radio buttons (user can select only one) and a submit button.
When I click on any of the radio buttons, control goes to a script function which is working properly.
Now I want to pass the values of 2 textfields to the script function. I tried a lot, but no use.
How can I achieve this?
Help me..Thanks in advance.
<script>
function dif()
{
}
</script>
<form name="<portlet:namespace/>fm" method="post" action="<%=updateBookURL.toString()%>">
<table>
<tr>
<th>Leave Application</th>
</tr>
<tr>
<td>Employee <font color=red>*</font></td>
<td>
<input type="text" name="<portlet:namespace/>name"/>
<input type="text" name="<portlet:namespace/>eid" />
</tr>
<td>
Date <font color=red>*</font>
<input type="text" id="<portlet:namespace/>fd" name="<portlet:namespace/>
</td>
<td>
<input type="radio" name="<portlet:namespace/>f" id="f" value="1st half" onClick="f()"/>
First Half&=
<input type="radio" name="<portlet:namespace/>f" id="f" value="2ndhalf" onClick="f()"/>
Second Half
</td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="save data" size="100px"/></td>
</tr>
</table>
</form>
Getting the value of the text in javascript function is nothing new in liferay it is plain old javascript, following are some links and examples which would help you (the code which I have written would go in your custom function you define within the <script> ... </script> tags):
Get input text value using:
var fdTextValue = document.getElementById("<portlet:namespace/>fd").value;
Get input text value using jQuery (the only problem with this is you have to include jQuery library in your portlet or theme, since starting from Liferay-6 you have Alloy UI included by default):
var fdTextValue = $("#<portlet:namespace/>fd").val();
/* or */
var fdTextValue = $("#<portlet:namespace/>fd").attr('value');
Get input text value using Alloy UI of Liferay:
AUI().use(function(A) {
var fdTextValue = A.one('#<portlet:namespace/>fd').get('value');
/* or */
var fdTextValue = A.one('#<portlet:namespace/>fd').val();
});
Some of the following links might also help you using Alloy UI:
Working with Elements and Events with Alloy UI.
Alloy UI API
It is very simple.
on click event of then in js define this function.
<script>
function callFun()
{
// Here you can use jquery easily
var name = $("#name").val();
alert(name);
}
</script>

Categories