I have two select lists and the second one depends on the first. I would like to allow the second select list to load and then fire some alerts after that. What is the best way to achieve this using jQuery?
For eg: The second list gets populated in the following manner below:
1 - a,b,c
2 - b,c,d
3 - a,c,d
4 - a,b
Meaning that if someone selects 1 in the first picklist, the second one is loaded with options a,b,c.
$("#first").change(function() { // bind a change event:
refreshsecond(document.theForm);
}).change(); // and trigger a "change" event immediately
function refreshsecond(form)
{
var length = $('#second').children('option').length;
alert("Length is :" + length);
}
<select id="first" name="firstName">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
<select id="second" name="secondName">
<option value='a'>a</option>
<option value='b'>b</option>
<option value='c'>c</option>
<option value='d'>d</option>
</select>
Other than having #second load elements in a certain way a better idea is to just add and replace to the elements HTML. Meaning that we start with #second being empty and change the <option> items based on the first select box's value. For example:
$("#first").change(function() {
if($(this).val() == 1)
$("#second").html(loadValues(['a','b','c']));
else if($(this).val() == 2)
$("#second").html(loadValues(['b','c','d']));
else if($(this).val() == 3)
$("#second").html(loadValues(['a','c','d']));
else if($(this).val() == 4)
$("#second").html(loadValues(['a','b']));
var length = $('#second').children('option').length;
alert("Length is :" + length);
}).change();
function loadValues(ArrValues){
var string = "";
for(var i = 0; i < ArrValues.length; i++)
string += "<option value='"+ArrValues[i]+"'>"+ArrValues[i]+"</option>";
return string;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first" name="firstName">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
</select>
<select id="second" name="secondName">
</select>
If it's dependent on the user selecting one in the first dropdown, you simply need to attach an onChange handler to the first dropdown list.
For example
$('#first').change(function() {
//do your stuff here to second dropdown list.
});
Take a look at http://api.jquery.com/change/ for more details.
Related
I'm writing a form with 4 <select> elements. They all have the same options and I would like to disable, hide, or remove the selected option from one <select> in the other <select> elements with the same options in order to prevent the user to select the same option in multiple <select> elements.
No jQuery, only plain JavaScript please.
If possible I would like the first option to always display in all <select> elements:
<option class="select-items" selected>Sélectionnez..</option>
Here is the HTML for one <select>:
<select class="custom-select mb-3" id="name_typage_0">
<option class="select-items" selected>Sélectionnez..</option>
<option class="select-items" value="designation">Désignation</option>
<option class="select-items" value="email">Email</option>
<option class="select-items" value="ville">Ville</option>
<option class="select-items" value="secteur_activite">Secteur d'activité</option>
</select>
Here is part of my JavaScript:
const custSelec = document.querySelectorAll('.custom-select');
custSelec.forEach(function(item){
item.addEventListener('change', function(){
if(item.options[item.selectedIndex].text == 'Sélectionnez..'){
count = -1;
}else{
count = 1;
total += count;
compteur.textContent = ` ${total}/${custSelec.length -1}`;
In your change event listener, you can get the current set of selected values from all <select> elements in the group, and then loop through each element's options to both disable the options currently selected elsewhere in the group as well as re-enable any options that were previously selected but have since been changed. You can avoid disabling the first "label" option in each of your selects by checking the value before disabling / enabling options.
You could use this same approach to hide or remove options keeping in mind that there are some browser compatibility issues when trying to hide <option> elements and that you would need some additional code to store the complete list of options if you were going to remove and restore them.
const selects = document.querySelectorAll('.select-group');
selects.forEach((elem) => {
elem.addEventListener('change', (event) => {
const values = Array.from(selects).map((select) => select.value);
for (const select of selects) {
select.querySelectorAll('option').forEach((option) => {
const value = option.value;
if (value && value !== select.value && values.includes(value)) {
option.disabled = true;
} else {
option.disabled = false;
}
});
}
});
});
<select class="select-group">
<option value="">Select...</option>
<option value="first">First Value</option>
<option value="second">Second Value</option>
<option value="third">Third Value</option>
</select>
<select class="select-group">
<option value="">Select...</option>
<option value="first">First Value</option>
<option value="second">Second Value</option>
<option value="third">Third Value</option>
</select>
<select class="select-group">
<option value="">Select...</option>
<option value="first">First Value</option>
<option value="second">Second Value</option>
<option value="third">Third Value</option>
</select>
Thanks a lot for your help! I added a small 'if' to fix my bug and it works perfectly (until the next bug ^^):
if(value !== ""){
option.disabled = true;
}
Or I could just :
if (value && value !== select.value && values.includes(value) && value !== "") {
option.disabled = true;
}
Another difficulty when you begin : learn to write simple code ^^z
I have two dropdown right now. I want to when the user selects "NO" the other automatically selects "YES" and vice versa.
I'm assuming I use JS here to make this occur, but not sure where to start. Below is my dropdown html code. If someone could help me get started, it would be helpful.
Code:
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" name="cmicrophone">
<option value=" " selected = "selected"> </option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" name = "microphone">
<option value=" " selected="selected"> </option>
<option value="on" >ON</option>
<option value="off">OFF</option>
</select>
</div
You can assign a same class to each select element and bind change event listener.
$('.elem').on('change', function() {
if ($(this).val() == 'on') {
$('.elem').not(this).val('off');
} else {
$('.elem').not(this).val('on');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cmicrophone" id="cmicrophone">Currently:
<select id="cmicrophone" class='elem' name="cmicrophone">
<option value="" selected = "selected"></option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
<div class="microphone" id="microphone">Microphone:
<select id="microphone" class='elem' name="microphone">
<option value="" selected = "selected"></option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
A good starting point might be listening for changes on one select, and when the change happens, selecting the other <select> and setting the right value
Here's a vanilla JS solution (no jquery required).
The idea here is to:
select both <select> elements and save them into variables to refer to later using document.querySelector
add input event listeners on both elements that call a function to handle the event
then use inside the function selectElement.selectedIndex to check the selected index of one element and use that to set the value of the other.
// select the `<select>` elements
const cmicrophone = document.querySelector('#cmicrophone');
const microphone = document.querySelector('#microphone');
// define function to handler the events
function inputHandler(thisSelect, otherSelect) {
if (thisSelect.selectedIndex == 1) {
otherSelect.selectedIndex = 2;
} else if (thisSelect.selectedIndex == 2) {
otherSelect.selectedIndex = 1;
} else {
thisSelect.selectedIndex = 0;
otherSelect.selectedIndex = 0;
}
}
// add event listeners that will 'fire' when the input of the <select> changes
cmicrophone.addEventListener('input', event => {
inputHandler(cmicrophone, microphone);
});
microphone.addEventListener('input', event => {
inputHandler(microphone, cmicrophone);
});
<div>Currently:
<select id="cmicrophone" name="cmicrophone">
<option value=" " selected = "selected"> </option>
<option value="on">ON</option>
<option value="off">OFF</option>
</select>
</div>
<div>Microphone:
<select id="microphone" name="microphone">
<option value=" " selected="selected"> </option>
<option value="on" >ON</option>
<option value="off">OFF</option>
</select>
</div>
One more thing to add: You assigned the same value to multiple ids. You should only assign one unique id per element.
I have a select box and add more button. when I click add more button it's creating another select using clone.In first select box I select one option value from select box means that value should be removed from next created select box.At the same time which selected value in select box that current value shown on current select box. Select box value is being loaded dynamically.
Eg:
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
Is it what you're looking for ?
I would recommend you to play and manipulate with index(), that won't bother your dynamic values.
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
$('button').click(function(){
//Take a clone of last
var cloneElement = $('.sectionType:last').clone();
//Get index of option selected from last
var indexToRemove = $('.sectionType:last').find('option:selected').index();
//Remove previously selected index
cloneElement.find('option').eq(indexToRemove).remove();
//Change the id of an element
cloneElement.attr("id", "section_"+parseInt($('.sectionType').length+1));
//If element has options
if(cloneElement.find('option').length)
{
//Finally append it
$('body').append("<br/><br/>").append(cloneElement);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value="">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Clone</button>
You can try like this.
$("#yourId").val(" ")//if your value has white spec else use like below line
$("#YourId").val("")//What ever you want to be selected, place your value in .val()
I hope this will help you, if you need anything please ask!
$("button").on("click", function() {
$("#section_1")
.clone()
.attr("id", "section_2")
.on("change", function() {
var sec2Val = $(this).val();
var delOption = $("#section_1 > option[value=" + sec2Val + "]").detach();
optionHolder.push(delOption);
})
.insertAfter($("#section_1"));
$(this).attr("disabled", "disabled");
});
var optionHolder = [];
$("#section_1").on("change", function() {
var sec1Val = $(this).val();
if ($("#section_2")) {
var delOption = $("#section_2 > option[value=" + sec1Val + "]").detach();
optionHolder.push(delOption);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="section" id="section_1" class="sectionType">
<option value=" ">------</option>
<option value="05">test1</option>
<option value="06">test2</option>
<option value="07">test3</option>
<option value="08">test4</option>
<option value="10">test5</option>
<option value="11">test6</option>
<option value="12">test7</option>
<option value="13">test8</option>
<option value="14">test9</option>
</select>
<button>Add more</button>
I could not find any example that suite my problem. I would like to count selected variables from drop down menu using javascript.
My biggest concern is, these drop down menu values are dynamically retrieved from db.The drop down menu is generated multiple times depending on number of student displayed in the form.
This is the codes for drop down menu of examiner name:
<select id="examinerID" name="examinerID">
<option selected disabled>Examiners Name</option>
<%
try{
//connection
String query1="select lecturerID, lecturerFullname from lecturer ";
while(rs1.next())
{
%>
<option value="<%=rs1.getString("lecturerID") %>"><%=rs1.getString("lecturerFullname") %></option>
//close connection and exception
%>
</select>
This is how it actually looks like:
Below the form, I would like to add a list of the examiner (also retrieve from db) and I would like to count how many times an examiner has been selected.
Assume these are the value in drop down menu (to make it easy to understand):
<select id="examinerID" name="examinerID">
<option selected disabled>Examiners Name</option>
<option>Mark</option>
<option>Adam</option>
<option>Lucy</option>
<option>John</option></select>
Expected outcome of counting the selected examiner:
Mark: 2 //assuming Mark has been selected twice
Adam: 1
Lucy: 1
John: 0 //assuming John is not selected to be an examiner
Change Id to class as you are creating multiple instance of select.
For eg:
HTML:-
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option>
</select>
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option> </select>
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option>
</select>
<select class="examinerID" name="examinerID">
<option selected disabled value="">Examiners Name</option>
<option value="Mark">Mark</option>
<option value="Adam">Adam</option>
<option value="Lucy">Lucy</option>
<option value="John">John</option>
</select>
JS:-
var count = {};
var selects = document.querySelectorAll("select[name=examinerID]");
for(var i=0;i<selects.length;i++){
selects[i].addEventListener("change",function(event){
count = {};
Array.prototype.forEach.call(selects, function(select, index) {
var selectedValue = select.value;
if(selectedValue != "")
count[selectedValue] = (count[selectedValue])?count[selectedValue]+1:1;
});
console.log(count)
});
}
Re your HTML:
<select id="examinerID" name="examinerID" onchange="checkLecturer()">
First, remove that id value. If you're outputting that in a loop (as your screenshot suggests), you're creating an invalid document, as id values must be unique.
If your goal is to get the value of the select that changed, pass this into your checkLecturer function:
<select name="examinerID" onchange="checkLecturer(this)">
<!-- Here ----------------------------------------^^^^ -->
...and then in checkLecturer, the first argument will be a reference to the select element:
function checkLecturer(select) {
// Use select.value or select.selectedIndex
}
If your goal is to access the values of all of the select boxes, you can find them with document.querySelectorAll:
var selects = document.querySelectorAll("select[name=examinerID]");
That will give you a NodeList, with a length telling you how many were found. You can access each one as though the NodeList were an array. So for instance, this will show the current value of each of them:
var selects = document.querySelectorAll("select[name=examinerID]");
Array.prototype.forEach.call(selects, function(select, index) {
console.log("#" + index + ": " + select.value);
});
(More on that odd-looking use of forEach in this answer on looping through arrays and array-like things such as NodeLists.)
I have two drop-down's, i want to disable the last value selected from the drop down and enable the previous value in other drop-down.
Let's say i have two drop-down's as below :
<select name="g1" id="box_g1">
<option value="Select">Select</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
<select name="g2" id="box_g2">
<option value="Select">Select</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">three</option>
</select>
If i select option : 'one' from box_g1 and then 'two' from box_g1 again (i.e. from the same box). then only the last value 'two' should be disabled in the next drop-down. Check the below fiddle :
JS Fiddle
Any help is appreciated.
Can try something like below
<script type="text/javascript">
var g1 = [],
g2 = [];
$('#box_g1 option').each(function(){g1.push($(this).val());});
$('#box_g2 option').each(function(){g2.push($(this).val());});
$('#box_g1').on('change', function(){
var options = '',
selected = $('#box_g1').val();
for(var i = 0; i < g2.length; i++){
if(selected != g1[i] && selected != 'Select'){
options += ('<option value="'+g2[i]+'">'+g2[i]+'</option>');
}
}
$('#box_g2').empty().html(options);
});
</script>
You could store the value of the last item selected from the first box, and then iterate through the 2nd box and compare the values to the stored value, disabling all those that match.