Fill second dropdown on the selection of first dropdown - java

I'm trying to fill the dropdown on run time from the database, whenever user selects the city from the dropdown, then in the next dropdown, it will fill the respective values from the database. How can I achieve this thing in JSP?
Here is what I have done so far:
<div class="label">City : </div>
<div class="control">
<select name="city" id="city">
<%
try {
ResultSet rs = state.executeQuery("SELECT CITY_ID,CITY_NAME FROM CITY ORDER BY CITY_NAME");
while (rs.next()) {
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(2) + " (" + rs.getString(1) + ")"%></option>
<%
}
} catch (Exception ex) {
%>
<option value="ERROR">CITY NOT AVAILABLE</option>
<% }
%>
</select>
</div>
<div style="clear:both;height:0px;"></div>
<div class="label">Report To : </div>
<div class="control">
<select name="report_to" id="report_to">
<%
try {
ResultSet rs = state.executeQuery("SELECT HOUSE_ID,HOUSE_ADD FROM HOUSE WHERE CITY_ID='PNP' ORDER BY HOUSE_ID");
while (rs.next()) {
%>
<option value="<%=rs.getString(1)%>"><%=rs.getString(2) + " (" + rs.getString(1) + ")"%></option>
<%
}
} catch (Exception ex) {
%>
<option value="ERROR">HOUSE NOT AVAILABLE</option>
<% }
%>
</select>
</div>
<div style="clear:both;height:0px;"></div>

First step would be to add onchange="submit()" to the first dropdown, so that the form will be "automatically" submitted by JavaScript. You can then just fill the second dropdown based on the submitted value of the first dropdown which you retrieve as request parameter the usual way.
You might only want to get rid of scriptlets and add a servlet so that your JSP is a bit more maintainable.
See also:
Populating cascading dropdown lists in JSP/Servlet (shows 3 different ways along with concrete examples)

For this to work either the users first selection (City) must be sent to the server which could then look up the selections available for that city and then re-render the page. Or, you could look up all Houses for all cities and then have a javascript that switched the content of the Houses selection box based on what selection is made in the first one.
As a side note, unless you are doing a very simplistic page (and you do not expect it will need to be maintained) it is bad design to mix your db access logic with your view generation logic...

Related

Java servlet sending select value

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.

Disable dropdown list without any event

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

How to get the selected values on the server side when using Bootstrap multiselect?

When I submit my form, I can see form data being submitted like such:
genre[]:action
genre[]:thriller
genre[]:romance
On the server side when I retrieve genre[] from request, I only get one value.
I did everything they said in this page, but it is not working
Here is my code:
<select class="select " name="genre[]" id="genre" multiple="multiple" >
<% for(Param param:selectGenres) {%>
<option value="<%=param.getValue() %>"
<%=param.getValue().equalsIgnoreCase(genre)?"selected":"" %> ><%=param.getTitle() %></option>
<%} %>
</select>
$(document).ready(function() {
$('#genre').multiselect({
maxHeight: 300,
buttonWidth: '99%',
checkboxName:"genre[]"
});
});
server side:
request.getParameter("genre[]")
To handle array of parameters, you need to use javax.servlet.ServletRequest#getParameterValues.
So your code a the server side might be:
final String[] genres = request.getParameterValues("genre[]");

how to break columns in a table using jdbc

I am making a simple table which stores product details from database using jdbc connection.
My table looks like this:
<table>
<td>
<img border="3"
src="image path" height="200" width="200" />
<p align="center"></p> // these tag contains specific product details from db
<p align="center"></p>
</td>
</table>
right now I'm getting each product details in particular column( i.e multiple column within single row), but my problem is that this row keeps on expanding , & I want this row(which consist of multiple columns) to automatically break let say after every 5 products.
In simple words i want to arrange my products details in 4 x n format just like in flipkart , as shown below:
http://www.flipkart.com/mobiles/android-phones~type/pr?sid=tyy,4io&otracker=hp_nmenu_sub_electronics_0_Android%20phones
you can see first product sony experia then lg then after samsung galaxy product, new row starts then again 4 products , then new row. In this way i need to show my products which are coming from database using jdbc connection.
Can anyone suggest me what's the best possible approach to achieve this. & Is there any option to break columns after 4th one & then start new row?
I am displaying database contents in jsp as shown below, just for demo:
<%
//1. Retrieve all products from database
//1a. Load the Driver
Class.forName("com.mysql.jdbc.Driver");
//1b. Get a connection to the database
Connection con = DriverManager.getConnection("url", "un", "pwd
PreparedStatement ps = con.prepareStatement("SELECT * FROM table");
//1d. Execute and retrieve our result
ResultSet rs = ps.executeQuery();
//2. Base on the results returned, construct a table
%>
</p>
<table border="0">
<%
if(rs.next()) {
rs.beforeFirst(); // for making sure you dont miss the first record.
while(rs.next())
{ // opening while loop brackets.
%>
<td>
<div style=""><img border="3"
src="<%=rs.getString("image") %>" height="200" width="200" /></div>
<p align="center"><%=rs.getString("title")%></p>
<p align="center"><%=rs.getString("price")%></p>
</td>
<%
} //closing while loop bracket
}
else {
//if no record is found, simply display a no record message
%>
Nothing.
<%
}
%>
</table>
Use <tr> tags to organize the table in rows. (That's what it stands for - *t*able *r*ow.)
Keep track of how many products (N) you've read from the database. If N is a multiple of 4 (n % 4 == 0), close the <tr> and start a new one.
So the result looks like:
<table>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
<tr>
<td>...</td>
<td>...</td>
<td>...</td>
<td>...</td>
</tr>
</table>
UPDATE based on updated question:
Here's my tweak based on your code. I really do not advocate doing SQL calls (or really any non-presentation-layer code) from within a JSP, but that's a matter for a different question.
<%
//1. Retrieve all products from database
//1a. Load the Driver
Class.forName("com.mysql.jdbc.Driver");
//1b. Get a connection to the database
Connection con = DriverManager.getConnection("url", "un", "pwd
PreparedStatement ps = con.prepareStatement("SELECT * FROM table");
//1d. Execute and retrieve our result
ResultSet rs = ps.executeQuery();
//2. Base on the results returned, construct a table
%>
</p>
<table border="0">
<tr>
<%
int i = 0;
if(rs.next()) {
rs.beforeFirst(); // for making sure you dont miss the first record.
while(rs.next())
{ // opening while loop brackets.
%>
<td>
<div style=""><img border="3"
src="<%=rs.getString("image") %>" height="200" width="200" /></div>
<p align="center"><%=rs.getString("title")%></p>
<p align="center"><%=rs.getString("price")%></p>
</td>
<%
i++;
if ((i % 4) == 0) {
%>
</tr>
<%
}
if (!rs.isLast()) { // don't open a new row if this is the last result
%>
<tr>
<%
} // closing isLast check
%>
<%
} //closing while loop bracket
}
else {
//if no record is found, simply display a no record message
%>
Nothing.
<%
}
%>
</tr>
</table>
I don't really have the patience to correct the whitespacing here, and I haven't actually compiled this, but hopefully you get the gist.
Apart from the response from dcsohl, you can use a combination of <div> and <span> elements. A <div> element is a block element, that is, each <div> will be rendered in new line. <span> element is an inline element.
This should help you:
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>
<div>
<span></span>
<span></span>
<span></span>
<span></span>
<span></span>
</div>

How to print dropdown values of a select tag using javascript?

I'm having a dropdown for selecting cities of Tamil Nadu.
All the cities are in an array list and using a for loop, I am iterating the values and writing using document.write but still I'm not getting the values printed in dropdown.
<select>
<script>
document.writeln('&ltoption value="chennai">');
</script>
</select>
How to get the dropdown values printed now?
Thanks in advance!
Assuming you are using jquery :
Assuming your HTML is similar to this
<SELECT NAME="mylist">
<option>Volvo</option>
<option>Saab</option>
<option>Mercedes</option>
<option>Audi</option>
</SELECT>
you need to modify your selector to iterate over the <OPTION> tags, your selector was iterating over the <SELECT> tag
var inputName = mylist;
$(':input[name=' + inputName + '] option').each(function(i, selected) {
alert($(selected).text());
});
if you need in java script :
<form>
<select id="myselect">
<option value="cat">Option 1</option>
<option value="dog">Option 2</option>
<option value="bear">Option 3</option>
</select>
</form>
<script type="text/javascript">
var selectobject=document.getElementById("myselect")
for (var i=0; i<selectobject.length; i++){
alert(selectobject.options[i].text+" "+selectobject.options[i].value)
}
</script>
Your option tag should look like this:
<option value="chennai">Chennai</option>
The code snippet you posted would produce an invalid (unclosed) option tag.
<select>
<script >
var list = [1,2,3];
for(i in list){
document.write("<option>"+list[i]+"</option>");
}
</script>
<select>
var list = ${cities}
I will give you a demo.
<?php
$city=array('Chennai','Madurai','Dindigal');//array containing cities
$count=1;
echo "<select>";
foreach($city as $value)
{
echo "<option value='city.$count'>".$value."</option>";
}
?>
Hope you understands.You can also use the id of each for other purposes in jsp
It's years since I've written anything in JSP and your question is lacking a bit in clarity but I think you're after something like this?
<%
String[] cityArray={"Chennai","Madurai","Dindigal"};
%>
That's just a an array of cities as an example - I assume you have your own
Then, in your page code
<select>
<%
int i=0;
for(i=0;i<cityArray.length;i++)
{
out.print("<option>" + cityArray[i] + "</option>");
}
%>
</select>
I've got nothing to test that with and the memory is a bit dim on jsp but is that what you mean?

Categories

Resources