"Dynamically populate dropdown options based on the selection made in another dropdown menu

On a JSP page, I have two dropdown fields and a type4 connection with Oracle 10g. I want the second dropdown to be automatically filled based on the selection from the first dropdown by fetching data from the database. This should happen without refreshing the JSP page, maybe showing an alert like "please wait". How can I achieve this using JSP-Servlet?

<select name="dropdown1">
    <option value="<%out.println(name);%>"><%out.println(name);%></option>
</select>

My goal is: Fill the following dropdown based on the selection above:

<select name="dropdown2">
    <option value="<%out.println(rollno);%>"><%out.println(rollno);%%gt;</option>
</select>

I found one potential solution :

<body onload="setModels()">
<% // Getting map in a different way.
Map<String,List<String>> map = new TreeMap<String,List<String>>();
Connection con=null;
String vehtypeout="";
...
(out of scope for rewrite)

catch(Exception e){
out.println(e);
}
%>
...

function setSelectOptionsForModels(modelArray) {
// JavaScript implementation here
}

function setModels() {
 // JavaScript implementation here
}

function modelSelected() {
 // JavaScript implementation here
}
</script>
<form name="myForm">
<select onchange="setModels()" id="manufacturer">
  <% boolean first = true;
     for (String mf : map.keySet()) { %>
      <option value="<%= mf %>" <%=first ? "SELECTED" : ""%>><%= mf %></option>
  <% first = false;} %>
</select>

<select onChange="modelSelected()" id="models">
<!-- Filled dynamically by setModels -->
</select>


However, I am only able to retrieve one value in vehtypeout1 while the database contains multiple values. How can I fetch all those values?

Answer №1

Utilize jQuery to attach a function to the onchange event of "combobox1" select box.

Within that function, make an ajax request (jQuery's get function can be used) to a JSP page on your server.

In that JSP page, retrieve the necessary information from the database and return the response to the client with said data (JSON format may be required).

When using the jQuery get function, include a callback function to run after the server sends back the response.

Inside that callback function, write the code to populate "combobox2" with the data received from the server.

Answer №2

To implement an ajax call, you can follow the example below. Create a function that will return an html string representing options.

"<option value='myVal'>myText</option>"
.

Here is how you can use jQuery/Ajax:

$("#ddl1").change(function() {
     $.ajax({
          url: "URLyouwanttoaddress",
          data: "myselection=" + $("#ddl1").val();
          type:"get",
          success: function(data) {
                     $("#ddl2").html(data);
          }
      });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Mastering the art of reading rows in ASP.NET using Java Script

Within the code snippet below, you'll find an image located in the second column. Clicking on this second column should allow me to access the data stored in the first column. Let's say we have a table with 10 rows. If the user clicks on the ico ...

Accessing WebService Remotely Using Ajax in ASP.NET

CLIENT - AJAX $.ajax({ type: "POST", url: 'http://www.website.com/Service.asmx/Method', data: "{ 'username': 'testuser', 'password': '123456' }", contentType: "applicati ...

Size of text Including line breaks

I have developed a function that calculates the maximum size of text: function CalculateMaxTextSize(width, height, text) { var ourText = $('span').css('font-weight', 'bold').text(text); ...

Ways to activate the JavaScript/AJAX script upon the dropdown value modification

I am currently working on a Django project where I want to execute a JavaScript/AJAX script when the value of a dropdown changes. Interestingly, the same code functions properly for a button but not for the dropdown. Below is the HTML code containing the ...

Difficulty organizing form inputs into arrays prior to submitting them through AJAX

I am currently developing a complex multi-step form that involves various sections such as Company, Job Site, Contact, and Product. My goal is to efficiently gather the form data either as an array or object before converting it into a string for transmiss ...

Attempting to integrate information from an external API source

I am struggling with properly formulating a question in order to retrieve relevant search results. I am attempting to extract data from a third-party API (ADP) and store it in my database using asp.net core. My goal is to save the users obtained from the ...

I'm experiencing an issue where my JavaScript function is only being triggered

I have a simple wizard sequence that I designed. Upon selecting an option from a dropdown menu on the first page, a new page is loaded using jQuery ajax. However, when clicking back to return to the original page, my modelSelect() function, responsible for ...

Having trouble with jQuery attribute selectors? Specifically, when trying to use dynamic attribute

This is the code I am working with $("a[href=$.jqURL.url()]").hide(); $.jqURL.url() fetches the current page URL. Unfortunately, this code is not functioning as expected. Is there a way to dynamically select elements? ...

What could be the reason that a basic click function fails to locate the selector?

I have created a quick JavaScript module that opens an image and fades out a container to reveal the image. The HTML markup for the image looks like this: <div style="margin-bottom:1px;" class="rsNavItem rsThumb front"> <di ...

Clicking on "li" to activate and deactivate

Currently utilizing: $('#btnEmpresarial').attr('onclick','').unbind('click'); In order to deactivate a read using javascript.. However, I now require enabling the onclick after the function has completed. Is ther ...

What is the easiest way to clear browser cache automatically?

Hello, I have implemented an ajax auto complete function in one of my forms. However, I am facing an issue where over time, the suggestions get stored and the browser's suggestion list appears instead of the ajax auto complete list, making it difficul ...

The success callback does not trigger when the status code is 201

Dealing with API Rest, I aim to create a resource using AJAX and JQuery. Although my resource is effectively created, the error callback is triggered. Here's the code snippet: $.ajax({ url: "/api/skills.json", data: JSON.stringify(skill), ...

Determine the dimensions of a div element in IE after adjusting its height to auto

I am currently working on a JavaScript function that modifies the size of certain content. In order to accomplish this, I need to obtain the height of a specific div element within my content structure. Below is an example of the HTML code I am dealing wit ...

What could be the reason why this function in jQuery is not functioning properly?

I am trying to duplicate the span element inside the `test` element using the .clone method. It seems like it works as expected. However, when I try to use .html in a `.click` function, it doesn't work. Can someone point out where I went wrong and sug ...

Can you explain the relationship between HTML 5 Canvas coordinates and browser pixels?

When trying to use HTML 5 canvas as a drawing board in my application, I encountered an issue. The drawings appear at an offset from the mouse pointer. My method involves using the Jquery .offset function to determine the event's position on the canv ...

Tips for leveraging OOP to eliminate redundant code repetition

How can I avoid repeating code when displaying multiple quizzes on the same page? Currently, I have a JavaScript function that duplicates everything for each quiz, with only a few variables changing in the second function. The problem arises when I need t ...

Is it possible to implement the Jquery blockui(plugin) code without relying on Ajax?

Hey there, I'm new to Jquery and could really use some help... I've got a page with multiple links, but when a user clicks on one link and it's still processing in the background before loading the page, they keep clicking on other links wi ...

The contents of the div disappear when using jQuery to extract it from a string

Update: I finally uncovered the reason behind the empty content of the #output div. The content is fetched from the server, which takes some time; by the time the document loads, the div remains empty. Does anyone have suggestions on how to extract infor ...

Error message: Trying to access a property of an empty object (variable 'element') is not possible

I've been attempting to execute the following code: WebElement body = driver.findElement(By.xpath("/html/body")); js.executeScript("var injector = window.angular.element(argument[0]).injector(); var $http = injector.get('$http&apos ...

enable jQuery timer to persist even after page refresh

code: <div class="readTiming"> <time>00:00:00</time><br/> </div> <input type="hidden" name="readTime" id="readTime"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script&g ...