How to remove options from map on selection jsp? - java

<form:select id="name1"
<form:options items="${questionsMap}"/>
</form:select>
<form:select id="name2"
<form:options items="${questionsMap}"/>
</form:select>
<form:select id="name3"
<form:options items="${questionsMap}"/>
</form:select>
The questions map come from enum.Can anyone please help how can I remove the question from the questionsMap after it is selected on the first select and display the unselected ones the second time.

You can not do it on a JSP, as the code there will run on the server side - if you don't want do extra queries to the server... So the best way is to do it with JavaScript. Jquery selectors make this task easy.
Suggestion: http://api.jquery.com/remove/
Also, events that might interest you:
http://api.jquery.com/change/
There you can even find a as example...
Just to put my example here:
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$( this ).remove();
});
})

Instead of removing options from the drop-down you could simply validate the same options selected and show the error message on submit.
var validateSubmit = function() {
var errors = [];//trace all errors here
//fetch selected values from the drop-down starting name attribute with `name`
var txt = $('select[name^=name]').map(function() {
return this.value; //get current drop-down selected value
}).get(); //get all value in array
$.each(txt, function(i, v) {//loop in the selected values
if (i !== $.inArray(v, txt)) {//inArray, gives -1 if not found else array index
errors.push('Cannot select [' + v + '] more than once');
}
});
var submit = 0 === errors.length//true if no errors, else false
if (!submit) {
alert(errors.join('\n'));//concat all errors with \n
}
return submit;//submit if true, else don't submit
};
$(function() {
$('#form1').on('submit', validateSubmit);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id='form1'>
<select name='name1'>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name2'>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name3'>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<button>Submit</button>
</form>
OR
You could simply validate the same options selected and show the error message on change.
var names;
var validateChange = function() {
var errors = []; //trace all errors here
//fetch selected values from the drop-down starting name attribute with `name`
var txt = names.map(function() {
return this.value; //get current drop-down selected value
}).get(); //get all value in array
$.each(txt, function(i, v) { //loop in the selected values
if ('' !== v && i !== $.inArray(v, txt)) { //inArray, gives -1 if not found else array index
errors.push('Cannot select [' + v + '] more than once');
}
});
if (errors.length) {
alert(errors.join('\n')); //concat all errors with \n
}
};
$(function() {
names = $('select[name^=name]');
names.on('change', validateChange);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select name='name1'>
<option value=''>-- Select --</option>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name2'>
<option value=''>-- Select --</option>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>
<select name='name3'>
<option value=''>-- Select --</option>
<option>JS</option>
<option>SQL</option>
<option>XML</option>
</select>

This is a jquery code I made which does exactly this. Also leaves empty values in (if you have "Please select" in the top) and reinserts unselected values. It does it for all select elements on the page, if you need to restrict replace the selector $("select") with a more specific one:
$( document ).ready(function() {
manageSelectValues();
$("select").change(manageSelectValues);
});
function manageSelectValues()
{
$("select").each(function() {
var id = $(this).attr('id');
var value = $(this).find(":selected").val();
if (value) {
$("select[id!='" + id + "']").find("option").filter(function() { return this.value == value;}).remove();
}
$(this).find("option").filter(function() { return this.value != value;}).each(function() {
var unselValue = $(this).val();
$("select").filter(function() { return $(this).find("option").filter(function() { return this.value == unselValue;}).length == 0; }).append(
$('<option></option>').val(unselValue).html(unselValue));
})
});
}

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>

How to change directive in angular js based on selected item from drop down

I have a drop down list and a calender. I have created directives for calender validation. Now i want to change the directive based on dropdown item selected.
Here is the html
<select class="form-control half" ng-model="address.prooftype">
<option value="" disabled>Select Address Proof</option>
<option value="dl" data-ng-disabled="paddress.prooftype == 'dl'">
Driving License
</option>
<option value="passport"
data-ng-disabled="paddress.prooftype == 'passport'">
Passport
</option>
<option value="aadharcard"
data-ng-disabled="paddress.prooftype == 'aadharcard'">
Aadhar Card
</option>
<option value="bankstatement"
data-ng-disabled="paddress.prooftype == 'bankstatement'">
Bank Statement
</option>
<option value="utilitybills"
data-ng-disabled="paddress.prooftype == 'utilitybills'">
Utility Bills
</option>
<option value="voteridcard"
data-ng-disabled="paddress.prooftype == 'voteridcard'">
Voter ID Card
</option>
</select>
<input readonly placeholder="Expiry Date" type='text'
class="btn btn-default form-control half" exp-date
data-ng-model="address.expdate"/>
Angular js Directive
App.directive('utilityDate', function () {
var link = function (scope, element, attrs) {
var date = new Date();
date.setDate(date.getDate() - 90);
var modelName = attrs['ngModel'];
//console.log(modelName);
$(element).datepicker(
{
endDate: new Date(),
startDate: date,
dateFormat: 'dd/mm/yyyy',
autoclose: true,
showMonthAfterYear: true,
showButtonPanel: true,
startView: 2,
onSelect: function (dateText) {
scope[modelName] = dateText;
scope.$apply();
}
});
$(element).datepicker('setDate', null);
};
return {
require: 'ngModel',
restrict: 'A',
link: link
}});
App.directive('expDate', function () {
var link = function(scope, element, attrs) {
var date = new Date();
date.setDate(date.getDate() + 90);
var modelName = attrs['datePicker'];
$(element).datepicker(
{
startDate: date,
dateFormat: 'dd/mm/yyyy',
autoclose: true,
showMonthAfterYear: true,
showButtonPanel: true,
startView: 2,
onSelect: function (dateText) {
scope[modelName] = dateText;
scope.$apply();
}
});
};
return {
require: 'ngModel',
restrict: 'A',
link: link
}
});
There are 2 directives namely utilitydate and expdate. I want to change the calender to utilitydate when i click on "Utility Bills" option.
Maybe what you want is just an ngSwitch : Depending on selected option, you generate one or the other directive, and you make them "point" to the same ngModel.
<directive ng-switch="paddress.prooftype">
<directive ng-switch-when="'utilitybills'">
<input readonly placeholder="Expiry Date" type='text' utility-date data-ng-model="address.expdate"/>
</directive>
<directive ng-switch-when="'otherOptionIfNeeded'">...</directive>
<directive ng-switch-default>
<input readonly placeholder="Expiry Date" type='text' exp-date data-ng-model="address.expdate"/>
</directive>
</directive>
In the example above, the directive "utilityDate" will be used when paddress.prooftype has value 'utilitybills'. Otherwise the "expDate" directive will appear.
https://docs.angularjs.org/api/ng/directive/ngSwitch

Text box and Drop Down list

I want design a web form,its have to control one Text Box and one Drop Down list when type a number between 5 and 10 in Text Box, Drop Down list is include 1,2,3,4,5 and when type a number between 11 and 20 in Text Box, Drop Down list is include 6,7,8,9,10.
How to do it without page refreshing?
please explain with code.
I think the following code may help you.
<select id="txt" onchange="changeNumber()">
<option>select value</option>
<option>10</option>
<option>11</option>
<option>12</option>
<option>13</option>
<option>14</option>
<option>15</option>
<option>16</option>
<option>17</option>
<option>18</option>
<option>19</option>
<option>20</option>
</select>
<select id="mySelect">
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
</select>
<script>
function changeNumber(){
var t_value=document.getElementById('txt').value;
if(t_value==10 ||t_value==11 || t_value==12 || t_value==13 || t_value==14 || t_value==15 ){
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect");
var j=1
for(var i=0;i<=y.options.length;i++){
y[i].text=j;
j++;
}
}
}
</script>
In this way you can solve your 2nd problem.
You can also follow the below code.
<input type="text" id="txt" onkeyup="checkValue();" />
<select id="mySelect">
<option>21</option>
<option>22</option>
<option>23</option>
<option>24</option>
</select>
<script>
function checkValue(){
var t_value=document.getElementById('txt').value;
if(t_value==10 ||t_value==11 || t_value==12 || t_value==13 || t_value==14 || t_value==15){
var x = document.getElementById("mySelect").selectedIndex;
var y = document.getElementById("mySelect");
var j=1
for(var i=0;i<=y.options.length;i++){
y[i].text=j;
j++;
}
}
}
</script>
I think this type of solution you need.

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>

Categories