Disable a select element option based on a class - javascript

Hey guys just been told that hide cannot be used cross browser for select element options.
So I am wondering how I can use disable for the following issue I am having.
This example is simplified, the actual code contains PHP loops and MySQL to display the options and content.
Okay so first of all I have these two select elements:
<select class="form-control select-box">
<option value="make-any">Make (Any)</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<select class="form-control select-box-model">
<option value="make-any">Make (Any)</option>
<option value="C220">C220</option>
<option value="X1">X1</option>
<option value="X5">X5</option>
<option value="XC90">XC90</option>
</select>
I then have these list:
<div class="makes BMW X1">
<ul>
<li>BMW</li>
<li>X1</li>
</ul>
</div>
<div class="makes VOLVO XC90">
<ul>
<li>VOLVO</li>
<li>XC90</li>
</ul>
</div>
<div class="makes MERCEDES C220">
<ul>
<li>MERCEDES</li>
<li>C220</li>
</ul>
</div>
<div class="makes BMW X5">
<ul>
<li>BMW</li>
<li>X1</li>
</ul>
</div>
I am currently using this jQuery to hide the div with the class of 'makes' if the selected option doesn't match the div's class so for example 'BMW':
<script>
$(document).ready(function(){
$('.form-control').change(function(){
var make = $(this).val();
if(make != 'make-any'){
$('.makes').hide();
$('.'+make).show();
} else {
$('.makes').show();
}
});
});</script>
So as you can see I have a bit of a problem because the second select element with the class of "select-box-model" contains all of the models, I'd like to disable the options that aren't associated with the first select element option that has been selected.
For example the list containers contain the classes for the 'Make' and 'Model' of the each vehicle:
<div class="makes BMW X5">
So how can I disable the options that are not associated with that 'Make', for example if the user selects BMW for the first element I'd only like the 'Models' that are associated with the 'Make'.
Any examples would be great, thanks.

Well, I am not completely certain that I have understood your question.
But I am assuming that you mean that if you select a car brand from select one (form control) the available models should be enabled in select two select-box-model. Once selecting the model, the accurate div needs to be shown?
If that is what you're trying to do your markup is not the best structure to achieve that.
Never the less, I made an example using your mark up:
jQuery:
$('.select-box-model').prop('disabled',true);
$('.form-control').on('change',function(){
$('.select-box-model').prop('disabled',false);
if($(this).val() != 'make-any'){
$('.makes').hide();
//check if the models drop down is used
if($(this).hasClass('select-box-model')){
//get selected value
var value = $(this).val();
$('.'+ value).show();
return false;
}
//get selected value
var carBrand = $(this).val();
$('.select-box-model option').prop('disabled',true);
$('.'+ carBrand).find('li').each(function(){
if($.trim(carBrand) != $.trim($(this).text())){
$('.select-box-model option[value="'+ $(this).text() +'"]').attr("disabled", false);
}
});
}
});
Here's a fiddle of that: http://jsfiddle.net/z59v56ec/
A neater solution to achieve this is using ajax to populate the models of the car brand.
But if you really want to do it your way, then the following logic is easier.
Select one holds value of car brand
Select two holds value of car brand and the text is the model
Select one will enable the options in select two with the value of that car brand
On select a model in select two the accurate divs would be shown according to the option text.
On a sidenote, be careful with your references. VOLVO is not the same as Volvo.
Just in case I completely missed the point - sorry! :)

First, you are far better off creating multiple selects and toggling their display based upon your first select's selectedvalue. Then, you create multiple divs and toggle their display based on your second select's selectedvalue. That said, if you really want to attack this "dynamically", you're better off having two selects - and one unordered list - and clearing their contents and rewriting the html as you go:
<select class="form-control select-box" id="selectMake">
<option value="make-any">Make (Any)</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>
<select class="form-control select-box-model" id="selectModel">
</select>
<ul id="ulCars">
</ul>
$("#selectMake").change(function(){
$("#selectModel").empty();
$("#ulCars").empty();
switch ($(this).val()){
case "BMW":
$("#selectModel").append("<option>X1</option>").val("X1");
$("#ulCars").append("<li>X1</li>");
break;
}
});
etc. etc., but you can easily clear lists and dropdowns - and then repopulate them. But like I said, I'd go with multiple divs and toggling their display.

Related

How do I make a toggle switch trigger a select dropdown to randomize its option value?

I'm setting up a page for a character generator, and I'm giving users the option to either randomize traits or enter their own. I have the "choice vs random" options set up as toggle switches for each trait category, and then if they want to choose their own, I have drop-down select menus for each category with all the traits listed.
Here's my HTML for the switches:
<div class="switch">
<p>Class</p>
<label>
My Choice
<input type="checkbox" id="class-choice">
<span class="lever red darken-4"></span>
Random
</label>
</div>
Here's my HTML for the corresponding select menu:
<div class="input-field col s6">
<select id="classMenu" name="class">
<option value="barbarian">Barbarian</option>
<option value="bard">Bard</option>
<option value="cleric">Cleric</option>
<option value="druid">Druid</option>
<option value="fighter">Fighter</option>
<option value="monk">Monk</option>
<option value="paladin">Paladin</option>
<option value="ranger">Ranger</option>
<option value="rogue">Rogue</option>
<option value="sorcerer">Sorcerer</option>
<option value="warlock">Warlock</option>
<option value="wizard">Wizard</option>
</select>
<label for="class">Class</label>
</div>
What I want to have happen is that every time they click the toggle switch to "random," the corresponding drop-down menu will display a randomized option from the list. I have all the option names saved as an array in my JavaScript:
var charClasses = ["barbarian", "bard", "cleric", "druid", "fighter", "monk", "paladin", "ranger", "rogue", "sorcerer", "warlock", "wizard"];
I know I need to use some sort of event listener and a math randomizing function and then something to display that option value, but I guess I'm confused about how to actually do that. And then I think I'll have to use a $('#save-btn').on("click", ... to save it to localStorage as well. I just started learning JS and it's not really intuitive for me yet, so any guidance would be appreciated.
To get a random item of array use:
var item = charClasses[Math.floor(Math.random()*charClasses.length)];
To select the item use:
$('#classMenu').val("item ");
You can use a button event like this:
$('#btnRandom').click(function() {
var item = charClasses[Math.floor(Math.random()*charClasses.length)];
$('#classMenu').val(item);
});
The code select a random value from array and put in variable item. Next select the item in select field.

How to show and hide multiple html selects with dynamic variable properly?

I have a select with options, let's call it Car Brands:
<select id="car-brands">
<option value="noselection">Car Brand</option>
<option value="toyota">TOYOTA</option>
<option value="lexus">LEXUS</option>
</select>
And I have another 2 selects, let's call them car models:
<select id="car-models-toyota" style="display:none;">
<option value="noselection">Car Model</option>
<option value="toyota">AVENSIS</option>
<option value="lexus">CAMRY</option>
</select>
<select id="car-models-lexus" style="display:none;">
<option value="noselection">Car Model</option>
<option value="toyota">AVENSIS</option>
<option value="lexus">CAMRY</option>
</select>
I hide them, so when user selecting TOYOTA or LEXUS in first select, Car Models will show up by their theme:
$('#car-brands').change(function() {
const brand = $(this).val();
$(`#car-models-${brand}`).show();
});
And it's working, car models selects show up, but I can't understand how can I hide another with this dynamic variable?
I mean I select TOYOTA and #car-models-toyota select shows up, select LEXUS and #car-models-lexus select shows up, but when it shows up toyota select should be hidden.
Can you help me, please?
You can do this by making all select elements hidden first in each first select, change event, and then shown the desired one by your provided code. So all you have to do is to select all selects (except the brand select) with $('select').not('#car-brands') then use hide() to make all of them hidden.
So this should be something like this:
$('#car-brands').change(function() {
const brand = $(this).val();
$('select').not('#car-brands').hide();
$(`#car-models-${brand}`).show();
});

Have dropdown menus use value of previous dropdown

I have a "master dropdown menu" that contains four options (English, Spanish, Russian, Other) as the question asks their primary language.
Below this master dropdown menu contains other questions that asks similar questions and contain the same options (English, Spanish, Russian, Other).
I am wondering if it's possible to have the other dropdown menu options have the same value selected based on the 'master dropdown menu' option. So if John Smith chooses English in the master dropdown menu, the other questions will automatically have English selected in the other dropdown menus, while also allowing John to change an Answer - he may choose Spanish for question 3. I'm hoping the solution uses JavaScript or jQuery, as PHP won't be an option.
<label>What is your primary language?</label>
<select name="question1">
<option></option>
<option value="english">English</option>
<option value="spanish">Spanish</option>
<option value="russian">Russian</option>
<option value="other">Other</option>
</select>
<label>Language your spouse speaks?</label>
<select name="question2">
<option></option>
<option value="english">English</option>
<option value="spanish">Spanish</option>
<option value="russian">Russian</option>
<option value="other">Other</option>
</select>
<label>Language your children speak?</label>
<select name="question3">
<option></option>
<option value="english">English</option>
<option value="spanish">Spanish</option>
<option value="russian">Russian</option>
<option value="other">Other</option>
</select>
When selecting the value in the master dropdown menu you can set the value to the other dropdowns via JavaScript.
document.querySelector('select[name="question1"]').addEventListener('change', function(event) {
document.querySelector('select[name="question2"]').value = event.target.value;
document.querySelector('select[name="question3"]').value = event.target.value;
});
really simple solution but should work
JSFiddle
You can do this in jQuery as follows, using nextAll() to populate the other select items:
$('select').on('change', function() {
$(this).nextAll('select').val($(this).val());
});
(Note that you probably want to add a class to your selects as the above will operate on ALL select elements on the page).
Below you are adding an EventListener to to trigger when the first item is changed and assigning its value to rest of the selectors. Please update var firstDD and reminingDD valriables based on your requirement. Or better use specific IDs for each seletor so that it would be easy to understand.
$( document ).ready(function() {
var firstDD = $("select:first-child");
var reminingDD = $("select:not(:first-child)");
console.log(reminingDD);
firstDD.change(function () {
$(reminingDD).val($(firstDD).val());
});
});

How to hide and show select options

I'm very very new to jQuery. I Googled a lot before I'm asking, though it looks silly but for me its complicated.
I have a simple <select> list which has around 4 values like this image shown below.
Now at runtime, I want to hide the options and show based on index or value names in jQuery. How can I achieve this?.
My drop down box has a div region and simple select option with set of values. Please provide me a simple example.
Sample code
<Div ID = "abcd">
<select>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
In this how to hide Volvo/Opel at run time?... like i want to show and hide these options dynamically.
Like Ex: When a button is pressed i want to hide Volvo. Similarly if another button is pressed i want to display Volvo back.
if you would like to hide the whole select you should give your select or the div containing your select an id and then you can do like :
<div id="mySelect" >your select tag here </div>
$('mySelect').show(); // or $('mySelect').hide();
http://api.jquery.com/hide/
http://api.jquery.com/show/
if you would like to hide the option you can do like below :
$("#edit-field-service-sub-cat-value option[value=" + title + "]").hide();
To be more specific to your code :
<div id="abcd">
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
</div>
title = 'volvo';
$("#mySelect option[value=" + title + "]").hide();
like in this post :
Hide options in a select list using jQuery
or remove it :
JQuery: Hide options of select according to option value

What's the easiest way to implement this multi-level drop-down list?

I want to implement the following system of drop down lists:
I'm aware that drop down lists are implemented using <select> statements. However, I'm not sure if I need to use Javascript commands to handle my requirements listed in the picture. How would you suggest to handle this?
Thanks in advance!
You will have all three drop down on the page but dropdown 2 and 3 will be hidden. On change of first drop down you will have to check the value of first drop down and show second and third dropdown. Demo is available here
In html we define three dropdowns first is visible and second and third are hidden. We will show the hidden dropdown when 3 is selected from first dropdown
<select id="sel1" >
<option > 1 </option>
<option > 2 </option>
<option > 3 </option>
</select>
<select id="sel2" style="display:none" >
<option > 1 </option>
<option > 2 </option>
<option > 3 </option>
</select>
<select id="sel3" style="display:none" >
<option > 1 </option>
<option > 2 </option>
<option > 3 </option>
</select>
​In javascript we have show the hidden dropdowns when 3 is selected from first drop down
$('#sel1').change(function ()
{
if($(this).val() == "3")
{
$('#sel2').show();
$('#sel3').show();
}
}
);
​
I think if you want to only allow the user to select second and third options based on the selection event in the first option, you are probably going to need JavaScript to do this. If you have to cater for users with JavaScript disabled you will have to have something like an Update button that posts to the server where server-side code in ASP.Net / PHP / Django / Node.js or something of that sort, builds the second and third options and returns them to the user.
You can put the second and third dropdowns inside divs and keep them hidden initially. Once the value of first is selected, make the second visible and so on. You can easily do this with javascript. For eg:
function onLoad() {
document.getElementById("dayDropDownDiv").style.visibility="hidden";
}
and create the select inside the div in the body as:
<div id="dayDropDownDiv">
<label for="select-Day" class="select">Day:</label>
<select name="select-day" id="dayDropDown" onchange="dayChange(this)"></select>
</div>
You can also create the dropdowns programmatically in javascript. You'll have to add the <option>s to the <select>'s innerHTML as:
function addValues() {
var dayOptionsList = "";
for(loopIndex=1;loopIndex<=31;loopIndex++){
dayOptionsList = dayOptionsList+"<option>"+loopIndex+"</option>";//<-this will create an options list for days
var daySelector = document.getElementById("dayDropDown");
daySelector.innerHTML = dayOptionsList;//done
}
Finally, make them visible when the first <select>'s particular option is selected:
function firstValueSelected( resultsObj){
var val = obj.options[obj.selectedIndex].text;//<- text of selected option
if(val=="f")
document.getElementById("dayDropDownDiv").style.visibility="visible";
}

Categories