Results 1 to 11 of 11
  1. #1
    karq is offline Member
    Join Date
    May 2010
    Posts
    63
    Rep Power
    0

    Default javascript + java

    Hey,

    is it possible to use java in javascript?

    Basically I want to make dropdown menu what depends on another drop down menu
    Example
    Java Code:
    if(dropdownmenu1selecetion.equals(example)){
       datalist = sqlmanager.getQueryList("SELECT DISTINCT name From People WHERE something='example'");
    //changes the new values in dropdownmenu2 
    }
    if someone selects IT from dropdownmenu1 then dropdownmenu2 options will be changes to those people who work there



    Hope you got what I ment?

  2. #2
    flyfisherman is offline Member
    Join Date
    Mar 2010
    Posts
    26
    Rep Power
    0

    Default

    It is called dynamic dropdowns

    Here is how I did it

    Master drop down

    XML Code:
    <select name="conf_mb" onchange="getCpuANDMemoryList(this)" id="conf_mb">
    <option value="">--- Please choose mainboard</option>
    <c:forEach var="product" items="${mb}">
    <option value="<c:out value="${product.id}"/>"><c:out value="${product.name}"/> - <c:out value="${product.price}"/> USD</option>
    </c:forEach>		
    </select>
    Slave drop down

    XML Code:
    <select name="conf_cpu" id="conf_cpu">
    </select>
    As you can see, the second one is empty... This drop down will be populated after function getCpuANDMemoryList(this) from the first one executes...

    Here is the JavaScript function which you need to include in your header part...


    PHP Code:
    function getCpuANDMemoryList(sel){
    	getCPUList(sel);
    	}
    
    
    var ajax = new Array();
    function getCPUList(sel) {
    	var category = sel.options[sel.selectedIndex].value;
    	document.getElementById('conf_cpu').options.length = 0;	// Empty city select box
    	if(category.length>0) {
    		var index = ajax.length;
    		ajax[index] = new sack();
    		
    		ajax[index].requestFile = 'scripts/returnCPU.jsp?mb='+category;	// Specifying which file to get
    		ajax[index].onCompletion = function(){ createCPUList(index) };	// Specify function that will be executed after file has been found
    		ajax[index].runAJAX();		// Execute AJAX function			
    	}
    }
    
    function createCPUList(index) {
    	var obj = document.getElementById('conf_cpu');
    	eval(ajax[index].response);	// Executing the response from Ajax as Javascript code	
    }
    Do not be confused because one function triggers the second one... I made this because the first function was made to call more than one function but I deleted them...

    As you can see the the JSP file for generating this list is scripts/returnCPU.jsp?mb='+category

    and here is it

    PHP Code:
    <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" import="data.*, business.*, java.util.*, java.lang.String"%>
    
    <%
    ArrayList<Product> cpu = null;
    ArrayList<Product> ram = null;
    
    String mbString = request.getParameter("mb");
    if (mbString == null) 
    	mbString = "0";
    int mb = Integer.parseInt(mbString);
    String mbTags = null;
    mbTags = ProductDB.returnTags(mb);
    //	System.out.println(mbTags); // debug 
    
    String temp[];
    String delim = ",";
    temp = mbTags.split(delim);
    
    String cpu_slot = temp[0];
    
    cpu = ProductDB.selectCPU(cpu_slot); // nakon odabira ploce
    
    for (int i = 0; i < cpu.size(); i++) {
    	out.println("obj.options[obj.options.length] = new Option('" + cpu.get(i).getName() + " - " + cpu.get(i).getPrice() + " KM','" + cpu.get(i).getId() + "');");
    }
    %>
    Of course, before this you need to have classes with defined objects...

    NOTICE
    Copy and paste method won't work here... As you can see JSP file is made strictly for my database and it is shown here just as a sample...
    Last edited by flyfisherman; 10-18-2010 at 08:24 PM.

  3. #3
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,036
    Rep Power
    20

    Default

    I'm guessing (I haven't walked through your code) that that's a standard Ajax set up?
    That is, the onChange simply makes an Ajax call with whatever's been selected as a parameter, which then hits the server, which returns your data?

    I would say that having a JSP page handle the request is not good practice. That should be the job of a Servlet (presuming you're in a Java environment on the server anyway). The result would then be something like a JSON string.

  4. #4
    flyfisherman is offline Member
    Join Date
    Mar 2010
    Posts
    26
    Rep Power
    0

    Default

    Sure... This it can be done through servlet...

  5. #5
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,036
    Rep Power
    20

    Default

    It's not about can...it's about should.

    JSPs are not good for doing processing like this...they're a pain to debug and a pain to maintain if you start sticking business logic in there, which database accessing is.

  6. #6
    karq is offline Member
    Join Date
    May 2010
    Posts
    63
    Rep Power
    0

    Default

    Quote Originally Posted by flyfisherman View Post
    It is called dynamic dropdowns

    Here is how I did it

    Master drop down
    //code ...
    I made a mistake or your code dosent work?

    heres my code:
    Master drop down
    Java Code:
    <select name="department" onchange="getWorkPositionList(this)" id="department">
                                              <option>Kõik</option>
                                              <option>IT</option>
                                              <option>Turundus</option>
                                              <option>Finants</option>
                                            </select>
    slave drop down
    Java Code:
    <select name="workPosition" id="workPosition">
                              <option>Kõik</option>;
                                </select>
    js file
    Java Code:
    function getWorkPositionList(sel){
        getList(sel);
        }
    
    
    var ajax = new Array();
    function getList(sel) {
        var department = sel.options[sel.selectedIndex].value;
        document.getElementById('workPosition').options.length = 1;    // Empty city select box
        if(department.length > 0) {
            var index = ajax.length;
            ajax[index] = new sack();
    
            ajax[index].requestFile = '/DropDownGen.jsp?department='+ department;    // Specifying which file to get
            ajax[index].onCompletion = function(){ createWorkPositionList(index) };    // Specify function that will be executed after file has been found
            ajax[index].runAJAX();        // Execute AJAX function
        }
    }
    
    function createWorkPositionList(index) {
        var obj = document.getElementById('workPosition');
        eval(ajax[index].response);    // Executing the response from Ajax as Javascript code
    }
    jsp file
    Java Code:
    <%@page contentType="text/html" pageEncoding="UTF-8" import="filter.sql.*,
            filter.model.Employee,
            java.util.*;"%>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    
    <%
    List<Employee> workPositions = null;
    
    String department = request.getParameter("department");
    if (department == null){
        department = "Kõik";
    }
    SqlManager sqlManager = new SqlManager();
    if(department.equals("Kõik")){
        workPositions = sqlManager.getQueryList("SELECT DISTINCT ametikoht From Employee");
    }
    else{
        workPositions = sqlManager.getQueryList("SELECT DISTINCT ametikoht From Employee WHERE osakond='"
                + department + "'");
    }
    for (int i = 0; i < workPositions.size(); i++) {
        if(workPositions.get(i) != null && !workPositions.get(i).equals("")){
        out.println("obj.options[obj.options.length] = new Option('" + workPositions.get(i) + "');");
        }
    }
    %>
    And if i run my page, and change the value of master drop down menu, then nothing happens.

  7. #7
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,036
    Rep Power
    20

    Default

    Debug both the Javascript and the JSP to see where it's going.

    ETA: Presuming you have no errors anywhere of course.
    Last edited by Tolls; 10-19-2010 at 04:13 PM.

  8. #8
    karq is offline Member
    Join Date
    May 2010
    Posts
    63
    Rep Power
    0

    Default

    Chromes javascript console gives this
    Java Code:
    Uncaught ReferenceError: sack is not defined categoryList.js:12
    line 12 in categoryList.js is
    Java Code:
    ajax[index] = new sack();
    maybe someone can help me, I have 0 experience with javascript.

  9. #9
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,036
    Rep Power
    20

    Default

    Ah, well I guess flyfishermans javascript was including some third party library?

    Quick Google and its the Simple Ajax Code Kit.

    I think this is the correct version.

  10. #10
    karq is offline Member
    Join Date
    May 2010
    Posts
    63
    Rep Power
    0

    Default

    Quote Originally Posted by Tolls View Post
    Ah, well I guess flyfishermans javascript was including some third party library?

    Quick Google and its the Simple Ajax Code Kit.

    I think this is the correct version.
    Thanks Tolls.

    But now I get this error:
    Java Code:
    Uncaught SyntaxError: Unexpected token <  CategoryList.js:23
    And line 23 in CategoryList.js is
    Java Code:
     eval(ajax[index].response);
    After that I tried something like this:
    Java Code:
    function addOption(selectbox,text,value )
    {
    var optn = document.createElement("OPTION");
    optn.text = text;
    optn.value = value;
    selectbox.options.add(optn);
    }
    
    function createWorkPositionList(index) {
        var list = new Array();
        list = ajax[index].response.split(" ");
        for(var i = 0; i < list.length; i++){
        addOption(work_position,list[i],list[i]);
    }
    after this changes it display's the values in a row, like this
    <option>james john jane mike</option>
    But it should display so:
    <option>james</option>
    <option>john</option>
    <option>jane</option>
    <option>mike</option>
    Last edited by karq; 10-19-2010 at 07:11 PM.

  11. #11
    flyfisherman is offline Member
    Join Date
    Mar 2010
    Posts
    26
    Rep Power
    0

    Default

    Sorry I completely forget on this :)

    /* Simple AJAX Code-Kit (SACK) v1.6.1 */
    /* ©2005 Gregory Wild-Smith */
    /* Twilight Universe | by Gregory Wild-Smith */
    /* Software licenced under a modified X11 licence,
    see documentation or authors website for more details */

    Here is the link where you can find it...

    This code was written a long time ago so I forget on this .js file which also need to be included in header...


    Also here is the original link where I found this... http://www.dhtmlgoodies.com/scripts/...ed-select.html

    Only I made some changes so it can effect two slave drop-downs and I wrote it in Java instead of PHP which can be found on the link above...
    Last edited by flyfisherman; 10-19-2010 at 10:42 PM.

Similar Threads

  1. java communicating with javascript
    By sunyi000 in forum New To Java
    Replies: 12
    Last Post: 08-10-2010, 07:44 AM
  2. Replies: 0
    Last Post: 02-16-2010, 10:15 PM
  3. HonoGenerate for Java,jsp,html,javascript,css
    By jaapnap in forum Reviews / Advertising
    Replies: 0
    Last Post: 12-05-2009, 11:56 PM
  4. JSON from javascript to java servlet
    By boss-tech in forum Java Servlet
    Replies: 1
    Last Post: 09-18-2009, 08:27 AM
  5. JavaScript to Java Statement
    By mutuah in forum Advanced Java
    Replies: 0
    Last Post: 08-08-2007, 05:16 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •