I have a page for writing Book Review. On that page, I have a dynamic dropdown where the values for Title and Author of a book are coming from the database. I need to make sure if user selects Java as book title, the author should be selected as Kathy sierra. How to ensure that?
The code is follows:
This is on bookreview.jsp
<select name="jumpMenu_group" size="1" id="jumpMenu_group">
<option value=""></option>
<% for(int i=0; i<beanList.size(); i++)
{
%>
<option value="<%=beanList.get(i).getTitle()
%>"><%=beanList.get(i).getTitle() %></option>
<%} %>
</select>
<select name="jumpMenu_group2" size="1" id="jumpMenu_group">
<option value=""></option>
<% for(int i=0; i<beanList.size(); i++)
{
%>
<option value="<%=beanList.get(i).getAuthor()
%>"><%=beanList.get(i).getAuthor() %></option>
<%} %>
</select>
You'll need to use JavaScript to get the selected value and set the appropriate value in the second drop-down. You also have repeating ID's (on the select
elements) -- ID's must be unique
Give your second dropdown a different ID (for this example, I'm just using jumpMenu_group2)
document.getElementById("jumpMenu_group").onchange = function() {
var selected = this.value; //currently selected value;
var author = document.getElementById("jumpMenu_group2"); //second select element;
//Do value comparison here
if (selected == "Java")
author.value = "Kathy Sierra"; //these values must exist in the dropdown, if they dont, add them dynamically
}
So change your jsp code to next
<select name="jumpMenu_group" size="1" id="jumpMenu_group">
<option value=""></option>
<% for(int i=0; i<beanList.size(); i++)
{
%>
<option data-author="<%=beanList.get(i).getAuthor()" value="<%=beanList.get(i).getTitle()
%>"><%=beanList.get(i).getTitle() %></option>
<%} %>
</select>
<select name="jumpMenu_group2" size="1" id="jumpMenu_group2">
<option value=""></option>
<% for(int i=0; i<beanList.size(); i++)
{
%>
<option value="<%=beanList.get(i).getAuthor()
%>"><%=beanList.get(i).getAuthor() %></option>
<%} %>
</select>
I used data-attribute in option(data-author) to know author and title from first select
Add javascript to your page (my code depends on jQuery library)
$("#jumpMenu_group").on("change", function(){
var val = $(this).attr("data-author");
// now we know author
$("#jumpMenu_group2").val(val);
});
Also my advice for you:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.