0

I am passing an arraylist from controller to this homepage.jsp. I am displaying the values using jstl tags.

<c:forEach items="${orgList}" var="item">
<tr>
 <td>
    <input type="radio" class="rbutton" name="chooseOrg" value="${item.orgId}">&nbsp&nbsp&nbsp
    <a href="http://localhost:8080/SpringDemo/deptPage/${item.orgId}">
    <c:out value="${item.orgName}" /></a>
 </td>
 <td>
    <c:out value="${item.orgDesc}" />
 </td>
</tr>

This is the code where I am iterating.It is displaying it perfectly fine. I want these values somewhere else in javascript.This is what i tried so far:

    var radioButtons = $("#orgDisplayForm input:radio[name='chooseOrg']");
    var totalFound = radioButtons.length;
    var checkedRadioButton = radioButtons.filter(':checked');
    var selectedIndex = radioButtons.index(checkedRadioButton);

selectedindex gives me right index of the for the arraylist.I checked it using alerts.However the alert below always gives the first value in the arrayList orgList.

    alert("${orgList.get(selectedIndex).orgName}");
    $("#updateName").val("${orgList.get(selectedIndex).orgName}"); 

My motive is to take the selectedIndex and get correspoding orgname from the arralist orgList and set it for the input field with id "updateName".Looking forward to help.

The entire code for reference is :

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<style>
html,body {
    width: 100%;
}
#insertPopUp,#updatePopUp {
    display:none;
}

</style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script>


$(document).ready(function(){
 /*    $("#insertPopUp").hide();    in css its display had to be made none*/



 $("#insert").click(function(){

     $("#insertPopUp").dialog({
            autoOpen:false,
            show: 'slide',
            resizable: false,
            position:"relative",
            stack: true,
            height: 'auto',
            width: 'auto',
            modal:true
        }); 
        $("#insertPopUp").dialog("open");
});

$("#popUpSave").click(function(){
    $.ajax({  
          type : 'POST',  
          url : "http://localhost:8080/SpringDemo/insertOrganization/"
          +"?insertName="+$("#insertName").val()
                  +"&insertDescription="+$("#insertDescription").val(), 
          success : function(){
              $("#insertPopUp").dialog("close");
              window.location.href="http://localhost:8080/SpringDemo/homePage";
          }       

      });
}); 


$("#delete").click(function(){  
    //to get the index of the selected option in a radio button group

    /* var radioButtons = $("#orgDisplayForm input:radio[name='chooseOrg']");
    // this should contain the count of all your radio buttons
    var totalFound = radioButtons.length;
    // this should contain the checked one
    var checkedRadioButton = radioButtons.filter(':checked');
    // this should get the index of the found radio button based on the list of all
    var selectedIndex = radioButtons.index(checkedRadioButton);
    alert(selectedIndex); */



    // to get value of the selected option in a radio button group    
    var orgid = $("#orgDisplayForm input[name='chooseOrg']:checked").val();
    $.ajax({  
        type : 'POST',  
        url : "http://localhost:8080/SpringDemo/deleteOrganization/" +"?orgid="+orgid, 
        success : function(){
          window.location.href="http://localhost:8080/SpringDemo/homePage";
        }         
    }); 
});


$("#update").click(function(){
    debugger;
    var orgid = $("#orgDisplayForm input[name='chooseOrg']:checked").val();
    $("#updatePopUp").dialog({
        autoOpen:false,
        show: 'slide',
        resizable: false,
        position:"relative",
        stack: true,
        height: 'auto',
        width: 'auto',
        modal:true
    }); 
    $("#updatePopUp").dialog("open");

    var radioButtons = $("#orgDisplayForm input:radio[name='chooseOrg']");
    // this should contain the count of all your radio buttons
    var totalFound = radioButtons.length;
    // this should contain the checked one
    var checkedRadioButton = radioButtons.filter(':checked');
    // this should get the index of the found radio button based on the list of all
    var selectedIndex = radioButtons.index(checkedRadioButton);
    /* alert("${selectedIndex}"); */
    /* var name = ${orgList};
    <c:out value="${colors[0]}"/> */
    /* $("#updateName").text($orgList[selectedIndex].orgName); */
    /* alert("<c:out value="${orgList[0].orgName}"/>");  */
    /* $("#updateName").text("<c:out value="${orgList[0].orgName}"/>");  */
    /* alert("<c:out value="${orgList.get(selectedIndex).orgName}"/>");
    alert("${orgList.get(selectedIndex).orgName}"); */


    //$("#updateName").val("${orgList.get(selectedIndex)}"); 
    $("#updateName").val("${orgList.get(selectedIndex)}");


    <%-- alert("${orgList.get(2).orgName}");
    $("#updateName").text(<%=${orgList.get(i)}%>) --%>; 



    /* $("#updateDescription").text(${orgList[selectedIndex].orgDesc}); */

});

$("#popUpUpdate").click(function(){


    var orgid = $("#orgDisplayForm input[name='chooseOrg']:checked").val();
    $.ajax({  
          type : 'POST',  
          url : "http://localhost:8080/SpringDemo/updateOrganization/"
          +"?updateName="+$("#updateName").val()
                  +"&updateDescription="+$("#updateDescription").val()
                  +"&orgid="+orgid, 
          success : function(){
              $("#updatePopUp").dialog("close");
              window.location.href="http://localhost:8080/SpringDemo/homePage";
          }       

      });
});

});

</script>

</head>
<body>
<br>
<br>
<br>
     <form:form id="orgDisplayForm">
        <table align="center" width="60%">
            <col width="30%">
            <col width="30%">
            <tr>
                <th align="left">Organization Name</th>
                <th align="left">Description</th>
            </tr>

            <c:forEach items="${orgList}" var="item">
                <tr>
                    <td>
                    <input type="radio" class="rbutton" name="chooseOrg" value="${item.orgId}">

                    &nbsp&nbsp&nbsp
                    <%-- <a  id ="deptAnchor" onclick=clickOrg(${item.orgId}) href="http://localhost:8080/SpringDemo/deptPage/"+${item.orgId}> --%>

                    <a href="http://localhost:8080/SpringDemo/deptPage/${item.orgId}">
                    <c:out value="${item.orgName}" /></a>
                    </td>
                    <td><c:out value="${item.orgDesc}" /></td>
                </tr>
                <tr><td></td><td></td></tr>
            </c:forEach>
            <tr><td></td><td></td></tr>
            <tr><td></td><td></td></tr>
            <tr><td></td><td></td></tr>
            <tr>

             <td><button type="button" id="insert">Insert</button>&nbsp&nbsp&nbsp<button type="button" id= "update">Update</button>&nbsp&nbsp&nbsp<button type="button" id="delete">Delete</button></td>
            </tr>
        </table>

        <div id="insertPopUp">
        <form:form method="POST" action="/insertOrganization">
        <p><label for="name">Organization name</label><p><input type="text" name="name" id="insertName" /></p></p>
        <p><label for="description">Organization description</label><p><input type="text" name="description" id="insertDescription" /></p></p>
        <button type="submit" id="popUpSave">Save</button>      
        </form:form>
        </div>


        <div id="updatePopUp">
        <p><label for="name">Organization name</label><p><input type="text" name="name" id="updateName" /></p></p>
        <p><label for="description">Organization description</label><p><input type="text" name="description" id="updateDescription" /></p></p>
        <button type="submit" id="popUpUpdate">Update</button>      
        </div>


    </form:form> 
</div>

</body>
2
  • did you try to save the values are (var list = ${orgList} ) in javascript and then you can use it as list[index] (by the way I am not expert in jsp but just an idea) Commented Aug 25, 2015 at 10:38
  • No i dint try that. Will try it. Thanks Commented Aug 25, 2015 at 11:03

2 Answers 2

1

I would say the problem is in this part:

alert("${orgList.get(selectedIndex).orgName}");
$("#updateName").val("${orgList.get(selectedIndex).orgName}");

Here, you are trying to mix two things - the server-side JSP code (${orgList.get(selectedIndex).orgName}) and browser-side Javascript. The server-side code is evaluated once, at the time of the HTML generation, and at that time, the selectedIndex value is probably 0, which gives you the orgName value of the first element of the orgList. This value is then present in the JavaScript code, which is processed by browser.

I would try to add a JavaScript array with the needed values from the orgList:

<script>
  var jsOrgList = [];
  var jsItem;
</script>
<c:forEach items="${orgList}" var="item">
  // your HTML code to generate table rows
  <script>
  jsItem = new Object();
  jsItem.orgName = '${item.orgName}';
  jsItem.orgDesc = '${item.orgDesc}';
  // ... etc., all properties needed for browser-side processing
  jsOrgList.push(jsItem);
  </script>
</c:forEach>

Then you can use the jsOrgList array in your Javacsript.

Disclaimer: The above code should be considered a Quick-and-Dirty-Hack, there are better methods to get the back-end values to the front-end.

Sign up to request clarification or add additional context in comments.

Comments

0

Thank you Jozef Chocholacek ... Your methods works fine.. I found one more way.. Iterate the table and take the values being displayed at particular row.The below code is working too.

var radioButtons = $("#orgDisplayForm input:radio[name='chooseOrg']");
var totalFound = radioButtons.length;
var checkedRadioButton = radioButtons.filter(':checked');
var selectedIndex = radioButtons.index(checkedRadioButton);


$('#orgDisplayTable tr').each(function() {
    if (this.rowIndex==selectedIndex+1)
        {

    var name = ( this.cells[0].innerText|| this.cells[0].textContent);
    var desc = ( this.cells[1].innerText|| this.cells[1].textContent);
    $("#updateName").val($.trim(name)); //trim to get rid of whitespaces in the begining or ending
    $("#updateDescription").val(desc);
    return false;
        }
        });

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.