I have a form with two identical select lists like follows:
<select id="system" name="system[1][1]">
Option 1
Option 2
Option 3
</select>
<select id="system" name="system[1][2]">
Option 1
Option 2
Option 3
</select>
I want the user select either one of this select option2. If user choose option2 in first select then hide the option2 in second select and vice versa.
Example:
var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');
if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}
Which I think is bit of messy. Is it any elegant way that I can achieve this in Javascript or Jquery?
Thanks
Try following code :
<select id="system" name="system[1][1]">
<option value="optioin-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
<select id="system" name="system[1][2]">
<option value="optioin-1">Option 1</option>
<option value="option-2">Option 2</option>
</select>
jQuery :
jQuery('select').change(function(e){
var value = $(this).val();
var selectboxId = $(this).attr('name');
jQuery('select option').show();
if(selectboxId == 'system[1][1]') {
jQuery('select[name="system[1][2]"]').find('option[value="'+value+'"]').hide();
} else if(selectboxId == 'system[1][2]') {
jQuery('select[name="system[1][1]"]').find('option[value="'+value+'"]').hide();
}
});
Try this Check out this fiddle
I hope this is what ur looking for ?
Html
<select id="system1" name="system[1][1]">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="system2" name="system[1][2]">
<option value="1">1</option>
<option value="2">2</option>
</select>
Jquery
$(document).ready(function(){
$('select').change(function(){
var select1 = document.querySelector('[name="system[1][1]"]');
var select2 = document.querySelector('[name="system[1][2]"]');
if (select1.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').hide();
$('select[name="system[1][1]"] option[value="2"]').show();
} else if (select2.value == '2') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
} else if (select1.value == '1') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
} else if (select2.value == '1') {
$('select[name="system[1][2]"] option[value="2"]').show();
$('select[name="system[1][1]"] option[value="2"]').hide();
}
});
});
I'd suggest the following approach (note the change of id properties, this is not optional, it's required in order to have valid HTML):
// cache the relevant <select> elements, here we use
// a CSS attribute-selector to get those <select>
// elements whose id attribute begins with 'system':
var selectElements = $('select[id^=system]');
// binding the anonymous function as the event-handler
// for the 'change' event, using the on() method:
selectElements.on('change', function() {
// we retrieve the index of the selected option from
// the changed <select> element:
var chosen = this.selectedIndex;
// we hide all the previously-selected <select> elements:
selectElements.hide()
// we find the <select> element at the same index as
// the chosen <option>:
.eq(chosen)
// and then show that element:
.show();
})
/* This is just to give a visual cue to
show which of the elements is currently
visible on the page: */
#system1 {
box-shadow: 0 0 1em fuchsia;
}
#system2 {
box-shadow: 0 0 1em limegreen;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="system1" name="system[1][1]">
<option>Option 1</option>
<option>Option 2</option>
</select>
<select id="system2" name="system[1][2]">
<option>Option 1</option>
<option>Option 2</option>
</select>
JS Fiddle demo.
References:
CSS:
Attribute selectors.
JavaScript:
HTMLSelectElement.selectedIndex.
jQuery:
on().
although there are some answers, here's what i came up with:
$("select").on("change", function() { //on any change event in all selects
var currentSelection = $(this); //save the used select box
//then take all selects, except the activated one, take the 'option' childs and iterate through them
$("select").not(currentSelection).find("option").each(function() {
if ($(this).val() == currentSelection.val()) //if option value = chosen value
$(this).hide(); //hide it
else //if not
$(this).show(); //show it (to reshow already hidden elements)
});
});
this works with endless options! but as soon, as you have more then 2 selects, you have to rework the 'show' part of this script...
here's a working fiddle: https://jsfiddle.net/usksL955/1/
Related
Hello is there any way to disable multiple options in a select form if you only choose one option?
For example:
First Select Form
<select name="secondchoice" id="second">
<option value="None">None</option>
<option value="Content Dev">Content Dev</option>
<option value="Web">Web</option>
<option value="Science">Science</option>
<option value="Managing">Managing</option>
</select>
Second Select Form
<select name="day2" id="exam2">
<option value="None">None</option>
<option value="Monday">Monday</option>
<option value="Tuesday">Tuesday</option>
<option value="Wednesday">Wednesday</option>
<option value="Thursday">Thursday</option>
</select>
If I select "None" in the first form then the second form must disable the options "Monday-Thursday" the only option available must be also "None" in the second form. Thank you!
You can do this with javascript by hiding options in the second elements whenever the first select element changes by checking its value and hiding elements accordingly like so:
// Select Elements
const first = document.getElementById('first')
const second = document.getElementById('second')
// Option Elements
const one = document.getElementById('one')
const two = document.getElementById('two')
// Runs whenever first select has changed
first.onchange = () => {
// Checks First Selects Value
if (first.value === '1') {
// If '1' then hide TWO and show ONE
second.value = 'ONE'
one.hidden = false
two.hidden = true
} else if (first.value === '2') {
// Else, if '2' then hide ONE and show TWO
second.value = 'TWO'
one.hidden = true
two.hidden = false
}
}
<select id='first'>
<option>1</option>
<option>2</option>
</select>
<select id='second'>
<option id='one'>ONE</option>
<option id='two'>TWO</option>
</select>
This is a very basic example and can be improved alot.
you can do something like below, so when you do selecting none, other options would be disabled, and other than none it would be enabled again
function disabledEnabled(event) {
var optiosLists = document.getElementById("exam2").options;
for (let i = 0; i < optiosLists.length; i++) {
if(event.target.value === "None"){
optiosLists[i].disabled = true;
optiosLists[0].disabled = false;
} else {
optiosLists[i].disabled = false;
}
}
}
You can either disabled select element itself and each of its options. You can find 2 ways to achieve each of those below.
Disabling Select Element
Disabling Option Element
Got this HTML:
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3">DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
Iterating over the options with this javascript & jQuery:
var departmentDDL = $(row).find('[id*="DepartmentID_"] > option');
departmentDDL.each(function () {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
$(this).remove(); // this works
}
});
I'm trying to hide the options, not remove them. Why does one work and not the other?
You have an extra ( in your if, remove it, it will work but only in Chrome with a little buggy behavior.
var departmentDDL = $('[id*="DepartmentID_"] > option');
departmentDDL.each(function() {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
//$(this).remove(); // this works
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3" >DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
Note that hiding HTML options has several issues cross browser and won't give expected results in some browsers, for further details check How to hide a <option> in a <select> menu with CSS?
remove extra ( here if (($(this)[0] and it will work
var departmentDDL = $('[id*="DepartmentID_"] > option');
departmentDDL.each(function () {
if ($(this)[0].innerHTML != "SA") {
$(this).hide(); // this does not work
//$(this).remove(); // this works
}else{
$(this).parent().val($(this).val()).change();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="trackChanges department" id="DepartmentID_0" name="DepartmentID_0">
<option value="3">DC</option>
<option value="5">PL</option>
<option value="7">SA</option>
</select>
It selected in the else part
I have HTML:
<select class="form" id="select" name="select">
<option>number1</option>
<option>number2</option>
</select>
<select name="organisation" class="form" id="cent" required>
<option value="1">UK</option>
<option value="2">SPAIN</option>
</select>
And another <select>:
<select class="form" id="ssip" name="organisation">
<option value="47" >US</option>
<option value="48">UKRAINE</option>
</select>
JQuery to show on 1 - first select on 2 - second
$(document).ready(function() {
$("#select").each(function () {
if (this.value == "1") {
$('#cent').show();
$('#ssip').hide();
}
if (this.value == "2") {
$('#cent').hide();
$('#ssip').show();
}
});
});
The problem is that when i choose option number1 appears first select with values 1 and 2 but when i select UK with value 1 and click submit it's sending value 47 , of second select's first option..
Try disabling the opposite select when toggling the selects. A control on a form will still be submitted if its display is set to none, however if the control is disabled it will not be submitted with the form.
$(document).ready(function() {
$("select").change(function () {
if (this.value == "number1") {
$('#cent').show().prop("disabled", false);
$('#ssip').hide().prop("disabled", true);
}
if (this.value == "number2") {
$('#cent').hide().prop("disabled", true);
$('#ssip').show().prop("disabled", false);
}
});
});
JS Fiddle: http://jsfiddle.net/bTJsH/
You are trying to loop one select box..
$("#select").each(function () {
There can be only one element with id "select". You should check like:
if ($("#select").value() == "1") { ..
And you don't even have values in your first select options..
i might suggest something like this
$('#select').on('change', function() {
var selected = this.selectedIndex;
$('.orgs').hide();
switch(selected) {
case 1:
$('#ssip').show();
break;
case 2:
$('#cent').show();
break;
}
});
here is an working example http://jsfiddle.net/pixelchemist/7ZGwy/
I have a validator function looping through to check and see if all inputs have been filled out, but I also need to check if the dropdown's have been selected as well. I would like to write that into the same function.
function validateSave (){
// reset status
var good = true
$('.errormessage-left').removeClass('active-left')
$('input').removeClass("warning")
$('input').each(function(){
if ($(this).val() == "") {
console.log("found an empty");
good = false
$(this).addClass("warning")
$('.errormessage-left').addClass('active-left'),
$('.modal').addClass('modal-active');
}
})
console.log(good)
return good
}
What's the best way to go about this?
You can use val() on a dropdown (<select> element) just like an input element, so just include it in your selector
$('input, select').each(function(){
You can do this :
Assuming the first element is :"please choose..."
if ($(".myDDL").get(0).selectedIndex>0)...
or
if ($(".myDDL").prop('selectedIndex')>0)...
Try this:
$('input').each(function(){
if($(this).prop('selected') == true){
// selected item
}
});
Assuming your HTML looks something like this:
<input type="text" name="whatever">
<select>
<option value="">Choose One...</option>
<option value="choice1">Choice 1</option>
<option value="choice2">Choice 2</option>
<option value="choice3">Choice 3</option>
</select>
Then your jQuery can figure it out like this
$('input, select').each(function(){
if($(this).val() == ''){
alert('Cannot be blank!');
}
else{
//proceed
}
}
you should be able to add this to your loop:
if ($(this).prop('type')=='select-one'){
if ($(this).prop('selectedIndex')==0){
console.log("found an empty");
good = false
$(this).addClass("warning")
$('.errormessage-left').addClass('active-left'),
$('.modal').addClass('modal-active');
}
}
I have multiple dropdown menus with the same options. If one option was selected, other dropdown menus will not show the selected option. When I tried to reset the selected option, it did not restore the removed select option.
HTML part:
<select id="selectNumber" class="selectbox">
<option value="0">Choose a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select id="selectNumber2" class="selectbox">
<option value="0">Choose a number</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Javascript part:
$(".selectbox").change(function(){
var selectedIndex = $(this).index();
var myVal = $(this).val();
$(".selectbox").each(function(i){
if (selectedIndex != i){
$("option", this).each(function(){
if (myVal == $(this).val() && myVal != 0){
$(this).detach();
}else{
$(this).prepend();
//not work
}
});
}
});
});
the demo but not working
Thanks for your time.
This should do what you want
/* store options */
var $selects = $(".selectbox");
var $opts = $selects.first().children().clone();
$selects.change(function () {
var myVal = $(this).val();
if (myVal !='0') {
$selects.not(this).children('[value="'+myVal+'"]').remove();
}else{
var replaceVal=$(this).data('currVal');
$selects.not(this).append( $opts.filter( '[value="'+replaceVal+'"]').clone())
}
$(this).data('currVal', myVal);
});
DEMO http://jsfiddle.net/7Ssu7/8/
EDIT Version - keeps sort order
/* store options */
var $selects = $(".selectbox");
var $opts = $selects.first().children().clone();
$selects.change(function () {
/*create array of all selected values*/
var selectedValues=$selects.map(function(){
var val=$(this).val();
return val !=0? val :null;
}).get();
$selects.not(this).each(function(){
var $sel=$(this), myVal=$sel.val() ||0;
var $options=$opts.clone().filter(function(i){
var val=$(this).val();
return val==myVal || $.inArray(val, selectedValues) ==-1;
});
$sel.html( $options).val( myVal)
});
});
DEMO: http://jsfiddle.net/8uunN/1/
When you do a detach(), the object is removed and needs to be put into a "global" variable to save as a reference.
For your purpose, you can use .hide() and .show() as it retains the object in the list, without causing a DOM insertion or removal (so definitely better for performance).
Well, your current code is not work, because you are not store selected value in another dropdown list. Also, like others said, use hide and show instead of detach and prepend.
You can see my solution in jsfiddle (tested in firefox)