Get selected value from dynamic selection list - java

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>

Related

Enabling the data from second dropdown when it selected in the first dropdown with jQuery

How can I write a jQuery function that enables the value from second dropdown only if a value is selected on the first dropdown?
As I selected Shiva in first drop down it should be disabled from 2nd drop down.
fist drop down value must not be equal to 2nd dropdown.
<select class="form-control" id="select2">
<option value="1556456">Shiva</option>
<option value="34234">Disha</option>
</select>
<select class="form-control" id="select3">
<option value="1556456">Shiva</option>
<option value="34234">Disha</option>
</select>
Not sure if this is what you mean. Let me know. You can use a .find and .filter on it.
$('select').on('change', function() {
$('option').prop('disabled', false);
$('select').each(function() {
var val = this.value;
$('select').not(this).find('option').filter(function() {
return this.value === val;
}).prop('disabled', true);
});
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<select class="form-control" id="select2">
<option value="1556456">Shiva</option>
<option value="34234">Disha</option>
</select>
<select class="form-control" id="select2">
<option value="1556456">Shiva</option>
<option value="34234">Disha</option>
</select>
</form>

How to properly update an Object in the back-end from the front-end using Spring and ThymeLeaf?

I'm getting trouble trying to update my Object in the back-end via a front-end template.
This is my template, it uses ThymeLeaf
<form id="formUpdate" method="put">
<div class="row">
<div class="col s12">
<h2> Modificar Gustos</h2>
</div>
</div>
<div class="divider"></div>
<div class="row">
<label for="selectGusto">Nombre del gusto a cambiar</label>
<select name="gustos" id="selectGusto">
<option value="-1" selected="selected" disabled="disabled">Lista de Gustos</option>
<option th:each="gusto : ${gustos}" th:text="${gusto.nombre}" th:value="${gusto.id}"> </option>
</select>
</div>
<label for="newName">Nuevo Nombre</label>
<input type="text" name="newName" id="newName" />
<div class="row">
<label for="selectCat">Elegir nueva Categoria</label>
<select name="newCat" id="selectCat">
<option value="-1" selected="selected" disabled="disabled">Nueva Categoria</option>
<option value="Dulces de Leche">Dulce de Leche</option>
<option value="Cremas">Cremas</option>
<option value="Chocolates">Chocolates</option>
<option value="Frutales">Frutales</option>
</select>
</div>
<button type="submit" id="btn-submit" class="button">Modificar</button>
</form>
This is my JS linked to the template:
var newCatId;
var idGusto;
var newName;
$('#selectCat').on('change', () => {
var value = $('#selectCat').val();
if(value === "Dulces de Leche") {
newCatId = 1;
}
else if(value === "Cremas") {
newCatId = 2;
}
else if(value === "Chocolates") {
newCatId = 3;
}
if(value === "Frutales") {
newCatId = 4;
}
console.log('newCatId: ' + newCatId);
console.log('idGusto ' + idGusto);
console.log('newName: ' + newName);
});
$('#selectGusto').on('change', function() {
idGusto = $(this).val();
});
newName = $('#newName').val();
$('#btn-submit').on('submit', (e) => {
e.preventDefault();
var url = idGusto + " '/edit' + '/' "+ newName + '/' + newCatId;
$('#formUpdate').attr('action', url);
});
And this is the Spring controller that should handle the request:
#RequestMapping(value = "/gustos/{id}/edit/{newName}/{newIdCat}")
public String updateGustoById(#PathVariable("id") int id, #PathVariable("newIdCat") int newIdCat, #PathVariable("newName") String newName){
Gusto gusto = gustoService.findGustoById(id);
gusto.setNombre(newName);
gusto.setIdCategoria(newIdCat);
gustoService.update(gusto);
return "redirect:/gustos/edit";
}
Ok !! This code doesn't breaks anywhere but when I click on the submit button the variables in the JS travel in the URL as a Query String, that's not what I want to.
Example of my URL after clicking the form's submit button:
http://localhost:8080/gustos/edit?gustos=106&newName=Dulce+de+Leche+Granizado&newCat=Dulces+de+Leche
This is my first time making a Spring App!
My question is, how can I send the information to the controller in the right way? How do people normally update an Object if is not like this? :(
EDIT: The expected values are OK, that means the JS is working OK. The problem is sending the values to the back-end !! The form is sending them as a Query String and that's not what I need, neither the assigned values on the Query String are fine
In Your Scenario, Your trying to form path param URL
1.Instead of path params you can directly specify the action attribute in form element
<form id="formUpdate" method="GET" action="http://localhost:8080/gustos/edit">
method attribute can be GET or POST according to your need.
And newCat Select box like
<select name="newCat" id="selectCat">
<option value="-1" selected="selected" disabled="disabled">Nueva Categoria</option>
<option value="1">Dulce de Leche</option>
<option value="2">Cremas</option>
<option value="3">Chocolates</option>
<option value="4">Frutales</option>
</select>
In Backend you can use #RequestParam to get paramter values
#RequestMapping(value = "/gustos/edit")
public String updateGustoById(#RequestParam(value="gustos") int id, #RequestParam(value="newCat")
int newIdCat, #RequestParam(value="newName") String newName)
{
Gusto gusto = gustoService.findGustoById(id);
gusto.setNombre(newName);
gusto.setIdCategoria(newIdCat);
gustoService.update(gusto);
return "redirect:/gustos/edit";
}
2.Another approach, Construct a JSON string with form field values (like you did for path params), While Submitting the form send this JSON string to back end through ajax call.
On your service layer keep this JSON String as Java beans (Spring Boot bind JSON values with the bean fields through #RequestBody annotation, if bean structure matched with the JSON).
I would recommend using th:object in your form. This creates an object of a given type instantly when you submit your form. So, let's say your object is of type Gusto. If you want to create a new entity from scratch, you could add this method in your controller that will return a new entity of type Gusto.
New Model Attribute
// In order to use th:object in a form, we must be able to map a new entity to that form.
// In this case we return a Gusto entity.
#ModelAttribute(value = "newGusto")
public Gusto newGusto() {return new Gusto();}
Form
So now, you can use this entity in a form using th:object="${newGusto}". This will create a new entity for you, which you might mapped fields to it.
In order to do so you would need to add following one elements to your form.
<form action="/gustos/edit/" id="formUpdate" method="put" th:object="${newGusto}">
<div class="row">
<div class="col s12">
<h2> Modificar Gustos</h2>
</div>
</div>
<div class="divider"></div>
<div class="row">
<label for="selectGusto">Nombre del gusto a cambiar</label>
<select th:field="*{id}" name="gustos" id="selectGusto">
<option value="-1" selected="selected" disabled="disabled">Lista de Gustos</option>
<option th:each="gusto : ${gustos}" th:text="${gusto.nombre}" th:value="${gusto.id}"> </option>
</select>
</div>
<label for="newName">Nuevo Nombre</label>
<input th:field=*{nombre} type="text" name="newName" id="newName" />
<div class="row">
<label for="selectCat">Elegir nueva Categoria</label>
<select th:field="*{categoria} name="newCat" id="selectCat">
<option value="-1" selected="selected" disabled="disabled">Nueva Categoria</option>
<option value="Dulces de Leche">Dulce de Leche</option>
<option value="Cremas">Cremas</option>
<option value="Chocolates">Chocolates</option>
<option value="Frutales">Frutales</option>
</select>
</div>
<button type="submit" id="btn-submit" class="button">Modificar</button>
</form>
The only difference you will find with your current code, is the added th:field elements in your selects and inputs and the th:object. Each one of these inputs and selects, will automatically mapped each field to the new entity you just created in your form.
Controller
Now for your controller you would need to change it for the following.
#RequestMapping(value = "/gustos/edit/")
public String updateGusto(#ModelAttribute("newGusto") Gusto gustoToUpdate){
Gusto gusto = gustoService.findGustoById(gustoToUpdate.getId());
gusto.setNombre(gustoToUpdate.getNombre());
gusto.setIdCategoria(gustoToUpdate.getCategoria());
gustoService.update(gusto);
return "redirect:/gustos/edit";
}
Of course, in your case, it is important that you change your jquery. We don't want to change the URL now. We just want to submit the form. So the following code, would have to be removed.
$('#btn-submit').on('submit', (e) => {
e.preventDefault();
var url = idGusto + " '/edit' + '/' "+ newName + '/' + newCatId;
$('#formUpdate').attr('action', url);
});

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...

Retrieving the Selected multiple select values

I need to have multiple values selected when I call that LoadDropDown function. But its not working.... Please suggest how to get multiple options selected.
<td>Select Profession:</td>
<td>
<select name="selectcontent_profession" id="selectcontent_profession" multiple>
<option value="0">None</option>
<option value="10">Student</option>
<option value="201">Lecturer</option>
<option value="333">Head Of Department</option>
<option value="421">Principal</option>
<option value="523">Chairman</option>
<option value="667">Management</option>
<option value="784">Placement Officer</option>
</select>
</td>
<%
String s1= "10,333,421,523";
String[] array = s1.split(",");
%>
<script >
function LoadDropDown()
{
<%for(int i=0;i<array.length;i++){%>
document.getElementById("selectcontent_profession").value ="<%= array[i]%>";
<%}%>
}
</script>
First you have to declare the select's multiple selection option as follows:
<select name="selectcontent_profession" id="selectcontent_profession" multiple="multiple">
And your function should be like this:
var fld = document.getElementById('selectcontent_profession');
for(var i=0;i<fld.options.length;i++){
for(var j=0;j<array1.length;j++){
if(fld.options[i].value==array1[j])fld.options[i].selected=true;
}
}
You are trying to get the value of the dropdown whereas you have to set it to selected.
You have to add the options like
var option = document.createElement("option");
option.text = "<%= array[i]%>";
option.value = "<%= array[i]%>";
document.getElementById("selectcontent_profession").options
.add(option);
document.getElementById("selectcontent_profession").options[<%=array[i]%>].defaultSelected =true;
Use this statement in the loop.

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