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 :)
Related
I'm making a form to add events to a list but I need to be able to see in that form the previous events from that list. I have a jsp that shows a list of events but it takes an attribute usually added by the controller when you access the list directly from the browser.
So how can I add the list jsp filling that attribute so it shows a list and not just the headers?
I have alreay included the jsp using
<jsp:include page="comp_list.jsp"></jsp:include>
And it shows the headers but as there is no attribute it shows no list. I tried adding attributes to the include like:
<jsp:include page="comp_list.jsp">
<jsp:attribute name="compensaciones">
${compensaciones}
</jsp:attribute>
</jsp:include>
But when I do it it shows an error telling me that this cannot be done.
Also tried params but that would not be the answer for me because params are treated in the controller and not in the jsp itself.
I'm just getting the header of the list which is fine, but i would like to see the list.
Edit: this is how i build the list in case you are wondering
<tbody>
<c:forEach var="comp" items="${compensaciones}">
<td>${comp.getSomething()}</td>
...
</c:forEach>
</tbody>
<jsp:include page="pagename.jsp" />
i thing you are not provide extension in your include tag
Sometimes since I've had prior experience back in the days with HTML and PHP, we simply just would include things like navigation and header for easier management.
I'm unsure for what purpose you're including JSP, but here's an example of how I've done it since I include JSP if a boolean is true.
The site that is accessed:
<div class="row">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<%
if (loggedin) {
%>
<%# include file="includes/profile.jsp" %>
<% } else {
out.println("<div><h2>You aren't logged in!</h2></div>");
}
%>
</div>
<div class="col-lg-2">
</div>
</div>
And the top and bottom of the JSP file I'm including doesn't contain things like head, title, html, body etc.
<%
User currUser = null;
currUser = (User) session.getAttribute("user");
%>
<div>
<h2>Du er logget ind, velkommen <% out.println(currUser.getUsername().toUpperCase()); %></h2> <br>
<h5>Din Saldo: <b><% if (currUser.getBalance() < 0) { out.println("<font color='red'>" + currUser.getBalance() + "</font>");} else { out.println("<font color='green'>" + currUser.getBalance() + "</font>");} %></b></h5>
<br>
<form class="form" method="post" action="#">
<h4>Oplysninger: </h4>
<h6>
For at ændre oplysninger skal du indtaste dit kodeord!
</h6>
Nuværende Kode: <input type="password" class="form-control" placeholder="kodeord" name="password" required>
<hr>
Email: <input type="text" class="form-control" value="<% out.println(currUser.getEmail()); %>" name="email"> <br>
Brugernavn: <input type="text" class="form-control" value="<% out.println(currUser.getUsername()); %>" name="username"> <br>
<input type="submit" class="btn btn-default" value="Indsend Oplysninger" />
</form>
</div>
When importing JSP into JSP, it's important to know that they will conflict if 1. Duplicate Local Variables. 2. Certain HTML tags aren't correct.
Your intended use seems very complicated to me since I'm not quite understanding it, sorry :3 but if you can't get it working consider to throw it to a session and if it's a one time use then remove it once you used it.
This is working from dacades
<%# include file="../scripts/standard_head_declaration.jsp" %>
I have a .jsp file of a basic chat with a bot, the page is designed as a div that should hold the messages that outcome or income from a form.
The form has one input line that should hold the message.
I want to call a java function that's in a different .java file from the div only after the form is submited
<div id="wrapper">
<div id="menu">
<p class="welcome">Welcome, <b>
<%
if (ctx.isLoggedIn()) //if there is someone in the current session
{
String name = ctx.getName(); // puts the name in the page
out.write(name); // same as last row
}
%></b></p>
<p class="logout"><a id="exit" href="#">Exit Chat</a></p>
<div style="clear:both"></div>
</div>
<div id="chatbox" style="overflow-y: scroll;">
<%
//the place I want to call the function
%>
</div>
<form name="message" action="#" method="post">
<input name="usermsg" type="text" id="usermsg" size="63" oninput="buttonEnabled()"/>
<input name="submitmsg" type="submit" id="submitmsg"/>
</form> <!-- the form that is served -->
</div>
ctx is defined as an object from a class I created
Context ctx = new Context(pageContext);
I tried to call the function like this-
<%
if(request.getParameter("usermsg").toString().length() > 0)// not empty
out.write(ctx.handleMessages());
%>
but It didn't work for some reason.
the function handleMessages() has a queue that contains all of the messages from the server and from the client and returns a String that is already build as an HTML code-
returnedMsg += "<b>"+message.getUser()+"</b> - <a style='color:gray;'>"+message.getTime()+"</a>";
returnedMsg += "<br>";
returnedMsg += "<a>"+msg.getText()+"</a>";
returnedMsg += "<hr>";
So every chat message should look like that-
It would really help me if someone knows how to call handleMessages() from that div when the form is submited.
Thank's ahead.
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>
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
Iam new to JSP and i can't seem to figure out how to run code only when the user clicks on the button..here's my code:
$
<form action="list_computers.jsp" method="post">
Search:
<input type="text" name="FromTextBox1"/>
<input type="submit" value="Search it!" >
<%
String TheSearch = (String)request.getParameter("FromTextBox1");
String GetIt = Searcher(TheSearch);
out.println(GetIt);
%>
</form>
The Searcher() is a function i declared above this. Any help would be really appreciated.
You need to do something like
if (request.getParameter("submit") != null) {
// do work here
}
You also need to give a name to your button
<input type="submit" value="Search it!" name="submit">
When user clicks (or presses enter), request['submit'] will be equal to "Search it!"
I highly recommend moving this logic to the top of the page or even better to a controller.
you need to use javascript to check for the onclick event here's a little example with JQuery
$("input[type='submit']").click(function(){
//do your thing
// use event.preventDefault(); to stop submission if need
});