0

I have created a cascading drop down menu for my registration page where I am fetching the counries from the database and base don the countries the states would be retrieved.

Everything is working good but I am not understanding how to include the OTHER option in the drop down select option in the last of the drop down select.

The following is the code I have written 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>

The following is the code for retrieving list of states based on countries in AJAX :-

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();

}

ALso the following is the getCity.jsp page to retrieve the list of states based on country :

 <% 
    String names = request.getParameter("q");
    out.print(names);
    try {
        MylistDAO dao =new MylistDAO();
        //GetCity c = new GetCity();
        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);
        //con.close();
        PrintWriter pw = response.getWriter();
        response.setContentType("text/xml");
        pw.write(xml);
        pw.flush();
        pw.close();
    } catch (Exception e) {
    }
%>

The following is my DAO.java class to fetch the data from database to populate the drop downs :

 public class MylistDAO {
    public Connection con;
    public Statement st;

    public Statement  get_connection()
    {
        try{
            con=DaoConnections.connection();
            st=con.createStatement();
        }catch(Exception e){
            e.getMessage();
        }finally{
            try{if(con==null){
                con.close();
            }
            }catch(Exception ex){
                ex.getMessage();
            }
        }
        return st;
    }
    public ResultSet getCountries()
    {   
        ResultSet rs = null;
        Statement st=null;
        try{
            MylistDAO dao= new MylistDAO();
            st=dao.get_connection();
            rs= st.executeQuery("select * from countries");

        }catch (Exception e){}
        return (rs);
    }

    public ResultSet getState(String countryname)
    {   
        ResultSet rs = null;
        Statement st=null;
        try{
            MylistDAO dao= new MylistDAO();
            st=dao.get_connection();
            rs= st.executeQuery("select s.stateName as statename from states s,countries c where s.countryID=c.countryId and c.countryName= '"+ countryname+"'" );

        }catch (Exception e){
            e.getMessage();
        }
        return (rs);
    }
}

I want to just add an option of OTHER in both the countries and states dropdown based on which an OTHER text box should display and I could enter the other state value in that. I tried the following in getCity.jsp :

  <% 
    String names = request.getParameter("q");
    out.print(names);
    try {
        MylistDAO dao =new MylistDAO();
        //GetCity c = new GetCity();
        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);
        //con.close();
        PrintWriter pw = response.getWriter();
        response.setContentType("text/xml");
        pw.write(xml);
        pw.flush();
        pw.close();
    } catch (Exception e) {
    }
%>

but it did not work. Please help me in adding the OTHER option in the select and I am a fresher so please help me giving sample code and only provide me cod ein JavaScript JSP or Servlets.

1 Answer 1

0

Without using any extra 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 had lots of options, or this code needed to be run very frequently, then you should look into using a DocumentFragment instead of modifying the DOM many times unnecessarily. For only a handful of options, I'd say it's not worth it though.

DocumentFragment is good option for speed enhancement, but we cannot create option element using document.createElement('option') since IE6 and IE7 are not supporting it.

What we can do is, create a new select element and then append all options. Once loop is finished, append it to actual DOM object.

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 we'll modify DOM for only one time!

you might be interested in this cheat sheet (PDF) on using jQuery with selects for more info.

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>
2
  • Thanks for ur response but I dnt wanna use jquery in my application and because dis is jst a small level project dere r no constraint of application performance and all. Jul 23, 2014 at 14:16
  • yeah but u mentioned only for static dro down.. what if I am populatibg the second drop down from database. Jul 24, 2014 at 16:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.