0

I'm new to JSP, I m trying to pass javascript value to jsp method.

In the below loop I m fetching list from java class and looping through with the selected value from dropdown in jsp i.e. yearVal and which value is equal assigning to a java variable. Inside the for loop, its showing the correct value for the String variable but outside the for loop its showing the last value in the list. I need to get correct value so that I can pass that String variable to a method.

<% String valYear=""; %>

<%for(int k=0;k<lists.getYearList().size();k++){%>
    if(yearVal==<%= lists.getYearList().get(k)%>){
        <%valYear = lists.getYearList().get(k);%>
        alert('inside scriptlet:::'+<%=valYear%>); 
    }
<%}%>
    alert('outside scriptlet year val:::'+<%=valYear%>);

In java the arraylist is as below:

public List<String> yearList = new ArrayList<String>();

    public List<String> getYearList() {
        if(yearList.isEmpty()){
        yearList.add("2012");
        yearList.add("2013");
        yearList.add("2014");
        yearList.add("2015");
        yearList.add("2018");
        }
        return yearList;
    }

    public void setYearList(List<String> yearList) {
        this.yearList = yearList;
    }

The last value 2018 is assigned to java variable in jsp instead of assigning the variable whicvh is equal in if loop.

Im trying like below:

For ex:

if(month != '11'){
        alert('if::'+month);
        <%abc = true;%>
    }else{
        alert('else::'+month);
        <%abc = false;%>    
    }

Though it is going inside if condition, its not setting abc to true, its setting abc to false.

cweiske
  • 30,033
  • 14
  • 133
  • 194
  • It seems the problem with the scope of the variable. Can you please post the full jsp code because we can not see the declaration of the few variable so that we can validate with it's scope. – Ravi Kumar Dec 30 '13 at 06:28
  • please don't do that (mixing js and jsp).. –  Dec 30 '13 at 06:29
  • Dont have an option, no frameworks being used in this application, I have to use javascript along with jsp :( – user3069111 Dec 30 '13 at 06:41

2 Answers2

0

Your javascript value is overriding in each iteration.

what you have to add a condition,

if(conditionForCorrectValue){
 var js = <%=valYear%>;
}

As a side note :How to avoid Java code in JSP files?

Community
  • 1
  • 1
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
0

Use JSTL

How to use for loop in jstl?

if(yourTrueCondition)
{
  var Year = <%= valYear %>;
  alert(Year);
}
Community
  • 1
  • 1
Prateek
  • 6,785
  • 2
  • 24
  • 37