Add an alternative selection feature to Ajax cascading drop-downs with JSP and Javascript

I have successfully created a dynamic drop-down menu on my registration page by fetching countries from the database and then retrieving corresponding states based on the selected country.

Everything is functioning well, but I am facing a challenge in including an "OTHER" option at the end of the select dropdown.

Below is the code snippet responsible for displaying countries in Countries_States.jsp :

<tr>
                <td>Country : </td>
                <td>
                    <%

                        try {
                            MylistDAO dao = new MylistDAO();
                            ResultSet rs = dao.getCountries();
                            String ss;
                    %> <select id="combos" name="combos"
                    onChange="showcity(this.value);" onfocus="return(validCountry(this));">
                        <%
                            while (rs.next()) {
                                    ss = rs.getString(2);
                        %>
                        <option value="<%=ss%>"><%=ss%></option>
                        <%
                            }
                        %>
                </select> <%
    } catch (Exception e) {
    }
 %>
                </td>
            </tr>

Below is the AJAX code snippet for fetching and displaying states based on selected countries:

function showcity(str) {

    document.getElementById("states").length = 0;

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.open("GET", "getCity.jsp?q=" + str, true);
    xmlhttp.onreadystatechange = function() {

        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

            var xml = xmlhttp.responseXML;

            var tags = xml.getElementsByTagName("tr");
            for ( var i = 0; i < tags.length; i++) {
                var combo = document.getElementById("states");
                var option = document.createElement("option");
                option.text = tags[i].childNodes[0].childNodes[0].nodeValue;
                option.value = tags[i].childNodes[0].childNodes[0].nodeValue;
                try {
                    combo.add(option, null); //Standard 
                } catch (error) {
                    combo.add(option); // IE only 
                }

            }

    };
    xmlhttp.send();

}

Additionally, here is the getCity.jsp code to retrieve a list of states based on the selected country:

 <% 
    String names = request.getParameter("q");
    out.print(names);
    try {
        MylistDAO dao =new MylistDAO();
        ResultSet rs = dao.getState(names);
        String xml = "<table>";
        while (rs.next()) {
            xml += "<tr>";
            xml += "<td>";
            xml += rs.getString(1);
            xml += "</td>";
            xml += "</tr>";
        }
        xml += "</table>";
        out.print(xml);
        PrintWriter pw = response.getWriter();
        response.setContentType("text/xml");
        pw.write(xml);
        pw.flush();
        pw.close();
    } catch (Exception e) {
    }
%>

Lastly, here is a snippet of the DAO.java class responsible for fetching data from the database to populate the dropdown lists:

 public class MylistDAO {
    // Code to fetch country and state data from the database
}

To add an "OTHER" option in both the countries and states dropdown menus, you can modify the getCity.jsp as follows:

  <% 
    String names = request.getParameter("q");
    out.print(names);
    try {
        MylistDAO dao =new MylistDAO();
        ResultSet rs = dao.getState(names);
        String xml = "<table>";
        while (rs.next()) {
            xml += "<tr>";
            xml += "<td>";
            xml += rs.getString(1);
            xml += "</td>";
            xml += "</tr>";
        }
        xml += "<tr>";
        xml += "<td>";
        xml += "Other";
        xml += "</td>";
        xml += "</tr>";
        xml += "</table>";
        out.print(xml);
        PrintWriter pw = response.getWriter();
        response.setContentType("text/xml");
        pw.write(xml);
        pw.flush();
        pw.close();
    } catch (Exception e) {
    }
%>

If you encounter any issues with this implementation, feel free to ask for further assistance. Remember, I am here to help! Good luck with your project!

Answer №1

To achieve this functionality without the need for any additional plugins,

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var mySelect = $('#mySelect');
$.each(myOptions, function(val, text) {
    mySelect.append(
        $('<option></option>').val(val).html(text)
    );
});

If you have a large number of options or if this code needs to be executed frequently, consider using a DocumentFragment instead of repeatedly modifying the DOM unnecessarily. However, for only a few options, it may not be worth the effort.

DocumentFragment can improve performance, but creating option elements with document.createElement('option') is not supported in IE6 and IE7.

An alternative approach is to create a new select element, append all options to it, and then append it to the actual DOM object once the loop is complete.

var myOptions = {
    val1 : 'text1',
    val2 : 'text2'
};
var _select = $('<select>');
$.each(myOptions, function(val, text) {
    _select.append(
            $('<option></option>').val(val).html(text)
        );
});
$('#mySelect').append(_select.html());

This way, the DOM will only be modified once!

You may find this cheat sheet (PDF) on using jQuery with selects helpful for more information.

Using Javascript

<html>
<body>
<script language="JavaScript">
    function function1() {
        var newOption = document.createElement('<option value="TOYOTA">');
        document.all.mySelect.options.add(newOption);
        newOption.innerText = "Toyota";
    }
    function function2() {
        document.all.mySelect.options.remove(0);
    }
</script>
<select id="mySelect">
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>
<input type="button" value="Add" onclick="function1();">
<input type="button" value="Remove" onclick="function2();">
</body>
</html>

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

The 'npm start' command is failing to recognize the changes made to the

I am embarking on a new node application journey, starting with the package.json below, which is quite basic. { "name": "mynewnodeventure", "version": "1.0.1", "description": "Exploring node", "main": "index.js", "start": "node server. ...

Forward user to a subdomain once they have successfully logged in on an Angular 2 application

I've been working on an Angular 2 application and I'm looking to redirect users from www.example.com to admin.example.com after they successfully log in. What is the best way to accomplish this using Angular 2? Additionally, how can I test this f ...

Error occurs when the asynchronous function is invoked and completes, or when the callback is not a valid function when called on the

Attempting to create a function that calls other functions: copy = () => { copyHtml(); copyCss(); copyJs(); copyImg(); } exports.copy = copy; When using gulp copy, the function runs but an error is encountered: The following tasks did ...

Retrieving all rows from a table using Laravel API and Vue.js

<template> <div class="container"> <div class="row mt-5 mb-3"> <div class="col-md-10"> <h3>Gallery</h3> </div> <div class="col-md-2"> <button class="btn btn-success" ...

disable td's from moving when hovered over

When you add a book, you will see the item added to the table with a cool font and an X icon for removal. However, I noticed that when hovering over the icon to increase its size, it slightly shifts the text in the other cells. Is there a way to prevent th ...

Is the "Illegal invocation" error popping up when using the POST method in AJAX?

Is there a way to retrieve JSON data using the POST method in Ajax? I attempted to use the code below but encountered an error: TypeError: Illegal invocation By following the link above, I was able to access JSON-formatted data. However, please note th ...

The autocomplete feature is malfunctioning when trying to input data into dynamic table rows

Recently, I designed a dynamic input table with auto-complete functionality. Everything was working well until I encountered an issue - the auto-complete function doesn't work on newly added rows in my dynamic table. Any suggestions for resolving this ...

How can we create a reusable dropdown list that appears when clicking on different elements?

Imagine having different sections of a webpage that, when clicked, reveal a dropdown list right below the selected link. I've noticed some websites accomplish this by actually having just one dropdown list defined in the DOM, which then appears below ...

Spin an Alpha with Adjustments (THREE.JS R76)

Creating a unique wormhole effect using a cylinder and rotating texture is my current project. To see an example, visit: The texture rotation is achieved with the following code... tunnel.material.map.offset.y += 0.01; tunnel.material.map.offset.x += ...

Mastering the ng-if directive in Angular can help you easily display or hide content based on boolean

Having trouble figuring out what to insert in the last span element where it mentions "I_DO_NOT_KNOW", here is the markup provided: <div class="row"> <div class="key" translate>Label</div> <div class="value form-group"> < ...

Execute JavaScript script whenever the state changes

I have a large table with multiple HTML elements such as dropdowns, textboxes, radio buttons, and checkboxes. Additionally, I have a function that I want to execute whenever any of these items change. Whether it's a selection from a dropdown, typing i ...

Repeatedly encountering identical values in delayed for loop

I can't figure out why my delayed for loop is consistently giving me a "-1" as the result. for (var i = 5; i > 0; i--) { setTimeout(function() { console.log(i) }, i * 1000) } (I adjusted my variable to be 5) ...

The ngBindHtml feature in AngularJS 1.2 does not handle processing of line breaks (/r & /n)

I have a string with a lot of extra whitespace, as it appears on my server: var care_description = "MATERIAL\r\n \r\n 56% Acrylic, 24% Rayon, 20% Polyester\r\n \r\n CARE\r\n \r\n Machine ...

The JSONP request connected to the user input field and button will only trigger a single time

Hello all, I'm new to this and have been searching the internet high and low to see if anyone has encountered a similar issue before, but haven't had any luck. I've been attempting to set up a JSONP request to Wikipedia that is connected to ...

How can you efficiently extract data from a variety of cells spanning across multiple rows in Protractor?

Need help with accessing and verifying data from specific cells in a table. The table consists of 10 rows and each row has 13 cells. I want to extract values and perform assertions only on cells 1, 2, 3, and 5. Below is the snippet of code I am using: l ...

Manipulating a DOM element in Angular 2 to alter its class attribute

I am a beginner in angular2. Here is my code: import { Component, OnInit } from '@angular/core'; @Component({ selector: 'main', template: ` <div class="current"> </div> ` }) export class MainComponent impl ...

Issue with CKEditor5 Link popup not displaying in both Bootstrap 5 modal and RSuite library modal in React

React: How to troubleshoot CKEditor5 Link popup not appearing in a modal using either Bootstrap 5 or rsuite library? Seeking advice on resolving this issue. Your help is appreciated! ...

How can I utilize a variable in a v-for loop as a label for a q-btn in Vue.js?

I have a list: myList = [1, 2, 3, 4, 5, 6, 7, 8, 9] I'd like to generate buttons using this list where the label corresponds to the number: <q-btn v-for="number in myList" v-bind:key="number" color="primary" label=&q ...

How can you refresh a functional component using a class method when the props are updated?

I've created a validator class for <input> elements with private variables error, showMessage, and methods validate and isOk. The goal is to be able to call the isOk function from anywhere. To achieve this, I designed a custom functional compone ...

How can I substitute a specific capture group instead of the entire match using a regular expression?

I'm struggling with the following code snippet: let x = "the *quick* brown fox"; let y = x.replace(/[^\\](\*)(.*)(\*)/g, "<strong>$2</strong>"); console.log(y); This piece of code replaces *quick* with <strong& ...