dynamic drop-down box, option, conditional statement
Hello:
I'm having a tiny problem here, perhaps you have more experience and can help me. I have a drop-down list that must show several options IF a condition has been met. The problem is that I still cannot make it work perfectly. Below is the code:
<!-- (...) -->
<%
String allDir[] ={"A","B","C"};
for(int i=0; i<3; i++)
{
File dir =new File("C:/db/" + allDir[i] );
String [] allFilesInDir = dir.list();
if (dir.exists() && dir.isDirectory())
%>
<option><%=allDir[i]%></option>
<%
}
%>
</select>
What I wish to be done is:
"IF the directory exist and IF the "file" is a directory THEN show the name of the directory as an option in the drop-down list."
It is showing the three items in the array , no matter if it exists or not. However when I add:
<option><%=allDir[i] + dir.exists() %><option/>
... it is showing "false" correctly to those directories that does not exists.
Thank you for your help.
--MMS
# 1
I guess, you're mixing scriptlet and javascript together. If you want to do something in the javascript based on a server side condition (using scriptlet), it will not work as expected. Recently I had this kind of issue, I used hidden variables, assigned the value(hidden) at server side and took this value back in javascript and worked it out.
skp71a at 2007-7-12 18:33:34 >

# 2
thanks.
Hmm.. I am not using any javascript in my page. I thought that with JSP alone I was able to do so.
My previous experiences have been with ASP.NET and perhaps I am still stuck in the ASP.net way.
Do you have a small example that can share?
Not a whole page of code, just the particular code lines.
Million thanks.
# 3
You are missing braces for the if statement.
If you don't provide braces, then the if statement would only apply to the very next line of code.
Given that JSP is being converted into a servlet it would probably produce something like this:
if (dir.exists() && dir.isDirectory())
out.println("\n");
out.println("<option>");
...
and the if statement would not apply where you want it to.
Solution: Add braces
<!-- (...) -->
<%
String allDir[] = {"A", "B", "C"};
for(int i=0; i<3; i++)
{
File dir = new File("C:/db/" + allDir[i] );
String [] allFilesInDir = dir.list();
if (dir.exists() && dir.isDirectory())
{
%>
<option><%=allDir[i]%></option>
<%
} // end if
} // end for
%>
</select>
As an alternative solution, implement a java.io.FileFilter which would then make the dir.list method return only the entries you are interested in.