How to find the selected element in a list in javascript
I have a jsp that I'm working on and I need to find out which item in a list is selected.
here is a screen shot of the jsp:
here is the code:
<% Venue v = (Venue)session.getAttribute("currentVenue"); %>
<% List<Conceptual_Package> cpList = Conceptual_PackageDAO.getInstance().getByVenue(v.getId()); %>
What Packages do you want to see?
<form开发者_如何学运维 method="post" action="ttp.actions.Sale3PackAction.action">
<select name="packid" id="packid">
<% for (Conceptual_Package cp: cpList) { %>
<option value="<%=cp.getId()%>"><%=cp.getName1()%></option>
<% } %>
</select>
<input type="button" value=" next " onclick="getSeats();"/>
</form>
<!--new-->
Available Seats:
<select name="aSeats" size="10" id="aSeats">
</select>
<input type="button" value=" add " onclick="addToCart();"/>
Selected Seats:
<form method="post" action="ttp.actions.sale4Action.action">
<select name="Seat2" size="10" id="seat2">
</select>
</form>
<jsp:include page="/footer.jsp"/>
You can get the selected <option>
DOM object by talking to the <select>
object:
var select = document.getElementById('packId');
var selectedOption = select.options[select.selectedIndex];
alert("Selected option: " + selectedOption.value);
You can find out the index of the selected option with the selectedIndex
property.
var index = document.getElementById('packid').selectedIndex;
If it is the value
attribute you want, you can use this (assuming index
from above)...
var value = document
.getElementById('packid')
.getElementsByTagName('option')[index]
.value;
It is best to cache a pointer to the select
element however so you don't need to select it twice :)
精彩评论