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.
Related
I have a small problem, I just need to redirect to the value of select like:
/results/name/Heli Redel
How would I go about doing that?
<div class="search">
<select th:required="true">
<option th:value="'Eha Raudreha'" th:text="'Eha Raudreha'"></option>
<option th:value="'Heli Redel'" th:text="'Heli Redel'"></option>
<option th:value="'Mait Kuusevaik'" th:text="'Mait Kuusevaik'"></option>
</select>
<a class="buttons" th:href="#{|/results/name/NAME_HERE|}"><button class="deleteBtn">Otsi</button></a><br />
</div>
Add a jQuery function, that when the button is clicked, it redirects to a another url.
jQuery(document).ready(function() {
$('.deleteBtn').on('click', function() {
var selectValue = $('.search').find('select').val()
window.location.replace("/result/name/" + selectValue);
})
})
I would add some ids to your elements to make it easier to fetch data.
I have an HTML page named Order that includes a drop-down:
<select name="Pizzas">
<option value="15.80" name="Napoletana">Napoletana</option>
<option value="16.95" name="Margherita">Margherita</option>
<option value="17.50" name="Sardiniana">Sardiniana</option>
<option value="16.85" name="Pollo Dolce">Pollo Dolce</option>
<option value="14.95" name="Funghi">Funghi</option>
<option value="15.60" name="Patate Con Aglio">Patate Con Aglio</option>
<option value="15.60" name="Romana">Romana</option>
<option value="17.85" name="Gamberetti">Gamberetti</option>
<option value="18.75" name="Capri">Capri</option>
<option value="14.30" name="La Mexicana">La Mexicana</option>
<option value="15.60" name="Pomodori Secchi">Pomodori Secchi</option>
<option value="17.70" name="Proscuitto Con Pomodori">Proscuitto Con Pomodori</option>
<option value="19.90" name="Siciliana">Siciliana</option>
<option value="16.70" name="Palermo">Palermo</option>
<option value="19.05" name="Pesto">Pesto</option>
</select>
I want to get the name and value of the option so I can pass it to a Servlet. So far I figured out how to pass the value, which is:
String[] pizzas = request.getParameterValues("Pizzas");
And then to display it:
out.println("<strong>Pizza: </strong>");
if (pizzas != null) {
for (String pizza: pizzas) {
out.println("<br/>Price: " + pizza);
}
}
So how would I be able to pass the names also? I'm trying to create a receipt so that I can have: Pizza: "name" and Price: "price"!
Only the option value is passed to the server. But with creative use of the option’s value, you can pass multiple pieces of data as the value.
<option value="15.80;Napoletana">Napoletana</option>
In your server code, split the value at your item separator …
String f[] = pizza.split(";");
System.out.println(f[1] + " costs " + f[0]);
I should point out: storing critical information client side is opening yourself to attacks. A malicious user can craft their own request string, such that they order the "0.80;Napoletana" pizza, and save $15.
It is better to use unique ids client side, and look up critical information server side.
When you post a form, it sends selected option's value with select element's name not the option element's name attribute.
So you could get Pizzas=selected options value. For example Pizzas : 15.60
You can try to send custom json instead.
var formData = {};
formData.pizzaName = $('#Pizzas').find(":selected").attr("name");
formData.pizzaValue = $('#Pizzas').find(":selected").val();
// You may add more data from your form here
$.ajax({
type: 'POST',
url: 'Test',
data: JSON.stringify(formData),
success: function(data) { console.log("Success"); },
contentType: "application/json",
dataType: 'json'
});
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('<option 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?
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>
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...