1

I need your help with this one :)

The main idea is pretty simple, I have a first dropdown, and I want to filter the values in the second dropdown depending on the first one.

I can't modify the datamodel.

My two sets of value are sent trough a request dispatcher :

[...]
    List<ConfigSousType> listConfigSousType =  new ArrayList();
    List<ConfigType> listConfigType =  new ArrayList();
[...]
    String querySousType = "SELECT distinct colonne, idValeur FROM ThanactConfigType";
    String queryType = "SELECT * FROM ThanactConfigType";
[...]
    request.setAttribute("listConfigSousType",listConfigSousType);
    request.setAttribute("listConfigType",listConfigType);
        
    String nextJSP = "/addConfigSousType.jsp";
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP)
[...]

The data model is this one :

First table Type: name, idType, value

Second table SubType : name, idType, subTypeName, idSubType

Example:

Type table
ColorCategory, 1, TheBlueColors
ColorCategory, 2, TheRedColors
FoodCategory, 1, TheTastyFood

SubType Table
ColorCategory, 1, DeepBlue, 1
ColorCategory, 1, LightBlue, 2
ColorCategory, 2, Crimson, 1
ColorCategory, 2, Scarlet, 2
FoodCategory, 1, Pizza

I'm creating the admin part allowing to add a new line in the subType Table.

I want a first dropdown with 'ColorCategory', 'FoodCategory'
Then my second dropdown on, the idType should be filtered depending on the first one.
I select "ColorCategory" on the first dropdown, the second one allow the values "TheBlueColors", "TheRedColors"

On my example

  • listConfigType contains the whole table (they will be small tables, <100 lines)
  • listConfigSousType contains "ColorCategory , 1", "ColorCategory , 2", "FoodCategory, 1"

In my JSP I get them like that:

<select id ='name' required name='name'><br><br>
                    <c:forEach items="${listConfigSousType}" var="configSousType">
                        <option value="${configSousType.name}">${configSousType.name}</option>
                    </c:forEach>    
        </select>                       

=> Two issues:

  • For the first dropdown, I will get ColorCategory twice, I need a distinct someway
  • How should I populate the second dropdown ?
    I select ColorCategory on the first dropdown, the second should offer, "TheBlueColors", "TheRedColors"

I think I may need a javascript part with the onChange function but I don't know what should be inside.

To diplay the value of the idType on my display list I use:

    <label for='value'>Valeur </label>              
    <input id ='value' type='text' name='value' 
    <c:forEach items="${listConfigType}" var="configType">
        <c:if test="${configType.name == configSousType.name && configType.idType == configSousType.idType}">
            value="${configType.value}"><br><br>
        </c:if>
    </c:forEach>        

Thank you if you read this whole post, I hope you'll be able to help me :)

Pandalex
  • 23
  • 7

1 Answers1

-1

I found a way to solve this here on stackoverflow using Gson

I used the answer from this post: How to use Servlets and Ajax?

I use this java :

import com.google.gson.Gson;

public class optionsSousType extends HttpServlet{ 
 

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
         Map<String, String> options = new LinkedHashMap<>();
        options.put("value1", "label1");
        options.put("value2", "label2");
        options.put("value3", "label3");
        String json = new Gson().toJson(options);

        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(json);
    }
}

And this JSP :

<%@ page language="java" import="java.util.*"%>
<%@ page contentType="text/html;  charset=ISO-8859-1"  pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>  
    <link rel='stylesheet' type='text/css' href='../Formulaire.css'>
    <meta name='viewport' content='width=device-width,initial-scale=1,user-scalable=no'>
    <title>Thanact - Gestion de l'activité Thanatologique</title>

    
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script>
    $(document).on("click", "#somebutton", function() {               // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
        $.get("optionsSousType", function(responseJson) {                 // Execute Ajax GET request on URL of "someservlet" and execute the following function with Ajax response JSON...
            var $select = $("#libelle");                           // Locate HTML DOM element with ID "someselect".
            $select.find("option").remove();                          // Find all child elements with tag name "option" and remove them (just to prevent duplicate options when button is pressed again).
            $.each(responseJson, function(key, value) {               // Iterate over the JSON object.
                $("<option>").val(key).text(value).appendTo($select); // Create HTML <option> element, set its value with currently iterated key and its text content with currently iterated item and finally append it to the <select>.
            });
        });
    });
    </script>   
</head>

<body>

    <br/>
    <div id='exForm'>
        <form name="configform" method="post" action="../addConfigType">        
            <fieldset><legend>Ajout d'une configuration de sous colonne</legend>            
                <label for='colonne'>Type de colonne</label>
                <select id ='colonne' required name='colonne'><br><br>
                    <c:forEach items="${listConfigType}" var="configType">
                        <option value="${configType.colonne}">${configType.colonne}</option>
                    </c:forEach>    
                </select>       
                
                <label for='libelle'>Type de sous colonne</label>
                <select id ='libelle' required name='libelle'> <option>Please select parent</option> </select><br><br>
                            
                <button id="somebutton">press here</button>
                
                <label for='libValeur'>Valeur</label><input id ='libValeur' type='text' required name='libValeur'><br><br>              
                <input type='submit' class="buttonBlue" value="Ajouter" name="Submit">
            </fieldset>         
        </form>
    </div>
</body>
</html>

When I click on the button, I got an error : Uncaught TypeError: Cannot use 'in' operator to search for '3282' in Because I needed to specify it was a JSon:

$.getJSON("optionsSousType"

Then my next issue was that nothing happened. It was the path of my servlet :

So my final fix was : $.getJSON("${pageContext.request.contextPath}/optionsSousType", function(responseJson) {

I hope someone will find this helpful !

Pandalex
  • 23
  • 7