Getting value from <select> in jsp - java

In my Java class I've declared an attribute like this,
String option = "<select name='logopt'><option value='fulllog'>Complete Log</option><option value='InfoLog'>INFO Log</option><option value='ErrorLog'>Error Log</option></select><br><br>";
request.setAttribute("LogOption", option);
in my jsp I've accessed the same like this,
<div id="box">${LogOption}</div>
Now as this is a select box, I want to get the select box value in Javascript How do I do this?

Like this -
JavaScript --> var selectVal = document.getElementsByName('logopt')[0].value;
jQuery --> var selectVal = $('select[name=logopt]').val();
Demo ----> http://jsfiddle.net/8t6mP/

Based on this answer
In my Java class I've changed what I had to,
String option = "<select name='logopt'onchange='xyz(this)'><option value='fulllog'>Complete Log</option><option value='InfoLog'>INFO Log</option><option value='ErrorLog'>Error Log</option></select><br><br>";
request.setAttribute("LogOption", option);
in my jsp page, I've added
function xyz(sel)
{
var val = sel.value;
alert(val);
}
and now this gives me the value of select

you can use attribute selector as specified of jquery as specified by Adil
<div>
<select name='logopt'>
<option value='fulllog'>Complete Log</option>
<option value='InfoLog'>INFO Log</option>
<option value='ErrorLog'>Error Log</option>
</select>
</div>
<input type="button" onClick ="return test();"/>
and js method
function test()
{
var x = $('select[name=logopt]').val();
alert(x);
}
jsfiddle link
jsfiddle

Related

Take a variable from thymeleaf th:each

Can i use variable charity from th:each in another block of code. For example
<select class="select-field">
<option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}"></option>
</select>
<div>
<p th:text="${'You selected '+ charity.name}">
<div>
No, Thymeleaf is rendered on the server-side, so to accomplish this, you would need to use js or jQuery. Something like the code below should do the trick.
jQuery
$(document).ready(function() {
// If you want the option's text.
$('.select-field').on('change', function() {
$('p').text("You selected " + $(this).find('option:selected').text()));
})
// If you want the option's value.
$('.select-field').on('change', function() {
$('p').text("You selected " + $(this).val()));
})
})
UPDATE
If you would like to add more information from your charity object to your options, you could use th:attr. So, for example, if you want the charity's description and image name, then you could do something like the following.
HTML
<select class="select-field">
<option th:each="charity : ${charities}" th:value="${charity.id}" th:text="${charity.name}" th:attr="data-description=${charity.description}, data-image=${charity.image}"></option>
</select>
Then, you could just get each attribute value using jQuery .attr() function.
$(document).ready(function() {
$('.select-field').on('change', function() {
var selectedOption = $(this).find('option:selected');
var name = $(selectedOption).text();
var id = $(selectedOption).val();
var description = $(selectedOption).attr('data-description');
var imageName = $(selectedOption).attr('data-image');
// Find your image by id.
var image = $('#myImage');
// Set your new image.
$(image).attr('src','/img/'+ imageName));
})
})
In HTML, you can make following change to div tag:
<div class="display-class">
<p></p>
<div>
This will help identify particular div
Then you can use jQuery to display the name of the selected option.
<script type="text/javascript">
$('.select-field').on("change", function() {
var selectedOption = $(this).find('option:selected').text();
$div = $('.display-class');
$p = $div.find('p');
$p.text("You selected: " + selectedOption);
});
</script>

Refreshing Page With A Parameter in JSP

I have a JSP page in my web application and i want to refresh the page with the parameter of option.
<select class="form-control combobox" name="education" >
<option value="" disabled selected hidden>Choose an education</option>
<option>English</option>
<option>French</option>
<option>Dutch</option>
<option>Spanish</option>
</select>
I want to use this parameter for querying my database again. Forexample;
<%
BookDAO bdao = new BookDAO();
for (TblBooks book : bdao.getAllBooks()) {%>
<tr>
<td><%=book.getTittle()%></td>
<td><%=boek.getAuthor()%></td>
<td><%=boek.getCategory()%></td>
<td><%=boek.getEducation()%></td>
<td><input type='checkbox' name ='chk1' /></td>
</tr>
<% }%>
I can get the parameter with request.getParameter("education") but how can i refresh page and query again with this parameter?
In Javascript, You can ask a web page to reload itself (the exact same URL) by:
location.href = location.href;
You can ask a web page to load a different location using the same mechanism:
location.href = 'http://www.google.com'; // or whatever destination url you want
You can get the value of a select control (which needs to have an id attribute):
var ctrl = document.getElementById("idOfSelectControl");
var selectedOption = ctrl.options[ctrl.selectedIndex].value;
So, if you update your JSP to give the control an id:
<select class="form-control combobox" id="education" name="education" >
you should be able to reload the page:
var educationControl = document.getElementById("education");
var selectedOption = educationControl.options[educationControl.selectedIndex].value;
location.href = "http://mysite.example/mypage?education=" + selectedOption;
By the help of Jason i have solved it. I added an onchange event to my select tag
onchange="changeThePage()"
Then i defined a javascript function.
function changeThePage() {
var selectedOption = "book.jsp?education=" + $("#education option:selected").text();
location.href = selectedOption;
}
Then i got the parameter by
String education = request.getParameter("education");
Then i added String education as parameter to my bdao.getAllBooks(education)) method for to query.
'
<script>
function abc(){
var yourSelect = document.getElementById( "ddlViewBy" );
var val = yourSelect.options[ yourSelect.selectedIndex ].value;
//window.location.href=window.location.href;
alert(val);
window.location.replace("index.jsp?name="+val);
}
</script>
<select id="ddlViewBy" onchange="abc()">
<option>select</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
<%
String name=request.getParameter("name");
if(name!=null){
%>
<table>
<tr>
<td>author<%=name%></td>
<td>book name<%=name%></td>
</tr>
</table>
<%
}
%>
Hi,
try this, this will be helpful,
when you select a value it will call abc, function and then you are assigning that value in scriptlet..and also page is refreshing. in scriptlet you can access that value using request.getParameter("name").
now you can write your code inside scriptlet..hope helpful for someone.. :)
thanks...

How to get selected dropdown value in scriptlet

<select name="userSelected">
<option value="-1">---Select---</option>
<c:forEach items="${users}" var="user" varStatus="status">
<option value="${user.userId}">${user.userName}</option>
</c:forEach>
</select>
<button type="button" onclick="window.location.href='${pageContext.request.contextPath}/viewExpense/userSelected/<%=-1%>'">view</button>
when a user selects any value from dropdown then we can get the corresponging value using the name attribute (in this case name is "userSelected"). But how I can append this value in the href url above using that scriptlet. Someone help!!!
If you are linking to an anchor on a page you need to put a # in front of the anchor.
Try This
$("#yourDropdown").change(function () {
var selectedValue = $('#yourDropdown option:selected').val();
$("a").attr('href','#'+selectedValue); // just Append # tag before value
});
You can try something like :
<select id="userSelected">
----------
----------
</select>
<button type="button" onclick="submitPage();">view</button>
<script type="text/javascript">
function submitPage() {
var elm = document.getElementById("userSelected");
var strVal = elm.options[elm.selectedIndex].value;
window.location.href = '/viewExpense/userSelected/' + strVal;
}
</script>
If possible, you try the same thing using JQuery.
<select id="userSelected">
--------
--------
</select>
<button id="submitButton">view</button>
<script type="text/javascript">
$(document).ready(function() {
$('#submitButton').on('click', function() {
window.location.href = '/viewExpense/userSelected/' + $('#userSelected :selected').text();;
});
});
</script>

Get selected value from dynamic selection list

I am working on a jsp project where I have a dynamic selection list. The values in this list change according to the value selected in the 1st selection list.
Here's the code:
<script language="JavaScript" type="text/javascript">
function optionsChange(){
var service = document.getElementById("service").value;
if(service == 'GSM'){
document.getElementById("cdmaService").value= '';
document.getElementById("cdmaService").style.display = 'none';
document.getElementById("gsmService").style.display = 'block';
$('gsmService').attr('name', 'services');
}else if(service == 'CDMA'){
document.getElementById("gsmService").value= '';
document.getElementById("gsmService").style.display = 'none';
document.getElementById("cdmaService").style.display = 'block';
$('cdmaService').attr('name', 'services');
}
}
</script>
<select id="service" onChange="javascript:optionsChange();">
<option value="GSM">GSM</option>
<option value="CDMA">CDMA</option>
</select>
<td id="gsmService" ><select name="services" >
<option value="COMBO OFFER">COMBO OFFER</option>
<option value="CRICKET">CRICKET</option>
<option value="ASTRO">ASTRO</option>
</select>
</td>
<td id="cdmaService" style="display:none"><select name="services" >
<option value="COMBO OFFER CDMA">COMBO OFFER CDMA</option>
<option value="WIN THE DREAM">WIN THE DREAM</option>
<option value="VOICE CHAT">VOICE CHAT</option>
</select>
</td>
now when the user selects a service, lets say "GSM", and then selects a service from the second list, lets say "ASTRO". He clicks on a button which redirects him to the next page where he sees "ASTRO" printed. This works fine.
But if the user selects "CDMA" from the 1st list and then selects, let's say "VOICE CHAT" from the second list. It still prints "ASTRO" on the next page. IT should print "VOICE CHAT".
this is the method to submit form:
<script language=javascript>
function submitForm(actionStr)
{
if(actionStr=="User Details")
{
document.login.action="showUsrDetail.jsp";
document.login.submit();
}
}
this is the code for the button:
<input type="button" value="User Details" onclick="submitForm(this.value);"/>
then it redirects to the page ""showUsrDetail.jsp". And when it does the name of the service is printed on the console. For which the code is:
<%
String service = request.getParameter("services");
System.out.println("Value Added Service selected is ="+service);
%>
if i change the first selection to CDMA and then select any service from the second selection list, it still prints the Service which is under GSM.
Can somebody please help me out?
You can write a javascript function to get the selected value instead of getting the same from servlet. Put the Javascript function in script tab with language as JavaScript.
function JSGetSelectedItem() {
var dropdownIndex = document.getElementById('service').selectedIndex;
var dropdownValue = document.getElementById('service')[dropdownIndex].text;
}
<select id="service" onChange="JSGetSelectedItem()">
<option value="GSM">GSM</option>
<option value="CDMA">CDMA</option>
</select>

Can not keep the value of select box

I try to keep the value of dropbox after reload page code is
<select name="slLimit" class="slLimitCl" id="limited_num" onchange="selectedTheChoice()">
<option value="10">10</option>
<option value="25">25</option>
<option value="100">100</option>
<option value="0">All</option>
</select>
<input type="hidden" id="selectedValue" name="selectedValue" value="<s:property value="limited_num"/>" />
<script type="text/javascript">
$(document).ready(function(){
var selectedValue = $("#selectedValue").val();
console.log(selectedValue);
$("#limited_num").val(selectedValue);
});
function selectedTheChoice(){
var code = $("#hidden_bunrui_code").val();
loadAjaxData(code);
}
when the selectedTheChoice() return no data the
console.log(selectedValue);
show right value of dropbox and can keep the selected value
but when
selectedTheChoice()
return data. the
console.log(selectedValue);
show undefined and i can not keep the value of dropbox. It return to the first value
Thanks for any help
Try to store that selected value in session.Then you can access after refresh the page.Otherwise you can not access client side data after refresh the page

Categories