Show/hide divs based on option selected - javascript

I have a listen of car makes and car models. When a user selects a certain car make, the relevant models appear in the next drop down.
These are some of options in the car make dropdown. It's a WordPress site so it has been assigned an id and value.
<option id="level-0" value="29">Alfa Romeo</option>
<option id="level-0" value="73">Audi</option>
<option id="level-0" value="75">BMW</option>
<option id="level-0" value="31">Citroen</option>
<option id="level-0" value="78">Fiat</option>
Here is are options for the car model dropdown. I have given each option a unique id to link them to their respective car make.
<option id="cars-bmw" value="172">1 Series</option>
<option id="cars-bmw" value="173">2 Series</option>
<option id="cars-bmw" value="106">3 Series</option>
<option id="cars-audi" value="169">A1</option>
<option id="cars-audi" value="170">A3</option>
<option id="cars-audi" value="171">A4</option>
When the page loads, I have already defined the classes .cars-bmw and .cars-audi (etc) as style display: none
I now have javascript to check which option in the first dropdown has been selected. From there it can determine which .car-make to display
Here is a non working fiddle :(
http://jsfiddle.net/HPMkL/

You can't use ids like that since it has to be unique... try an data-* attribute like
<option id="level-0" data-make="cars-audi" value="73">Audi</option>
then in category
<option data-make="cars-audi" value="169">A1</option>
<option data-make="cars-audi" value="170">A3</option>
<option data-make="cars-audi" value="171">A4</option>
then
jQuery(function ($) {
var $cat = $('#cat'),
$models = $cat.find('option').slice(1).remove(),
$test = $('#test');
$test.change(function () {
$models.add($cat.find('option').slice(1).remove());
var $opts = $models.filter('[data-make="' + $(this).find('option:selected').data('make') + '"]');
$cat.append($opts)
}).change()
})
Demo: Fiddle

Try this. I did some modification
$('#test').change(function(){
if(document.getElementById('test').value == "73") {
document.getElementById('cars-audi').style.display="inline";
}});

Related

Clear value from select element when filtering in Angular

I have a basic select element with options that dropdown hooked up to a small set of data which is being filtered using the dropdown. Initially on page load the select element has a value of undefined (according to the console), however after selecting any option it takes on the value of that option.
How can I go back to undefined? Basically I want to be able to select an option in the list that will go back to displaying all of the data. Below is my app on JSBin:
App
add a custom filter function
$scope.filterByGenre = function(item){
if (!$scope.selectedGenre || $scope.selectedGenre == 'All'){
return true;
}
return item.genre && item.genre.indexOf($scope.selectedGenre) != -1;
}
change your <select> to this:
<select ng-model="selectedGenre"
ng-options="choice as choice for (idx, choice) in genres"
name="genre"
class="genre-dropdown">
</select>
change <tr ng-repeat="... filters to this:
<tr ng-repeat="movie in movies | filter:searchBar | filter:filterByGenre | orderBy:sortType:sortReverse">
Online Demo - http://jsbin.com/riyafupexu/1/edit?html,js,output
I'm confused, you are using ng-options but you also provided the static options.
For a quick fix in this case you can remove that ng-options and uncomment that All and remove it's value.
Like:
<select ng-model="selectedGenre"
ng-change="handleSelect()"
name="genre"
class="genre-dropdown">
<option selected="selected" value="">All</option>
<option value="Action">Action</option>
<option value="Adventure">Adventure</option>
<option value="Animation">Animation</option>
<option value="Biography">Biography</option>
<option value="Comedy">Comedy</option>
<option value="Crime">Crime</option>
<option value="Drama">Drama</option>
<option value="Fantasy">Fantasy</option>
<option value="History">History</option>
<option value="Horror">Horror</option>
<option value="Romance">Romance</option>
<option value="Sci-Fi">Sci-Fi</option>
<option value="Western">Western</option>
</select>
You can do it this way:
$scope.selectedGenre = "";//set the model to blank.
$scope.genres = 'All,Action,Adventure,Animation,Biography,Comedy,Crime,Drama,Fantasy,History,Horror,Romance,Sci-Fi,Western';
//create an array after splitting the commas
$scope.genresAry = $scope.genres.split(',');
$scope.genresAry.push("");//push blank into the array.
In HTML use genresAry.
<select ng-model="selectedGenre"
ng-options="choice as choice for (idx, choice) in genresAry"
ng-change="handleSelect()"
name="genre"
class="genre-dropdown">
working code here

count number of variables selected in dropdown using javascript

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.)

Jquery function to split option list into hierarchical select

I have list that looks like this:
<select>
<option value="All" selected="selected">- Any -</option>
<option value="16">Africa</option>
<option value="17">Asia</option>
<option value="56">-China</option>
<option value="57">-Japan</option>
<option value="19">Canada</option>
<option value="20">-Alberta</option>
<option value="21">-British Columbia</option>
<option value="22">-Manitoba</option>
<option value="23">-New Brunswick</option>
<option value="24">-Newfoundland & Labrador</option>
<option value="25">-Northwest Territories</option>
<option value="26">-Nova Scotia</option>
<option value="27">-Nunavut</option>
<option value="28">-Ontario</option>
<option value="29">-Prince Edward Island</option>
<option value="30">-Quebec</option>
<option value="31">-Saskatchewan</option>
<option value="32">-Yukon</option>
<option value="33">Central & South America</option>
<option value="34">Europe</option>
<option value="35">Republic of Ireland</option>
<option value="36">United Arab Emirates</option>
<option value="37">United Kingdom</option>
<option value="38">-England</option>
<option value="39">-Northern Ireland</option>
<option value="40">-Scotland</option>
<option value="41">-Wales</option>
</select>
I can't change the HTML, but need to split the select into two selects by jQuery first the show the top level choices then for example if Canada was chosen show a second drop down with the provinces. This has to be dynamic as the underlying list might change with the time.
I understand that it would be much easier if there would be optgroups but unfortunately this is out of my control. So basicly i need to convert this simple list into hierarchical select in the browser.
You can use below query to split continents and countries select box.
NOTE - put id="select" for main select box.
$(function(){
var continent='';
$('#select option:gt(0)').each(function(){
var value = $(this).val();
//check if option text don't have '-' in it, then take it as
// continent and create a select box with same id
if($(this).text().indexOf("-")==-1 && continent!=value)
{
continent=value;
$('#select').after('<select id="'+continent+'" style="display:none" class="country"></select>');
}
else
{
//add option to the newly created select box
$('#'+continent).append($(this));
}
});
//remove all country select box which are empty
$('.country').filter(function(){
return $(this).children().length ==0;
}).remove();
//bind change event to select box to show / hide country select box
$('#select').change(function(){
$('.country').hide();
$('#'+$(this).val()).show();
});
});
DEMO

Dynamically removing options from select box

I want to dynamically remove options from a select box..
<select name="goal1">
<option value="1">Fat Loss</option>
<option value="2">Competition Prep</option>
<option value="3">Marathon Training</option>
<option value="4">Lean Mass</option>
<option value="5">Triathlon Training</option>
<option value="6">HIIT Training</option>
<option value="7">LISS Training</option>
</select>
<select name="goal2">
<option value="1">Fat Loss</option>
<option value="2">Competition Prep</option>
<option value="3">Marathon Training</option>
<option value="4">Lean Mass</option>
<option value="5">Triathlon Training</option>
<option value="6">HIIT Training</option>
<option value="7">LISS Training</option>
</select>
<select name="goal3">
<option value="1">Fat Loss</option>
<option value="2">Competition Prep</option>
<option value="3">Marathon Training</option>
<option value="4">Lean Mass</option>
<option value="5">Triathlon Training</option>
<option value="6">HIIT Training</option>
<option value="7">LISS Training</option>
</select>
There are, as you can see, three of these select boxes on the page with the exact same options, is there any way to dynamically remove options of the other select boxes based on selections made from the others.
So for example, if in the first of three select boxes, I choose 'Fat Loss', is there any way to remove that option from the other 2 select boxes to avoid duplication in the input?
Then if an option gets unselected, the option needs to reappear in the other select boxes..
Yes there is. Check this JSFiddle. When selecting an item in one of the three dropdown boxes, the options are removed from the other two.
$(document).ready(function () {
$("select").on("change", function () {
// Show all options
$("option").show();
// Get an array of all current selections
var selected = [];
$("select").each(function () {
selected.push($(this).val());
});
// Remove all selected options, except the current showing one, from all lists
$("select").each(function () {
for (var i = 0; i < selected.length; i++) {
if (selected[i] != $(this).val()) {
$(this).find("option[value='" + selected[i] + "']").hide();
}
}
});
});
});
Edit: I've updated the fiddle with a new version which lets options reappear when they get unselected in other lists. Not sure if it's the best way of doing this though...

Show Hide select options based on previous selection dropdown

Thanks for reading my question... ;-)
I'm building a Wordpress site that uses Custom Posts and Custom Fields to show a vehicle inventory. I would like the visitor to be able to filter the posts by Taxonomies...
The plugin I use for drilling the available Taxonomies (Query Multiple Taxonomies) outputs all options it can find for that particular Taxonomy into a dropdown list.
To prevent the dropdown list (i.e. Model) to become too long, I would like to show only those options that are based on the previous selection.
So when the visitor selects Vehicle = Cars, the dropdown for Manufacturer should only show the car manufacturers.
When the visitor selects a manufacturer, i.e. Ford, the next dropdown for selecting a model should only show the models available for the previous selected manufacturer, in this case Ford...
The labels and level-0 values don't change but when I add or change a manufacturer or model, the level-1 and/or level-2 changes.
Not that important but, if possible, it would also be nice to strip everything not needed to show up in the "filtered" dropdown. In case of the Manufacturer dropdown, level-0 and all the spaces are not needed.
In case of the Model dropdown, level-0, level1 and all the spaces are not needed after selection.
Here's a sample how the HTML-code, generated by the plugin, looks like:
<label for="qmt-vehicle">Vehicle:</label>
<select id="qmt-vehicle" name="vehicle">
<option></option>
<option class="level-0" value="cars" >Cars</option>
<option class="level-0" value="motorcycles" >Motorcycles</option>
</select>
<label for="qmt-manufacturer">Manufacturer:</label>
<select id="qmt-manufacturer" name="manufacturer">
<option></option>
<option class="level-0" value="cars" >Cars</option>
<option class="level-1" value="ford" > Ford</option>
<option class="level-1" value="chevrolet" > Chevrolet</option>
<option class="level-0" value="motorcycles" >Motorcycles</option>
<option class="level-1" value="honda" > Honda</option>
<option class="level-1" value="yamaha" > Yamaha</option>
</select>
<label for="qmt-model">Model:</label>
<select id="qmt-model" name="model">
<option></option>
<option class="level-0" value="cars" >Cars</option>
<option class="level-1" value="ford" > Ford</option>
<option class="level-2" value="model-1-ford" > Model 1</option>
<option class="level-2" value="model-2-ford" > Model 2</option>
<option class="level-2" value="model-3-ford" > Model 3</option>
<option class="level-1" value="chevrolet" > Chevrolet</option>
<option class="level-2" value="model-1-chevrolet" > Model 1</option>
<option class="level-2" value="model-2-chevrolet" > Model 2</option>
<option class="level-2" value="model-3-chevrolet" > Model 3</option>
<option class="level-0" value="motoren" >Motorcycles</option>
<option class="level-1" value="honda" > Honda</option>
<option class="level-2" value="model-1-honda" > Model 1</option>
<option class="level-2" value="model-2-honda" > Model 2</option>
<option class="level-2" value="model-3-honda" > Model 3</option>
<option class="level-1" value="yamaha" > Yamaha</option>
<option class="level-2" value="model-1-yamaha" > Model 1</option>
<option class="level-2" value="model-2-yamaha" > Model 2</option>
<option class="level-2" value="model-3-yamaha" > Model 3</option>
</select>
I can do some simple things with Javascript but this is not simple to me, sorry... ;-)
Can someone please help me to figure out how to do this in Javascript/JQuery?
Cross browser would be great!
* EDIT *
The HTML code shows the code send to the browser. Because I cannot modify the plugin that much, I'd like to "manipulate" this code to make it work the way I want to... ;-)
The only fixed things are: Labels for the dropdowns and the Values for all the Class="level-0" elements.
So "Cars" and "Motorcycles" will always stay and never change. BUT from there everything is flexible to change. I.e. when there are no Posts for Chevy's to display, Chevy will not be in the generated HTML. So the plugin only shows dropdown options for the items that are realy there and can be found.
So when there's no Ford available at all, Ford will not be in the dropdown...
I rather not make a predefined list of Manufacurers and their Models.
subscribe to your select elements' onchange events: http://www.w3schools.com/jsref/event_onchange.asp. In the event handler, read the currently selected value and repopulate the other elements accordingly.
I would suggest you hold the data in javascript so you only need to show the necessary options for each model without having to hide some..
I put this on jsfiddle but the site keeps breaking.
The code below was tested and works though.
Ok Works now:
<script type="text/javascript">
var vehicles = {"Cars": {
"Ford" : [ "Fiesta", "Focus", "Fusion"],
"Chevy": [ "Malibu", "Corvette", "Tahoe"],
},
"Motorcycles": {
"Honda": ["model 1", "model 2", "model 3"],
"Yamaha": ["model 1", "model 2", "model 3", "model 4"]
}
};
$(document).ready(function() {
var $vehiclesList = $("#qmt-vehicle");
var $manufList = $("#qmt-manufacturer");
var $modelList = $("#qmt-model");
var selectedType = null
var selectedManuf = null;
$.each(vehicles, function(key, vehicle) {
$vehiclesList.append($("<option/>", {value:key,text:key}));
});
$vehiclesList.bind("change", function() {
selectedType = $(this).val();
if (selectedType && vehicles[selectedType]) {
var manufacturers = vehicles[selectedType];
$("#qmt-manufacturer option").not(":first").remove();
$("#qmt-model option").not(":first").remove();
$.each(manufacturers, function(key, manufacturer) {
$manufList.append($("<option/>", { value: key, text: key}));
});
}
});
$manufList.bind("change", function() {
var selectedManuf = $(this).val();
$("#qmt-model option").not(":first").remove();
if (selectedManuf && vehicles[selectedType] && vehicles[selectedType][selectedManuf]) {
var models = vehicles[selectedType][selectedManuf];
$.each(models, function(key, model) {
$modelList.append($("<option/>", { value: model, text: model}));
});
}
});
});
</script>
Then in your page you'd have
<label for="qmt-vehicle">Vehicle:</label>
<select id="qmt-vehicle" name="vehicle">
<option></option>
</select>
<label for="qmt-manufacturer">Manufacturer:</label>
<select id="qmt-manufacturer" name="manufacturer">
<option></option>
</select>
<label for="qmt-model">Model:</label>
<select id="qmt-model" name="model">
<option></option>
</select>

Categories