1

I have two arraylists named as asclist,desclist which contains ascending records and descending records. In JSP, i can iterate these two arraylist values.Its working fine. My Code is given below

List <UserInfo> asclist=new ArrayList<UserInfo>();
asclist=(ArrayList)request.getAttribute("ascend");
if(!asclist.isEmpty())
{
    for(UserInfo info: asclist)
    {
        out.print("<td>"+info.getId()+"</td>");
        out.print("<td>"+info.getName()+"</td>");
        out.print("<td>"+info.getAge()+"</td>");
        out.print("<td>"+info.getSalary()+"</td>");
        out.print("<br>");
    }
   }
    List <UserInfo> desclist=new ArrayList<UserInfo>();
desclist=(ArrayList)request.getAttribute("descend");
if(!desclist.isEmpty())
{
    for(UserInfo info: desclist)
    {
        out.print("<td>"+info.getId()+"</td>");
        out.print("<td>"+info.getName()+"</td>");
        out.print("<td>"+info.getAge()+"</td>");
        out.print("<td>"+info.getSalary()+"</td>");
        out.print("<br>");
    }
   }
%>

what i need is how can i achieve this code in javascript using functions with same button. First time, by click the button the ascending should be work and next time if i click the button the descending should be work. How can we achieve this. Thanks in advance..

My JavaScript Code is

<script>
function Ascend()
{ 
<%
List <UserInfo> alist=new ArrayList<UserInfo>();
alist=(ArrayList)request.getAttribute("ascend");
if(!alist.isEmpty())
{
    for(UserInfo info: alist)
    {
        out.print("<td>"+info.getId()+"</td>");
        out.print("<td>"+info.getName()+"</td>");
        out.print("<td>"+info.getAge()+"</td>");
        out.print("<td>"+info.getSalary()+"</td>");
        out.print("<br>");
    }
    alist.clear();
}
else
{
    out.print("The list is empty");
}
%>

}
</script>
<input type="button" onclick="Ascend()" value="SORT" />   

But its not working....

Pearl
  • 384
  • 1
  • 8
  • 15

1 Answers1

0

you should try to populate a javascript array within the function (probably an array of arrays) and then use it to set the values in the html

function Ascend()
{ 
var list = [];
<%
List <UserInfo> alist=new ArrayList<UserInfo>();
alist=(ArrayList)request.getAttribute("ascend");
if(!alist.isEmpty())
{
    for(UserInfo info: alist)
    {
        out.print("list.push([\"" + info.getId() +"\"]);")
    }
    alist.clear();
}
%>
// write javascript code to iterate over 'list' and create html elements on the client side
}
</script>

basically you need to generate the javascript code using code in the jsp

Dev Blanked
  • 8,555
  • 3
  • 26
  • 32