Next and Back Button in Form with Radio Button - java

i want to put 10 questions from database and a timer on a html form.
questions to be displayed one by one
when i click next button next question will be shown
and when clicked back button previous question should be shown
<form name="form1" bgcolor="red" action="resultbyme.jsp" method="POST">
<div style="background-color:orange;">
<% qno=n+1;
ques=rs.getString(4);
op1=rs.getString(5);
op2=rs.getString(6);
op3=rs.getString(7);
op4=rs.getString(8);
%>
<br>Q.<%=qno%>--><%=ques%></br>
<input type="radio" name="opt<%=qno%>" value="<%=op1%>" /><%=op1%><br>
<input type="radio" name="opt" value="<%=op1%>" /><%=op2%><br>
<input type="radio" name="opt" value="<%=op1%>" /><%=op3%><br>
<input type="radio" name="opt" value="<%=op1%>" /><%=op4%><br>
<%
}
} //end for
}
catch(SQLException e)
{
out.println("erorr in sql ") ;
}
%>
<div bgcolor="blue"><input type="submit" value="submit" name="submit test" /></div>
</div>
</form>

You can load everything in different div, and show them one after another with JavaScript.

You will have a common header and which will handle you timer. your html body will dynamically change (Use ajax for this ) based on user click next or back.
Better to maintain questions numbers hidden in next and back button. So in AJAX call you can get question number and pass to server to get that specific question and. You can display it in defined span or div tag.
<div id="questionId"> My question is here </div>
inside javascript
function loadQuestion(questionNo){
$.ajax({
type: "POST",
url: 'projectName/showQuestion.action',
data: "quesionNo="+questionNo
success: function(data) {
document.getElementById('questionId').innerHTML =data;
}
});
}
This is just a guide and you change thing to suit your approach

Related

How to get selected radio button in div of form in jsp?

I have a form has many divs and actions to a servlet to check whether user makes right or wrong every questions. Each div is a multiple choice question created by java code.
jsp file
<form id="doExam" name="doExam" action="CheckAnswer" method="POST">
<% for (int i = 0; i < NumofQuestions; i++) {
Question q = (Question) exam.get(i); %>
<div id="question">
<p> <b>Question <%=i+1%>:</b> <%=q.getContent()%></p>
<p> <b>A.</b> <input type="radio" name="<%=q.getId()%>" value="A"> <%=q.getAnswerA()%> </p>
<p> <b>B.</b> <input type="radio" name="<%=q.getId()%>" value="B"> <%=q.getAnswerB()%> </p>
<p> <b>C.</b> <input type="radio" name="<%=q.getId()%>" value="C"> <%=q.getAnswerC()%> </p>
<p> <b>D.</b> <input type="radio" name="<%=q.getId()%>" value="D"> <%=q.getAnswerD()%> </p>
</div>
<%
String selected = request.getParameter(q.getId()); // ****** //
list_answer.add(selected);
}
session.setAttribute("user_answer", list_answer); %>
<input type="submit" value="Finish Exam">
</form>
The variable selected (at the line has comment) always got null. So that all of the list_answer items are null too. Are there any ways to get the selected radio button of the question div?
What you are trying to achieve is that selecting a radio button and setting the value of it to String selected in the same jsp/Servlet file.
This is impossible using request.getParameter(q.getId()), since a HttpServletRequest is created once you submit the form.
After form submission, the request parameters will be set to request object and it is accessible to your action servlet/jsp CheckAnswer. That's why you are always getting nullin the current page.
One of the solution to set radio button value to session object can be done using javaScript.
Check this article Pass variables from client side to server side

hidden div doesn't appears where i want it to appear

This is my first on posting here. I hope you understand my question!
<script language="JavaScript">
function setVisibility(id, visibility)
{
document.getElementById(id).style.display = visibility;
}
</script>
<% for(cart c: cart) {%>
<td> ......</td>
<td> ......</td>
<td> ......</td>
<td> ......</td>
<td>
<input type=button name=type value='Edit' onclick="setVisibility('DivQTY', 'inline');">
<div id="DivQTY" style="display: none">
<input type="text" name="qty">
<form action="doEditCart.jsp?id=<%= c.getID() %>" method="post">
<input type="submit" value="Save">
</form>
</div>
</td>
<% }%>
This Shows a table and, in every row, shows a "Edit" button.
My problem here is that, if i press any "Edit" button in any row, "TextBox" and "Save" button appears only in the first row.
In this capture I pressed Edit in the fourth row.
How to show TextBox and Save button in the row that I pressed the edit button?
Thank you.
Your for statement is creating different <div> elements with the same id attribute, what is not allowed.
As a solution, you could use the cart's id (c.getID()) as part of the div's id:
(...)
<input type=button name=type value='Edit' onclick="setVisibility('DivQTY<%=c.getID()%>', 'inline');">
<div id="DivQTY<%=c.getID()%>" style="display: none">
(...)
The problem is at below line where you are using same id for each div
<div id="DivQTY" style="display: none">
Element IDs should be unique within the entire document. Use different dynamic IDs for each element in HTML.
HTML 4.01 specification says ID must be document-wide unique.
Read more about it here Two HTML elements with same id attribute: How bad is it really?

How to keep dynamicly added controls ater postback? Javascript, JSP

Good Morning all. I have an issue that I am trying to solve but I am stuck, partially due to me not having a full understanding of JSP/ Java platform, and not having a full understanding of what/ how to implement my code in the right way. I do have an ASP background, so I am a bit familiar with some concepts.
The issue I am running into is: I am trying to populate a dynamic label and text box to appear on a webpage (JSP). I have successfully been able to populate the textboxes with a piece of JavaScript code, however, when I submit the form (on Postback) my dynamic controls are gone but all of my static controls are still present. I need to find a way to keep my information in the dynamic control on submit as well. The form does not submit when I have errors but when the form finish rendering all information and dynamic text are all lost.
My Solution: I have decided to use hidden fields to hold this information but I am unable to fire off the hidden fields after form submit: Please have a look below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript">
function validateForm(){
var x=document.forms["myForm"]["fname"].value;
if (x==null || x=="" && document.getElementById('two').value==1){
alert("EMPTY");
document.getElementById('text').style.display = "block";
return false;
}else{
document.myform.submit();
}
}
function display(el) {
if (el.value == "two") {
document.getElementById('text').style.display = "block";
}else {
document.getElementById('text').style.display = "none";
document.getElementById('dynbox').value = '';
}
}
</script>
</head>
<body>
<form name="myForm" action="demo_form.asp" onsubmit="return validateForm()" method="post">
<label >First Name</label> <input type="text"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" onclick="validateForm()" value="Submit"/>
</div>
</form>
</body>
</html>
What I am trying to do is select the "Not Eligible" option and type some text in the text box 'mytext' then press submit. Once I press submit, and if the First Name textbox is not filled in, then I want to trigger my hidden textbox so that I won't loose my information in my dynamically created textbox.
I hope this makes sense. I am not sure of how to do in JSP. Can someone give guidance on how to get my expected results? Keeping dynamic controls after Postback?
Thanks in advance.
One thing first: don't let the names Java and Java-Script confuse you. They have (almost) nothing in common. What you are using here is Java-Script only (no Java, no JSP anywhere).
Anyway, I think it is the condition in your validateForm() function that does not work.
I tested it a little bit and it works with these changes:
your form
<form name="myForm" action="test.html" method="get" onsubmit="return validateForm();">
<label >First Name</label> <input type="text" id="firstName"/>
<div>
<input type="radio" name="radio1" id="one" value="one" onchange="display(this);"/>Eligible
</div>
<div>
<input type="radio" name="radio2" id="two" value="two" onchange="display(this);"/>Not Eligible
</div>
<div id="text" class="glassy" name="mytext" style="display:none;">Other: <input type="text" id="dynbox"/>
</div>
<div>
<input type="hidden" name="mytext" value="${mytext}" />
<br></br>
<input type="submit" value="Submit"/>
</div>
</form>
I simply changed the first input and gave it an ID (since I couldn't find the id 'fname' anywhere), so we can access it with JavaScript.
The next thing is your submit button. You had an additional onclick="validateForm()"; there – which indeed calls the validateForm function but does not listen to the returned value (it executes the function.. nothing more). So the onsubmit="return validateForm()" is enough.
your validate function
function validateForm() {
var x = document.getElementById('firstName').value;
if ((x == null || x == "")) {
alert("EMPTY");
// document.getElementById('text').style.display = "block";
return false;
} else {
return true;
}
}
x can now be retrieved by the element's id (which I find easier).. Anyway, the if condition was one of the problems. In your form you set the value of your radio button 'two' to two. But in the if condition you ask if could be 1... which (in my understanding) should never happen. I just removed it to show you that your function works like this. If you want to check the state of the second radio button, you can test it like this:
if(document.getElementById('two').checked == true)
or even better
if(document.getElementById('two').checked)
one last thing: in your else statement, you can simply return true instead of calling submit.. because here:
onsubmit="return validateForm();"
you ask your validateForm() function to give you either true and then submit or false and then stop submitting.
Oh, one last thing (it'S the last, promise): Java and Java-Script handle all && and || in the order: first ´x==null´ would be tested and then x=="" && document.getElementById('two').value==1 would be evaluated together (&& has a stronger binding than ||).. Just for your information :)

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>

checking which check boxes are selected using JAVA ( a jsp)

I am trying to create a servlet that displays a simple form with checkboxes , when the user selects the number of checkboxes he wants and clicks on a "confirm" the POST request in my servlet checks for which boxes have been checked and queries the database based .
I am unsure on how to do this in Java as the user may select either 1 or more checkboxes . if somebody could explain this with a small example this would be great.
I am very new to programming and would provide a code snippet if I knew how to do it .
<%# page language="java"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Multiple Checkbox</title>
</head>
<body>
<form name="form1" onsubmit="checkBoxValidation()">
<h3>Select your favorite Fruits</h3>
<p><input type="checkbox" name="fruit" value="Mango"/>Mango</p>
<p><input type="checkbox" name="fruit" value="Apple"/>Apple</p>
<p><input type="checkbox" name="fruit" value="Grapes"/>Grapes</p>
<p><input type="checkbox" name="fruit" value="Papaya"/>Papaya</p>
<p><input type="checkbox" name="fruit" value="Lychee"/>Lychee</p>
<p><input type="checkbox" name="fruit" value="Pineapple"/>Pineapple</p>
<p><input type="submit" value="submit"/>
</form>
<%String fruits[]= request.getParameterValues("fruit");
if(fruits != null){%>
<h4>I likes fruit/s mostly</h4>
<ul><%for(int i=0; i<fruits.length; i++){%>
<li><%=fruits[i]%></li><%}%>
</ul><%}%>
</body>
</html>
Run this sample jsp on your web container to get some basic idea on how it works. You need to move the display logic on this page that gets request parameter into your servlet code on form submission. This example can be found from here. Hope this would help.
This is actually the HTML form behavior question. When you check a few checkboxes with one "name" attribute and different "value" attributes and press submit button, your browser will send request to the server with checked checkbox values. So you can get value names from this url parameters.
For example:
<form name="input" action="html_form_action.asp" method="get">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car
<br><br>
<input type="submit" value="Submit">
</form>
If you check both of checkboxes your server will receive this parameters like so:
http://example.com/your_page.jsp?vehicle=Bike&vehicle=Car
After that you can get values like this:
String checkboxValues = request.getParameter("vehicle");
checkboxValues gets all values separated by comma.
In your servlet you would use getParameter() like so:
request.getParameter( "id_of_checkbox" )
That function returns null if the the box is not checked. So you could do something like:
boolean myCheckBox = request.getParameter( "id_of_checkbox" ) != null;
Now myCheckBox is true if checked, false if not checked.
This one might be neater if you just want the output. Assuming you're using jstl libraries, which I prefer because it makes your pages cleaner:
<c:forEach var='fruitValue' items='${paramValues.fruit}'>
${fruitValue} <br>
</c:forEach>

Categories