I have a form that conditionally disables select field options based on the value from a previous select field. In my example, salt is offered for sale at different weights, with weights determined by the type of salt.
My form select looks like this:
<select id="salt_type" class="form-control" name="salt_type">
<option value="null" selected disabled>Select a salt type</option>
<option value="block-salt">Block Salt</option>
<option value="tablet-salt">Tablet Salt</option>
<option value="granular-salt">Granular Salt</option>
</select>
<select id="pack_weight" class="form-control" name="pack_weight">
<option value="null" selected disabled>Select a weight</option>
<option class="hide-if-tablet-salt hide-if-granular-salt" value="8kg">8kg</option>
<option class="hide-if-block-salt" value="10kg">10kg</option>
<option class="hide-if-block-salt hide-if-granular-salt" value="25kg">25kg</option>
</select>
My JS:
$('#salt_type').bind('change', function() {
var bool = ($(this).find(':selected').val() === 'block-salt') ? true : false;
$('.hide-if-block-salt').prop('disabled', bool);
var bool2 = ($(this).find(':selected').val() === 'granular-salt') ? true : false;
$('.hide-if-granular-salt').prop('disabled', bool2);
var bool3 = ($(this).find(':selected').val() === 'tablet-salt') ? true : false;
$('.hide-if-tablet-salt').prop('disabled', bool3);
});
It works if there's only one limiting class, but if there are two, the option isn't always disabled. It doesn't even seem to be consistent in failing to disable the first, or the last class.
I tried using classList.contains:
$('#fw_salt_type').bind('change', function() {
var bool = ($(this).find(':selected').val() === 'block-salt') ? true : false;
$('.pack-weight-option').classList.contains('hide-if-block-salt').prop('disabled', bool);
});
But I get a 'classlist not defined' error. Any help appreciated.
Suggest to use non-negative class name for less confused
<option class="show-if-block-salt" value="8kg">8kg</option>
<option class="show-if-tablet-salt show-if-granular-salt" value="10kg">10kg</option>
<option class="show-if-tablet-salt" value="25kg">25kg</option>
Then on salt option change, enable only weight options with show class.
$('#salt_type').bind('change', function() {
var value = $(this).find(':selected').val();
$('#pack_weight option').each(function() {
$(this).prop('disabled', !$(this).hasClass(`show-if-${ value }`));
});
});
https://codesandbox.io/s/cranky-easley-vpcvh
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
I've got 2 dropdowns. One with 6 values :
Query 1
Query 2
Query 3
Query 4
ToxKeywords
Molecule
and the second with 2 values :
ToxKeywords
Molecule
I want that when we select ToxKeywords or Molecule in the first dropdown, the second dropdown should be empty.
Dropdowns :
<select class="form-control space" name="textQuery" id="textQuery">
<option selected disabled>Choose here</option>
<option value="ToxKeywords:%22genotoxicity%22%20AND%20ToxKeywords:%22ames%22%20OR%20ToxKeywords:%22micronucleus%22">Query 1 : Genotoxicity + Ames or Micronucleus</option>
<option value="ToxKeywords:%22systemic%20toxicity%22%20OR%20ToxKeywords:%22kidney%20toxicity%22">Query 2 : Systemic Toxicity or Kidney Toxicity</option>
<option value="ToxKeywords:%22antibacterial%20effect%22%20OR%20ToxKeywords:%22phototoxicity%22">Query 3 : Skin Sensitization + LLNA or Hript</option>
<option value="ToxKeywords:%22skin%20sensitization%22%20AND%20ToxKeywords:%22llna%22%20OR%20ToxKeywords:%22hript%22">Query 4 : Antibacterial Effect or Phototoxicity</option>
<option value="ToxKeywords:">ToxKeywords</option>
<option value="Molecules.Main_name:">Molecule</option>
</select>
<label for="textQuery2">Choose one parameter</label>
<select class="form-control space" name="textQuery2" id="textQuery2">
<option selected disabled>Choose here</option>
<option value="%20AND%20ToxKeywords:">ToxKeywords</option>
<option value="%20AND%20Molecules.Main_name:">Molecule</option>
</select>
I find this jquery code that hide only the same value wich is selected :
$(document).ready(function() {
var layout_select_html = $('#textQuery2').html(); //save original dropdown list
$("#textQuery").change(function () {
var cur_column_val = $(this).val(); //save the selected value of the first dropdown
$('#textQuery2').html(layout_select_html); //set original dropdown list back
$('#textQuery2').children('option').each(function () { //loop through options
if ($(this).val().indexOf(cur_column_val) != -1) { //do your conditional and if it should not be in the dropdown list
$(this).remove(); //remove option from list
}
});
});
})
Could someone find a way to hide both values of the second dropdown when ToxKeywords or Molecule is selected in the first one ?
$(document).ready(function() {
var layout_select_html = $('#textQuery2').html(); //save original dropdown list
$("#textQuery").change(function () {
var cur_column_val = $(this).val(); //save the selected value of the first dropdown
if($(this).val()==='ToxKeywords:' || $(this).val()==='Molecules.Main_name:') {
return $('#textQuery2').empty();
}
$('#textQuery2').html(layout_select_html); //set original dropdown list back
$('#textQuery2').children('option').each(function () { //loop through options
if ($(this).val().indexOf(cur_column_val) != -1) { //do your conditional and if it should not be in the dropdown list
$(this).remove(); //remove option from list
}
});
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control space" name="textQuery" id="textQuery">
<option selected disabled>Choose here</option>
<option value="ToxKeywords:%22genotoxicity%22%20AND%20ToxKeywords:%22ames%22%20OR%20ToxKeywords:%22micronucleus%22">Query 1 : Genotoxicity + Ames or Micronucleus</option>
<option value="ToxKeywords:%22systemic%20toxicity%22%20OR%20ToxKeywords:%22kidney%20toxicity%22">Query 2 : Systemic Toxicity or Kidney Toxicity</option>
<option value="ToxKeywords:%22antibacterial%20effect%22%20OR%20ToxKeywords:%22phototoxicity%22">Query 3 : Skin Sensitization + LLNA or Hript</option>
<option value="ToxKeywords:%22skin%20sensitization%22%20AND%20ToxKeywords:%22llna%22%20OR%20ToxKeywords:%22hript%22">Query 4 : Antibacterial Effect or Phototoxicity</option>
<option value="ToxKeywords:">ToxKeywords</option>
<option value="Molecules.Main_name:">Molecule</option>
</select>
<label for="textQuery2">Choose one parameter</label>
<select class="form-control space" name="textQuery2" id="textQuery2">
<option selected disabled>Choose here</option>
<option value="%20AND%20ToxKeywords:">ToxKeywords</option>
<option value="%20AND%20Molecules.Main_name:">Molecule</option>
</select>
Try this
$("#textQuery").change(function () {
var cur_column_val = $(this).val(); //save the selected value of the first dropdown
$('#textQuery2').html(layout_select_html); //set original dropdown list back
$('#textQuery2').children('option').each(function () { //loop through options
if ($(this).val().indexOf(cur_column_val) != -1) { //do your conditional and if it should not be in the dropdown list
$("#textQuery2 option[value='%20AND%20ToxKeywords:']").remove();
$("#textQuery2 option[value='%20AND%20Molecules.Main_name:']").remove(); //remove option from list
}
});
});
It will remove both options.
})
$("#textQuery").change(function () {
var cur_column_val = $(this).val();
if(cur_column_val=='ToxKeywords' || cur_column_val=='Molecule'){
$('option[value=textQuery2]', $('#textQuery2')).remove();
$('option[value=Molecule]', $('#textQuery2')).remove();
}
});
doen't work like this? let me know :)
I'm trying to get the value of the option which have the attribute "selected" to compare it to the current option selected.
function onChangeOption(opt) {
var update_value = opt.value;
var selectedValue = '???'; // get selected attribute
if (update_value != selectedValue) {
// Do some things
}
}
<select class="form-control" onchange="onChangeOption(this)">
<!-- I wanna got the content of option selected=selected-->
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
// save initial selected value to a variable
var initSelected = $('.form-control option:selected').val();
$('select').on('change', function() {
// check if the selected value is the same as the initial one was
if(this.value == initSelected) {
console.log('same values');
} else {
console.log('not same values');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="form-control">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Just add change event listener.And get the selected value.You can achieve comparision between selected value and changed value by maintaining an array.Like below.
values = []//creates an array
select = document.querySelector('#myselect');
values.unshift(select.value);
//console.log(values);
select.addEventListener('change',function(){
update_value = this.value;
console.log(this.value);
if (update_value != values[0]) {
// alert('Not matched');
console.log('Not matched');
}
else{
//alert('Matched');
console.log('Matched')
}
});
<select class="form-control" id="myselect">
<option selected="selected" value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
I think alexis actually wants something more like this:
function onChangeOption(opt) {
var update_value = opt.value;
var options = document.getElementsByTagName("option");
if (options[0].getAttribute("selected")=="selected") {
var selectedValue = options[0].value;
} else {
var selectedValue = options[1].value;
}
if (update_value != selectedValue) {
// If the selected option's value is not equal to the value of the option with the attribute "selected", then do... (this way, you can change the attribute to any of the options!)
console.log(selectedValue);
}
}
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<option value="2">2</option>
</select>
Comment the result and if you need anything else. Glad to help.
You can always store previously selected values, if you want to access them somehow later on: working example.
HTML:
<select id="mySelect" class="form-control" onchange="onChangeOption(this)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>Previous: <span id="prev"></span></p>
<p>Current: <span id="curr"></span></p>
JS:
var selectElem = document.getElementById("mySelect");
var prev = document.getElementById("prev");
var curr = document.getElementById("curr");
var allEverSelected = [ selectElem.value ];
selectElem.addEventListener("change", function(evt){
allEverSelected.push( this.value );
prev.innerHTML = allEverSelected[allEverSelected.length - 2];
curr.innerHTML = allEverSelected[allEverSelected.length - 1];
});
To access default value, just get the <select> value after DOM loads.
selected attribute on <option> tag exist only to make other than first <option> element inside <select> default option, i.e.:
<select>
<option value="1">1</option>
<option selected value="2">2</option>
</select>
Above select's default value is 2.
I think this is the one what you want. Try it.
function onChangeOption(opt) {
var update_value = opt.value;
console.log(update_value);
var selectedValue;// = '???'; // get selected attribute
// I think this is the one you want
//If you want to select the HTML element,
selectedValue=document.querySelector("option[value='"+update_value+"']");
console.log(selectedValue);
//
if (update_value != selectedValue) {
// Do some things
}
}
//onChangeOption(document.querySelector('form'));
function start(){
while(typeof document.querySelector('form')!=typeof {}){}
onChangeOption(document.querySelector('.form-control'));
}
<body onload="start()">
<select class="form-control" onchange="onChangeOption(this)">
<option selected="selected" value="1">1</option>
<!-- I wanna got this -->
<option value="2">2</option>
</select></body>
So I am trying to create a function that will validate if an option is selected in my Scrolling List. If nothing is selected, and alert will go off, if one is selected, then it passes validation. This is the code I am using:
<select id="topList" name="toppings" size="8" multiple>
<option value="opCream">Whipped Cream</option>
<option value="opFudge">Hot Fudge</option>
<option value="opMarsh">Marshmallow</option>
<option value="opCherry">Cherries</option>
<option value="opChocSprinkles">Chocolate Sprinkles</option>
<option value="opRainSprinkles">Rainbow Sprinkles</option>
<option value="opCheese">Cheesecake</option>
<option value="opOreo">Oreo Crumbles</option>
</select>
function checkScrollList() {
var ddl = document.getElementById("topList");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == false)
{
alert("Please select a sundae topping.");
}
}
Thanks for the suggestions!
You could use the selectedIndex property of the select object, like this:
function checkScrollList() {
var ddl = document.getElementById("topList");
if (ddl.selectedIndex === -1) {
alert("Please select a sundae topping.");
}
}
The selectedIndex property will give the zero-based index of the first selected option, so it is not useful for actually retrieving all the selected options. But it is guaranteed to be -1 when no options are selected.
How do you select a value from a dropdown list, by using the text, instead of the value or the index?
The HTML:
<select name="category_group" id="category_group" sel_id="" >
<option value="0" selected="selected">Kies de rubriek</option>
<option value='1000' style='background-color:#dcdcc3;font-weight:bold;' disabled="disabled" id='cat1000' >
-- VOERTUIGEN --
</option>
<option value='1020' id='cat1020' >
Auto's
</option>
<option value='1080' id='cat1080' >
Auto's: Onderdelen
</option>
<option value='1040' id='cat1040' >
Motoren
</option>
<option value='1140' id='cat1140' >
Motoren: Onderdelen
</option>
</select>
the script:
this.fillSelectors('form[name="formular"]', {
'select[name="category_group"]': 'Motoren'
}, false);
This does not work, but it works using the value of "Motoren" (which is 1140).
How can I make it work, using fillSelectors, with the text?
CasperJS' fill functions only work by using the value. In your case this doesn't work because you're trying to set the shown value not the assigned option value. Though, this can be easily extended:
casper.selectOptionByText = function(selector, textToMatch){
this.evaluate(function(selector, textToMatch){
var select = document.querySelector(selector),
found = false;
Array.prototype.forEach.call(select.children, function(opt, i){
if (!found && opt.innerHTML.indexOf(textToMatch) !== -1) {
select.selectedIndex = i;
found = true;
}
});
}, selector, textToMatch);
};
casper.start(url, function() {
this.selectOptionByText('form[name="formular"] select[name="category_group"]', "Motoren");
}).run();
See this code for a fully working example on the SO contact page.