I have two html drop down list, their value are retrieved from the database by using jsp.
<%
String query =" SELECT question_text,question_id FROM questions WHERE id = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1,request.getParameter("QID"));
ResultSet rs = stmt.executeQuery();
if(!rs.next()) {} else {%>
<form action="#" method="post">
<p> First Question </p>
<select name="currentQuestion">
<%do{%>
<option value="<%=rs.getString("question_id")%>"><%=rs.getString("question_text")%> </option>
<%}while(rs.next());}%>
</select>
<%
String query =" SELECT question_text,question_id FROM questions WHERE id = ? AND question id != ? ";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1,request.getParameter("QID"));
stmt.setString(2,CHOOSEN QUESTION);
ResultSet rs = stmt.executeQuery();
if(!rs.next()) {} else {%>
<p> Next Question </p>
<select name="currentQuestion">
<%do{%>
<option value="<%=rs.getString("question_id")%>"><%=rs.getString("question_text")%></option>
<%}while(rs.next());}%>
</select>
</form>
Now, I what when the user choose a specific question from the first drop down list, the value of the second drop down list does not include that question ?
is anyone know how to do that ?
You don't set CHOOSEN QUESTION anywhere in the code.
You forgot he id and name tags in the option element.
CHOOSEN QUESTION is an illegal name for a variable since it contains a space.
You can't do it the way you're trying to do, cause this code runs on the server-side before the user chooses an option. What you probably want to do is load all the options (if there aren't too many of them) and create a JS/jQuery that will refresh the second dropbox on the event onChange of the first dropbox (before the user chooses an option - you'll probably want to have the second dropbox disabled)
Another thing that you probably want to do is create a form which will eventually submit the user's choices to a JSP (server-side).
You can also achieve the same behavior using AJAX, you can find an example of how to do it here.
UPDATE (example code for changing options using JS):
<html>
<head>
<script type="text/javascript" >
<!-- hide
function update(x){
if (x != "null") {
if (x == "1") {
var jumpmenu2 = document.getElementById("jumpmenu2");
var newOption1 = document.createElement('option');
newOption1.text = "a"; //HERE You'll use newOption1.text = "<?php echo $db_option_text;?>";
newOption1.value = "1"; //HERE You'll use newOption1.text = "<?php echo $db_option_value;?>";
var newOption2 = document.createElement('option');
newOption2.text = "b"; // same like above
newOption2.value = "2"; // same like above
var newOption3 = document.createElement('option');
newOption3.text = "c"; // same like above
newOption3.value = "3"; // same like above
jumpmenu2.remove(jumpmenu2.length-1);
jumpmenu2.remove(jumpmenu2.length-1);
jumpmenu2.remove(jumpmenu2.length-1);
try {
// For standard browsers
jumpmenu2.add(newOption1,null);
jumpmenu2.add(newOption2,null);
jumpmenu2.add(newOption3,null);
}
catch (ex) {
// For Microsoft Internet Explorer and other non-standard browsers.
jumpmenu2.add(newOption1);
jumpmenu2.add(newOption2);
jumpmenu2.add(newOption3);
}
}
else if (x == "2"){
var jumpmenu2 = document.getElementById("jumpmenu2");
var newOption1 = document.createElement('option');
newOption1.text = "d";
newOption1.value = "1";
var newOption2 = document.createElement('option');
newOption2.text = "e";
newOption2.value = "2";
var newOption3 = document.createElement('option');
newOption3.text = "f";
newOption3.value = "3";
jumpmenu2.remove(jumpmenu2.length-1);
jumpmenu2.remove(jumpmenu2.length-1);
jumpmenu2.remove(jumpmenu2.length-1);
try {
// For standard browsers
jumpmenu2.add(newOption1,null);
jumpmenu2.add(newOption2,null);
jumpmenu2.add(newOption3,null);
}
catch (ex) {
// For Microsoft Internet Explorer and other non-standard browsers.
jumpmenu2.add(newOption1);
jumpmenu2.add(newOption2);
jumpmenu2.add(newOption3);
}
}
}
}
// end hide -->
</script>
</head>
<body>
<form name="form1" id="form1">
<select name="jumpmenu" name="jumpmenu" onChange="update(document.form1.jumpmenu.options[document.form1.jumpmenu.options.selectedIndex].value)">
<option value=1>1</option>
<option value=2>2</option>
</select>
</form>
<select name="jumpmenu2" id="jumpmenu2">
<option value=a id=1>a</option>
<option value=b id=2>b</option>
<option value=c id=3>c</option>
</select>
</body>
</html>
Related
I wrote the code below. I want to get element by id_proizvoda and get rest info of that input in a textarea inside of that servlet if selected.
My Code:
Statement st = conn.createStatement();
st.executeQuery("SELECT * FROM prodavnica.proizvodi;");
ResultSet rs = st.getResultSet();
out.print("<select id = 'izabrani' name = 'izabrani'>");
while (rs.next()) {
out.print("<option value = '");
out.print(rs.getString("id_proizvoda"));
out.print("'> ");
out.print(rs.getString("ime_proizvoda"));
out.print("</option>");
If I understood you correctly, what you want is show details of select option in a text area.
To do so, you need JS on your page to modify text area content depending on the choice of select option.
I created a fiddle to give you an idea. Here it is
Here is the sample HTML code:
<select>
<option value='' data-matr='tralala'>Select an option...</option>
<option value=1 data-matr='tralala2'>Option 1</option>
<option value=2 data-matr='tralala3' selected=''>Option 2</option>
<option value=3 data-matr='tralala4'>Option 3</option>
<option value=4 data-matr='tralala5'>Option 4</option>
</select>
<textarea id="result"></textarea>
And here is my sample JS code:
$('select').val(3);
$('select').on('change', function(){
var str="";
$( "select option:selected" ).each(function() {
str = $( this ).attr('data-matr') + " ";
});
$('#result').val(str);
});
All you need to do is to modify your java code slightly to add custom attributes into your options and add necessary JS code to your page to facilitate on change events.
Please note that I used JQuery.
I hope it helps.
I have one jsp and want to disable dropdown list using scriplet without any onclick method or event in dropdown menu
<%
boolean something= true;
if(something){
// here I want to get plc1 using id and want to disable it if it is true
}else{
//do some thing
}
%>
my dropdown html code is here
<td bgcolor='' align="center" ><select id = "plc1" name="place1" onclick="this.parentNode.style.backgroundColor = this.value">
<option value='red'>Park here</option>
<option value='green'>Cancel</option>
</select></td>
how to do it? any hint please?
just use disabled attribute: <select id="plc1" disabled>
<%
String state = "";
if(something){
state = "disabled";
}
%>
<select id="plc1" <%= state %>>
<%
boolean something=false;
String state = "";
if(something){
state = "disabled";
// here I want to get plc1 using id and want to disable it if it is ture
}else{
state = "enable";
}
%>
Html
<select <%= state %> id = "plc1" >
Now its working Thanks
Hello I am new to AJAX and JQUERY/JQUERY(UI), I have an application that has 4 tabs (1,2,3,4).
The first tab is enabled and the last 3 tabs are disabled initially. When the user clicks on the next button in the first tab it goes to the second tab. When the user clicks the button in the second tab it should go to the third tab to review or display the details of the information collected in the database, then the user clicks on the button in the third tab it goes to tab 4.
The problem:
Now clicking on the button in the 2nd tab, what I do is a AJAX post that takes all the form data from tab 1 and tab 2 to a Liferay Portlet Controller class in which it collects the data and insert into a database but does not return any data from this function.
The issue is when I click on the NEXT button in the second tab it goes to third tab but only shows the table header information and not the table row data (i.e its empty). The only way it shows this data is when I physically click on refresh the page browser in which goes back to first Tab then I have to go click on tab 1 and tab 2 again to see the data in the table row which is on Tab 3 that was previously inserted into the database.
Here are my code snippets. Can someone please help in how to resolve this issue? Is this suitable way of implementing this solution?
<script type="text/javascript">
$(document).ready(function () {
var $tabs = $('#tabs').tabs({ selected: 0, disabled: [1,2,3]
});
$("#additem").click(function(e){
//FAULTS
var fault = $('#dd1').val();
var child = $('#childFault').val();
//var childFaultVal = $('#childFault').val;
var how = $('#faultReason').val();
var noteVal = $('#note').val();
var occurenceDate = $('#datepicker').val();
if (fault == ''){
alert("Please select a Stain or Damage");
return false;
}
if (child == ''){
alert("Please select type of "+fault);
return false;
}
if (occurenceDate == ''){
alert("Please select the date that the "+ fault +" occured ");
return false;
}
if (how == ''){
alert("Please select how the incident happened");
return false;
}
$tabs.tabs('enable', 1).tabs("option", "active", 1).tabs('disable', 0);
return false;
});
/* $('#btn-submit').bind('click', function(){ */
$('#btn-submit').click(function(){
//$('#myform').on('submit', function(e){
//$tabs.tabs('enable', 2).tabs("option", "active", 2).tabs('disable', 1);
//FAULTS
var fault = $('#dd1').val();
var childFaultVal = $('#childFault').val;
var how = $('#faultReason').val();
var noteVal = $('#note').val();
var occurenceDate = $('#datepicker').val();
//ITEMS
var itemVal = $('#item').val();
var subitemVal = $('#subItems').val();
var materialVal = $('#material').val();
var locationVal = $('#location').val();
var materialLocVal = $('#materialLoc').val();
if (itemVal == ''){
alert("Please select an Item");
return false;
}
if (subitemVal == ''){
alert("Please select the type of"+itemVal);
return false;
}
if (materialVal == ''){
alert("Please select a material of the "+itemVal);
return false;
}
if (locationVal == ''){
alert("Please a location on the "+itemVal);
return false;
}
if (materialLocVal == ''){
alert("Please select the material location of the"+itemVal);
return false;
}
var form_data = $("form").serialize();
$.ajax({
type: "POST",
url: "<%=renderResponse.encodeURL(reviewClaimURL.toString())%>",
cache: false,
data: form_data,
dataType: "text",
error: function() {
$('#status').text('Update failed. Try again.').slideDown('slow');
},
success: function(response) {
$tabs.tabs('enable', 2).tabs("option", "active", 2).tabs('disable', 1);
},
complete: function() {
setTimeout(function() {
$('#status').slideUp('slow');
}, 3000);
}
});
});
$("#addfault").click(function(){
$tabs.tabs('enable', 0).tabs("option", "active", 0).tabs('disable', 1);
return false;
});
$("#confirm").click(function(){
$tabs.tabs('enable', 3).tabs("option", "active", 3).tabs('disable', 1);
return false;
});
});
HTML CODE TAB 2
<div id="Atab2">
<p id="status"></p>
<div>
<strong> <label>Please Select the Item </label></strong> <select
name="item" id="item"
onChange="<portlet:namespace/>poputlateItemList(this);"
style="width: 200px;">
<option></option>
<c:if test="${itemList != null}">
<c:forEach var="itm" items="${itemList}">
<option value="${itm.text}">
<c:out value="${itm.text}" />
</option>
</c:forEach>
</c:if>
</select>
<div id="<portlet:namespace/>materialText"></div>
<div align="center">
<input type="button" name="btn-submit" class="button"
id="btn-submit" value="NEXT" />
</div>
</div>
</div>
</aui:form>
HTML TAB3
<div id="Atab3">
<div id=someElement>
<p>
<strong>Please review the following items selected. You
could add additional faults or select NEXT to complete your claim</strong>
</p>
<table id="
tfhover" class="tftable" border="1">
<tr>
<th>Fault Selected</th>
<th>Item Selected</th>
<th>Incident Date</th>
<th>Action</th>
</tr>
<c:if test="${newClaimReviewList != null}">
<c:forEach var="review" items="${newClaimReviewList}"
varStatus="theCount">
<%
paragraphID = Helper.getParagraphID();
%>
<c:set var="myCount">${theCount.count + 100}</c:set>
<c:set var="myChildFault">${review.childFault}</c:set>
<c:set var="myItem">${review.item}</c:set>
<c:set var="myIncidentDate">${review.incidentDate}</c:set>
<c:set var="myId">${review.id}</c:set>
<%
String myCountVal = (String) pageContext
.getAttribute("myCount");
String myChildFault = (String) pageContext
.getAttribute("myChildFault");
String myItem = (String) pageContext.getAttribute("myItem");
String myIncidentDate = (String) pageContext
.getAttribute("myIncidentDate");
String myId = (String) pageContext.getAttribute("myId");
String rowName = "my_row_" + myCountVal;
%>
<div class="aui-ctrl-holder" id=<%=paragraphID%>>
<liferay-ui:icon-menu>
<tr id=<%=rowName%>>
<td>${review.childFault}</td>
<td>${review.item}</td>
<td>${review.incidentDate}</td>
<td><liferay-ui:icon-menu>
<%
String taglibUrl = "javascript:"
+ renderResponse.getNamespace()
+ "removeFault('" + myCountVal + "','"
+ myId + "')";
%>
<liferay-ui:icon-delete url="<%=taglibUrl.toString()%>" />
</liferay-ui:icon-menu></td>
</tr>
</liferay-ui:icon-menu>
</div>
</c:forEach>
</c:if>
</table>
</div>
<br /> <br />
<div align="center">
<button id="addfault">ADD FAULT/ITEM</button>
<button id="confirm">NEXT</button>
</div>
</div>
/******************************
*
* #param actionRequest
* #param actionResponse
***********************************/
#SuppressWarnings("unchecked")
#ProcessAction(name = "reviewClaim")
public void postData(ActionRequest actionRequest,ActionResponse actionResponse){
ActionUtil.createReviewClaimDetail(actionRequest,hows,items,claim,policyId);
actionResponse.sendRedirect(viewCreateNewClaim+"?id="+policyId+"&action=review");
}
Here is the code to populate the HTML table
Fault Selected
Item Selected
Incident Date
Action
<c:if test="${newClaimReviewList != null}">
<c:forEach var="review" items="${newClaimReviewList}"
varStatus="theCount">
<%
paragraphID = Helper.getParagraphID();
%>
<c:set var="myCount">${theCount.count + 100}</c:set>
<c:set var="myChildFault">${review.childFault}</c:set>
<c:set var="myItem">${review.item}</c:set>
<c:set var="myIncidentDate">${review.incidentDate}</c:set>
<c:set var="myId">${review.id}</c:set>
<%
String myCountVal = (String) pageContext
.getAttribute("myCount");
String myChildFault = (String) pageContext
.getAttribute("myChildFault");
String myItem = (String) pageContext.getAttribute("myItem");
String myIncidentDate = (String) pageContext
.getAttribute("myIncidentDate");
String myId = (String) pageContext.getAttribute("myId");
String rowName = "my_row_" + myCountVal;
%>
<div class="aui-ctrl-holder" id=<%=paragraphID%>>
<liferay-ui:icon-menu>
<tr id=<%=rowName%>>
<td>${review.childFault}</td>
<td>${review.item}</td>
<td>${review.incidentDate}</td>
<td><liferay-ui:icon-menu>
<%
String taglibUrl = "javascript:"
+ renderResponse.getNamespace()
+ "removeFault('" + myCountVal + "','"
+ myId + "')";
%>
<liferay-ui:icon-delete url="<%=taglibUrl.toString()%>" />
</liferay-ui:icon-menu></td>
</tr>
</liferay-ui:icon-menu>
</div>
</c:forEach>
</c:if>
you need to make another ajax get request to pull the data from before enabling/displaying 3 tab or set the data in model map(on your post call) and retrieve it on 3rd tab.
I'm currently working on an Inventory Management project. I m working with JSP and MySQL on Netbeans Platform. In my project on querying I need to retrieve values from the database and display it in a table. The rows to be displayed should be dynamic in my page. They should be displayed in any number. Suppose When I want to retrieve values based on a particular choice I select, I should be able to display all the data based on the choice and display it in the rows of the table. I am not able to display it in multiple rows of my table because I m using text boxes to display the values.
Here is the code snippet:
<table>
<tr>
<td>
<select name="choice_type">
<option>select</option>
<option value="part_type">part_type</option>
<option value="category">category</option>
<option value="names">names</option>
</select>
</td>
</tr>
<tr>
<th>VAL</th>
<th>VAL DESC</th>
</tr>
<tr>
<td> <input type="text" name="val" id="val" size="15" /></td>
<td> <input type="text" name="val_desc" id="val_desc" size="15" /></td>
</tr>
</table>
<input type="submit" name="Query" value="Query" onClick="getData();"/>
The getData() function is as follows:
function getData(){
xmlHttp=GetXmlHttpObject()
var id=document.getElementById("choice_type").value;
var url="choice_retrieval.jsp";//The code for this file is defined below
url=url+"?choice_type="+id;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null);
}
function stateChanged(){
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var showdata = xmlHttp.responseText;
var strar = showdata.split(":");
if(strar.length>1){
var strname = strar[1];
document.getElementById("val").value= strar[1];
document.getElementById("val_desc").value= strar[2];
}
}
The Code snippet for choice_retrieval.jsp is as follows:
<%
String ch = request.getParameter("choice_type").toString();
System.out.println(ch);
String data ="";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://", "", "");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from master_panel where choice_type='"+ch+"'");
while(rs.next())
{
data = ":" + rs.getString("val") + ": " + rs.getString("val_desc");
}
out.println(data);
System.out.println(data);
}
catch(Exception e) {
System.out.println(e);
}
%>
Database table used here is master_panel(choice_type varchar,val varchar,val_desc varchar). I have not put any constraints as of now. Based on the choice_type value I need to retrieve the corresponding data(val and val_desc) from the database and display it in dynamic rows.
Assuming that the data is being returned (your stateChanged method is being invoked) you need to dynamically create the table rows (and their contents, the text boxes) in your stateChanged method by modifying the DOM.
To modify the DOM to create the table structure the code should read something like this (assuming you've already removed the previously displayed rows):
var table = document.getElementById('tableId');
var data = xmlHttp.responseText.split(":");
for (int i = 0; i < data.length; i + 2)
{
var valueText = document.createElement('input');
valueText.type = 'text';
valueText.name = 'value' + i;
valueText.value = data[i];
var valueCell = document.createElement('td');
valueCell.appendChild(valueText);
var descriptionText = document.createElement('input');
descriptionText.type = 'text';
descriptionText.name = 'value' + i;
descriptionText.value = data[i + 1];
var descriptionCell = document.createElement('td');
descriptionCell.appendChild(descriptionText);
var tableRow = document.createElement('tr');
tableRow.appendChild(valueCell);
tableRow.appendChild(descriptionCell);
table.tBodies[0].appendChild(tableRow);
}
Also, as #TrueDub said, putting SQL in JSPs is bad for a whole host of reasons. What's worse is building SQL queries with string concatenation - it opens your system to SQL injection attacks, especially when the string being concatenated includes a string captured in the browser.
You're doing quite a few things wrong there, especially having database code within a JSP, but to answer your specific question, you should write your resultset into a list and set this list into the request scope with a specific id. You can then iterate over it using the JSTL tag and display the output using the {} notation.
I have a database driven textbox that needs to be repopulated when the user hits the back button (a back button that I have created on the form)
Currently, I am able to repopulate non database driven fields on the form using http sessions just fine. I cannot seem to apply to same logic to database driven fields.
The code on my jsp looks as follows:
<td><select name = "actionType" tabindex = "1" value="<%if(session.getAttribute("actionType")== null) out.print(""); else out.print(session.getAttribute("actionType"));%>">
<option>--</option>
<% for(int i=0; i<actTypeDDL.size()-1; i++){
String actType = actTypeDDL.get(i).toString();
i++;
String actTypeVal = actTypeDDL.get(i).toString();%>
<option value=<%=actTypeVal%>>
<%=actType%>
</option>
<%
} %>
</select></td>
Any ideas?
The issue doesn't have anything to do with the fact that the value comes from the database, the problem is that specifying a value on a select tag won't preselect the option. You need to add a "selected" flag to the option itself.
The following should work:
<td><select name = "actionType" tabindex = "1" >
<option>--</option>
<% for(int i=0; i<actTypeDDL.size()-1; i++){
String actType = actTypeDDL.get(i).toString();
i++;
String actTypeVal = actTypeDDL.get(i).toString();%>
<option value=<%=actTypeVal%>
<% if (session.getAttribute("actionType") == actTypeVal) {
System.out.println("selected = 'true'");
} %>
>
<%=actType%>
</option>
<%
} %>
</select></td>