Show different options depending on what is selected - javascript

I want to make it so that if United States is selected from the drop down list State list shows, if Canada is selected then the Province list shows. How can this be done?
<select name="country">
<option value="US">United States</option>
<option value="CA">Canada</option>
</select>
<select name="state">
<option value="1">State 1</option>
<option value="2">State 2</option>
<option value="3">State 3</option>
</select>
<select name="province">
<option value="1">Province 1</option>
<option value="2">Province 2</option>
<option value="3">Province 3</option>
</select>

If you're using JQuery, i'd recommend looking into the "change" event, combined with "show" and "hide" functions.
I won't write all the code for you, but something to the effect of;
$("#country").change(function()
{
// get value of "country"
// if it's 'US';
$("#state").show();
// otherwise
$("#province").show();
});
It's also generally better to use id's instead of the "name" attribute, on your elements. That enables very quick lookup of elements, and that's the only way the hash selector will work. ("#country"). If you need to use the "name" attribute, your selector could look like
$("select[name=\"country\"]")

You can do:
$('select[name="country"]').change(function() {
var val = this.value;
if(val == "US") {
$('select[name="state"]').show().siblings('select[name="province"]').hide();
} else {
$('select[name="province"]').show().siblings('select[name="state"]').hide();
}
}).change();
Fiddle Demo

You can do this in plain javascript by hiding the <select>'s using display:none and then exposing them using an if statement in the onChange for the primary <select>.
<select name="country" onchange="if (this.value == 'CA') { document.getElementById('state').style.display=''; } else { document.getElementById('province').style.display=''; };">
Here's a working example: http://jsfiddle.net/u7NpP/

Related

How to use getElementByID in JavaScript to connect to my HTML drop down box?

I have a drop-down box in HTML showing three options. I am also using javaScript and want to use the getElementById tool to connect the two. However, I only have one ID for the drop-down box. How does javascript recognize that I have three different options?
There's actually a demo on w3schools.com showing exactly what you're asking. To get the number of options, you could do something like
document.getElementById("mySelect").options.length
Here is an example of how to retrieve the value of a dropdown: https://jsfiddle.net/ykcwgnm8/
You use getElementBy* functions to get the element, however value attribute denotes which item is currently selected.
HTML:
<select id="dropdown">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
JS:
function onChangeHandler(e)
{
alert("you have selected item with value "+this.value);
}
document.getElementById("dropdown").addEventListener("change", onChangeHandler);
You can listen for change like this
var list = document.getElementById("mySelect")
list.addEventListener('change', function(e){
console.log(e.target.selectedIndex)
console.log(e.target.options[e.target.selectedIndex].text)
})
<select id="mySelect">
<option>Apple</option>
<option>Orange</option>
<option>Pineapple</option>
<option>Banana</option>
</select>
You can do something like this, here is an example:-
html
<select id="selectBox">
<option value="1">option 1</option>
<option value="2" selected="selected">option 2</option>
<option value="3">option 3</option>
</select>
js
var e = document.getElementById("selectBox");
var selectedValue = e.options[e.selectedIndex].value;
// this will give selectedValue as 2
Hope you find this useful!!

JQuery how to difference between a select option with an option selected attribute and a select without a selected value

I'm populating multiple select with a webservice.
This web service is returning the selected value.
Well, at the moment to render them, I have 2 different select
<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>
<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>
Well, the first select hasn't any selected attribute and the second one has it.
When I execute:
$("select1").find("option:selected").val(); //Returns 1
$("select2").find("option:selected").val(); //Returns A
How I can identify when the select has an option really selected?
Instead of using :selected which looks for the selected state, you can look for [selected], which will check for the selected attribute.
var $selectedOption = $("#select1 option[selected]");
if ($selectedOption.length) {
//option selected
console.log(selectedOption.val() + " selected.");
} else {
//no option selected
console.log("Nothing selected.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='select1'>
<option value='1'>Option 1</option>
<option value='3'>Option 3</option>
</select>
<select id='select2'>
<option selected="selected" value='A'>Option A</option>
<option value='B'>Option B</option>
</select>
You can use the has() jQuery method to find the select that has an option with the selected attribute.
$("select").has("option[selected]")
$("#select1").has("option[selected]").val() // undefined
$("#select2").has("option[selected]").val() // "A"

Show Hide select options based on previous selection dropdown in Jquery or Javascript

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.
I can do some simple things with JavaScript but this is not simple to me, sorry... ;-)
I searched for tips and examples and tried to make it work but no luck.
Can someone please help me to figure out how to do this in jQuery?
Here is the code,
<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>
You need to use javascript, or jquery.
Here is how I do it.
Get the class that is selected:
var levelClass = $('#qmt-manufacturer').find('option:selected').attr('class');
Then use the level class to hide or show
$('#qmt-model option').each(function () {
var self = $(this);
self.hide();
if (self.hasClass(levelClass)) {
self.show();
}
});
Edit:
to clarify how to use this:
it uses a slightly altered version of the code
$(function(){
$("#qmt-vehicle").on("change",function(){
var levelClass = $('#qmt-vehicle').find('option:selected').attr('class');
console.log(levelClass);
$('#qmt-manufacturer option').each(function () {
var self = $(this);
if (self.hasClass(levelClass) || typeof(levelClass) == "undefined") {
self.show();
} else {
self.hide();
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="qmt-vehicle">Vehicle:</label>
<select id="qmt-vehicle" name="vehicle">
<option></option>
<option class="car" value="cars">Cars</option>
<option class="motorcycle" value="motorcycles">Motorcycles</option>
</select>
<label for="qmt-manufacturer">Manufacturer:</label>
<select id="qmt-manufacturer" name="manufacturer">
<option></option>
<option class="car" value="cars">Cars</option>
<option class="car" value="ford"> Ford</option>
<option class="car" value="chevrolet"> Chevrolet</option>
<option class="motorcycle" value="motorcycles">Motorcycles</option>
<option class="motorcycle" value="honda"> Honda</option>
<option class="motorcycle" value="yamaha"> Yamaha</option>
</select>
There is another way to achieve this --- Check this Fiddle example: Fiddle
You can learn from this example and add according logic which you need for the third option box.
jQuery Code:
$('#qmt-vehicle').on('change', function () {
//alert(this.value); // or $(this).val()
if (this.value == 'cars') {
$("#qmt-manufacturer").html(
"<option class=\"level-1\" value=\"ford\"> Ford</option><option class=\"level-1\" value=\"chevrolet\"> Chevrolet</option>");
} else {
$("#qmt-manufacturer").html(
"<option class=\"level-1\" value=\"honda\"> Honda</option><option class=\"level-1\" value=\"yamaha\"> Yamaha</option>");
}
});
A Javascript might help you...
You can add an "onchange" event (in Javascript) in your "select" component. Also, add an ID for the labels.
Example:
<label for="qmt-manufacturer" id="lblManufacturer">
<select id="qmt-manufacturer" name="manufacturer"
onchange="changeManufacturer(this.value);">
Using a script tag, build your method in javascript as following:
<script type="text/javascript">
function changeManufacturer(manufacturerValue){
switch(manufacturerValue){
case ford:
document.getElementById('lblManufacturer').innerHTML = 'FORD';
break;
case chevrolet:
document.getElementById('lblManufacturer').innerHTML = 'Chevrolet';
break;
}
// And so on for other values...
}
</script>
this code above changes the Label Text running time, implement it to make changes in your second dropdown (Model)
Hope it helps you.

JQuery - how to select dropdown item based on value

I want set a dropdown(select) to be change based on the value of the entries.
I have
<select id="mySelect">
<option value="ps">Please Select</option>
<option value="ab">Fred</option>
<option value="fg">George</option>
<option value="ac">Dave</option>
</select>
And I know that I want to change the dropdown so that the option with the value of "fg" is selected. How can I do this with JQuery?
You should use
$('#dropdownid').val('selectedvalue');
Here's an example:
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
$('#yourdropddownid').val('fg');
Optionally,
$('select>option:eq(3)').attr('selected', true);
where 3 is the index of the option you want.
Live Demo
$('#mySelect').val('fg');...........
$('#mySelect').val('ab').change();
// or
$('#mySelect').val('ab').trigger("change");
You can use this jQuery code which I find it eaiser to use:
$('#your_id [value=3]').attr('selected', 'true');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="your_id" name="name" class="form-control input-md">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
<option value="3">Option #3</option>
<option value="4">Option #4</option>
<option value="5">Option #5</option>
<option value="6">Option #6</option>
<option value="7">Option #7</option>
</select>
You can simply use:
$('#select_id').val('fg')
In your case $("#mySelect").val("fg") :)
May be too late to answer, but at least some one will get help.
You can try two options:
This is the result when you want to assign based on index value, where '0' is Index.
$('#mySelect').prop('selectedIndex', 0);
don't use 'attr' since it is deprecated with latest jquery.
When you want to select based on option value then choose this :
$('#mySelect').val('fg');
where 'fg' is the option value
$('#dropdownid').val('selectedvalue');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id='dropdownid'>
<option value=''>- Please choose -</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='selectedvalue'>There we go!</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
This code worked for me:
$(function() {
$('[id=mycolors] option').filter(function() {
return ($(this).text() == 'Green'); //To select Green
}).prop('selected', true);
});
With this HTML select list:
<select id="mycolors">
<option value="1">Red</option>
<option value="2">Green</option>
<option value="3">Blue</option>
</select>
I have a different situation, where the drop down list values are already hard coded. There are only 12 districts so the jQuery Autocomplete UI control isn't populated by code.
The solution is much easier. Because I had to wade through other posts where it was assumed the control was being dynamically loaded, wasn't finding what I needed and then finally figured it out.
So where you have HTML as below, setting the selected index is set like this, note the -input part, which is in addition to the drop down id:
$('#project-locationSearch-dist-input').val('1');
<label id="lblDistDDL" for="project-locationSearch-input-dist" title="Select a district to populate SPNs and PIDs or enter a known SPN or PID." class="control-label">District</label>
<select id="project-locationSearch-dist" data-tabindex="1">
<option id="optDistrictOne" value="01">1</option>
<option id="optDistrictTwo" value="02">2</option>
<option id="optDistrictThree" value="03">3</option>
<option id="optDistrictFour" value="04">4</option>
<option id="optDistrictFive" value="05">5</option>
<option id="optDistrictSix" value="06">6</option>
<option id="optDistrictSeven" value="07">7</option>
<option id="optDistrictEight" value="08">8</option>
<option id="optDistrictNine" value="09">9</option>
<option id="optDistrictTen" value="10">10</option>
<option id="optDistrictEleven" value="11">11</option>
<option id="optDistrictTwelve" value="12">12</option>
</select>
Something else figured out about the Autocomplete control is how to properly disable/empty it. We have 3 controls working together, 2 of them mutually exclusive:
//SPN
spnDDL.combobox({
select: function (event, ui) {
var spnVal = spnDDL.val();
//fire search event
$('#project-locationSearch-pid-input').val('');
$('#project-locationSearch-pid-input').prop('disabled', true);
pidDDL.empty(); //empty the pid list
}
});
//get the labels so we have their tool tips to hand.
//this way we don't set id values on each label
spnDDL.siblings('label').tooltip();
//PID
pidDDL.combobox({
select: function (event, ui) {
var pidVal = pidDDL.val();
//fire search event
$('#project-locationSearch-spn-input').val('');
$('#project-locationSearch-spn-input').prop('disabled', true);
spnDDL.empty(); //empty the spn list
}
});
Some of this is beyond the scope of the post and I don't know where to put it exactly. Since this is very helpful and took some time to figure out, it's being shared.
Und Also ... to enable a control like this, it's (disabled, false) and NOT (enabled, true) -- that also took a bit of time to figure out. :)
The only other thing to note, much in addition to the post, is:
/*
Note, when working with the jQuery Autocomplete UI control,
the xxx-input control is a text input created at the time a selection
from the drop down is picked. Thus, it's created at that point in time
and its value must be picked fresh. Can't be put into a var and re-used
like the drop down list part of the UI control. So you get spnDDL.empty()
where spnDDL is a var created like var spnDDL = $('#spnDDL); But you can't
do this with the input part of the control. Winded explanation, yes. That's how
I have to do my notes or 6 months from now I won't know what a short hand note means
at all. :)
*/
//district
$('#project-locationSearch-dist').combobox({
select: function (event, ui) {
//enable spn and pid drop downs
$('#project-locationSearch-pid-input').prop('disabled', false);
$('#project-locationSearch-spn-input').prop('disabled', false);
//clear them of old values
pidDDL.empty();
spnDDL.empty();
//get new values
GetSPNsByDistrict(districtDDL.val());
GetPIDsByDistrict(districtDDL.val());
}
});
All shared because it took too long to learn these things on the fly. Hope this is helpful.
You can select dropdown option value by name
// deom
jQuery("#option_id").find("option:contains('Monday')").each(function()
{
if( jQuery(this).text() == 'Monday' )
{
jQuery(this).attr("selected","selected");
}
});
$('select#myselect option[value="ab"]')
either can be used to get the selected option value
$('#dropdownID').on('change', function () {
var dropdownselected=$("#dropdownID option:selected").val();
});
or
$('#dropdownID').on('change', function () {
var dropdownselected=this.selectedOptions[0].value;
});

Using JQuery "select option:first-child" just for an element with a given id?

This code looks at if dropdownlist with 'townid' has an option of Central and then puts Central after the first option at all dropdownlists.
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('select option:first-child');
}
My problem is that:
How can I add it just after dropdownlist that has id of townid? I mean something like:
var central = $('#townid option:contains("Central")');
if(central){
central.insertAfter('#townid select option:first-child');
}
For example:
<select id=townid>
<option value="5000">AL</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5204">Central</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
After that process they should be seem like:
<select id=townid>
<option value="5000">AL</option>
<option value="5204">Central</option>
<option value="5001">NY</option>
<option value="5002">LA</option>
<option value="5003">NY</option>
<option value="5024">FA</option>
</select>
<select id="someid">
<option value="3002">Brooklyn</option>
<option value="6001">Manhattan</option>
</select>
How can I add it just after dropdownlist that has id of townid?
Okay, I’m gonna assume your HTML looks something like this:
<select id="townid">
<option>
…
</option>
</select>
In that case, you could use:
$('#townid option:contains("Central")').appendTo('#townid option');
If there are multiple option elements inside #townid and you only want to select the first, just change the selector:
$('#townid option:contains("Central")').appendTo('#townid option:first');
In your example, don’t use if (central), use if (central.length) instead.
You just messed up the selector, because #townid IS the select tag.
var central = $('#townid option:contains("Central")');
if(central.length === 1){
central.insertAfter('#townid option:first-child');
}

Categories

Resources