How to set default value for drop-down/select in JSP? - java

I have an arraylist for Strings eqArray.
I need to show it in a drop-down list for which I'm using the following in my JSP:
<%
for(int count=0;count<eqArray.size();count++){ %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%}
%>
I have an eqName String which is part of eqArray and should be the selected value by default.
How do I go about it without having to check and set the first option as eqName always?

<% for(int count=0; count<eqArray.size(); count++){ %>
<option value="<%= eqArray.get(count) %>" <%= (eqArray.get(count).equals("eqName"))?"selected":"" %> ><%= eqArray.get(count) %></option>
<%} %>

Change the index of eqName element to 0 in the array, or use a conditional Statement.
<%
for(int count=0; count < eqArray.size(); count++){ %>
<%if(eqArray.equals("eqName"){ %>
<option selected="selected" value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%} %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%} %>
but use JSTL taglibs instead of using scriptlets.

You can do it via JQuery, which IMHO more clean:
<select data-selected="${eqName}">
<%
for(int count=0;count<eqArray.size();count++){ %>
<option value="<%=eqArray.get(count)%>"><%=eqArray.get(count)%></option>
<%}
%>
</select>
At the end of the page:
<script type="text/javascript">
$("select[data-selected]").each(function() {
var selected = $(this).data("selected");
$("select[data-selected='" + selected + "'] option[value='" + selected + "']").attr("selected", "selected");
})
</script>
By this way, you just need include the js at each of your page.
BTW, I recommend you to use JSTL and EL, which is more readable:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<select data-selected="${eqName}">
<c:forEach items="${eqArray}" var="model">
<option value="${model}">${model}</option>
</c:forEach>
</select>

You can implement these in two ways
By using jsp
" selected="selected" >
By Using Javascript at the end of the select box code
document.getElementById('selectBoxID').value=""
instead of selectBoxID id use the select box id

Related

NPE in MultiSelect option JSP

i have written a jsp code which contains mutiple select and when i click on submit i get the null pointer exception . i am using the request.getParametervalues() to fetch the data from multiple select:
jsp code is as follows
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page language="java" import="java.lang.* ,javax.servlet.*,javax.servlet.http.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form id="form1" method="get" name="form">
<select name="color1" id="dd1" multiple>
<option value="empty">Select Color</option>
<option value="RED">red</option>
<option value="BLUE">blue</option>
<option value="GREEN">green</option>
<option value="YELLOW">yellow</option>
<option value="PINK">pink</option>
<option value="BLACK">black</option>
<option value="BROWN">brown</option>
<option value="PURPLE">purple</option>
</select>
<input type="submit" value="Submit">
</form>
</body>
</html>
<%
String [] x = request.getParameterValues("color1");
if(!x.equals(""))
{
for (int i = 0; i < x.length; i++)
out.println (x[i]);
}
%>
i am getting null pointer exception in out.println (x[i]); part
i have also tried if(x ! = null) which is giving error
i have also tried this :
if(request.getParameterValues("color1").equals(null))
{
out.println("abcd");
}
its giving the same exception
Check before doing this in your scriplet
if(request.getParameterValues("color1")!=null){
//Go On
}
As your select is in same .jsp and so on start up load it will give you null for sure.
<select name="color1" id="dd1" multiple>
Moreover you are comparing array with ""
if(!x.equals("")) //No use Check for Not Null
if(x!=null)//Cahange this
If you are using form why not pass request and perform checks and other stuff in Servlet.

how to add arraylist in Jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%=new Date() %>
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<option value="<%=al%>"></option>
</select>
</body>
</html>
This is my code i want to add Arraylist in drop down in Jsp I dont know how to Bind arraylist in html obtion or drop down please help me i have tried Much but unable to do this .
You have to use JSTL <forEach> to iterate through the elements and add it to the select-option . Probably make the List a scoped attribute . Populate the List object in the servlet, set it in request/session scope and forward the request to this JSP. Remember you can populate the List in the JSP itself and use pageScope to refer it , but that will be bad design in my opinion.
<select>
<c:forEach var="element" items="${al}">
<option value="${element}">${element}</option>
</c:forEach>
</select>
Here , al is the name of the attribute which stores the List in probably request or session scope.
Use JSTL in project :
Download the JSTL 1.2 jar .
Declare the taglib in JSP file for the JSTL core taglib.
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
If you want to use just the scriptlets(which is bad off course) :
<%
List<String> al = new ArrayList<String>();
al.add("C");
..........
...........
%>
<select>
<% for(String element: al) { %>
<option value="<%=element%>"><%=element%></option>
<% } %>
</select>
The above code will work if you have defined the List as List<String> , or else you need to cast the element to String.
Read How to avoid Java Code in JSP-Files?.
EDITED
Try this:
<%
ArrayList al = new ArrayList();
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
%>
<select>
<% for(int i = 0; i < al.size(); i++) {
String option = (String)al.get(i);
%>
<option value="<%= option %>"><%= option %></option>
<% } %>
</select>
</body>
</html>
Take a look at the tag in the core JSTL library.
Store the arraylist in pageScope.myList and loop as follows:
<select>
<c:forEach items="${pageScope.myList}" var="item" varStatus="status">
<option value='${item}'></option>
</c:forEach >
</select>
This is preferable than using scriptlets which are not considered good practice
Try this: declare your arraylist in between <%! … %>
<%! ArrayList al = new ArrayList(); %>

how to display Value On select change in jsp

<html>
<head>
<style>
div { color:red; }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
<div></div>
<script>
$("select").change(function() {
var str = "";
$("select option:selected").each(function() {
str += $(this).text() + " ";
});
$("div").text(str);
}).change();
</script>
</body>
</html>
This my code I want to display on console in jsp on Select change passing the value.I want to Print onslected item in Jsp page
<%
String k=request.getParameter("sweets");
out.println(k);
%>
Like this I want to Print on select item data please help me
Enclose select box with-in form tag and in
onchange method of select , trigger form submit
<form id="resultform" action="resultPage.jsp">
<select name="sweets" multiple="multiple">
<option>Chocolate</option>
<option selected="selected">Candy</option>
<option>Taffy</option>
<option selected="selected">Caramel</option>
<option>Fudge</option>
<option>Cookie</option>
</select>
</form>
In jquery method write
$("select").change(function() {
$('#resultform').submit();
}

Displaying array values in jsp

I have following two array in my code
List<Double> centralityList = (List<Double>) request
.getAttribute("centralityList");
List<String> labelList = (List<String>) request
.getAttribute("labelList");.
Now I have six string values and corresponding 6 double values of the string in these two array. My question is how to display them in tabular format in my JSP?Is this possible
For Example:
label list contains [a,b,c,d,e]
centrality list contains- [4,6,8,9,0]
So now I want to display output like:
label list centrality list
a 4
b 6
c 8.
. .
etc
Yes of course you can. You can use scriplets but they are not recommended. Instead use JSTL.
Try this out:
Have this at top of your JSP:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
And code for displaying data
<c:forEach begin="0" end="${fn:length(centralityList) - 1}" var="index">
<tr>
<td><c:out value="${centralityList[index]}"/></td>
<td><c:out value="${labelList[index]}"/></td>
</tr>
</c:forEach>
try this code
<%
List<Double> centralityList = (List<Double>) request
.getAttribute("centralityList");
List<String> labelList = (List<String>) request
.getAttribute("labelList");
String myString="";
%>
<table>
<tr><td>
<%
for(int i = 0; i < labelList.size(); i++)
{
out.println((String)labelList.get(i));
}
%>
</td><td>
<%
for(int i = 0; i < centralityList.size(); i++)
{
out.println((double)centralityList.get(i));
}
%>
</td>
</table>
You can achieve this eaisly by using JSTL which is even more easy and far better way but as in your code I didn't find any evidence of using JSTL , so this is the way for now
You can use JSTL tags and iterate through this-
<c:forEach var="Array" items="userNames">
// do something with the element
</c:forEach>
Use this in your jsp page
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

Java populating <option> dropdown list

I have the following code:
<div>
<%
TaxonomicTypeFeed ttf = new TaxonomicTypeFeed();
ArrayList<String> tmp = ttf.getTypes();
System.out.println("Going to print");
for (int i=0; i < tmp.size(); i++)
{
System.out.println(tmp.get(i));
}
%>
<form>
<select>
<%
Iterator<String> i = tmp.iterator();
while (i.hasNext())
{
String str = i.next(); %>
<option value="<%str.toString();%>"><%str.toString();%>
</option>
<%}%>
</select>
</form>
</div>
It creates a dropdown list fine, however there is no text.
This is the first time I have ever used any of these options before, so I have no idea if I am even going about it in the right manner.
You need to print the values by <%= %>. The <% %> won't print anything.
<option value="<%=str%>"><%=str%></option>
Unrelated to the problem: this is not the best practice. Consider using taglibs/EL. You end up with better readable/maintainable code.
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:useBean id="taxonomicTypeFeed" class="com.example.TaxonomicTypeFeed" />
...
<select>
<c:forEach items="${taxonomicTypeFeed.types}" var="type">
<option value="${type}">${type}</option>
</c:forEach>
</select>
Instead of <jsp:useBean> you can also use a preprocessing servlet.

Categories