Javascript onchange event not working in my code - javascript

what is wrong with this code? Why is my onchange event not working? I have tried a lot already and it's making me nuts. Please help?
<!DOCTYPE html>
<html>
<head>
<script type=text/javascript>
function populate(s1,s2){
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
else if(s1.value=="Dodge"){
var optionArray=["|", "avanger|Avanger", "challenger|Challenger",
"charger|Charger"];
}
else if(s1.value=="Ford"){
var optionArray=["|", "mustang|Mustang", "shelby|Shelby"];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHtml=pair[1];
s2.options.add(newOption);
}
}
</script>
</head>
<body>
<h2>Choose Your Car</h2>
<hr />
Choose Car Make:
<select id="slct1" name="slct1" onchange="populate(this.id, 'slct2')">
<option value="">Select</option>
<option value="Chevy">Chevy</option>
<option value="Dodge">Dodge</option>
<option value="Ford">Ford</option>
</select>
<hr />
Choose Car Model:
<select id="slct2" name="slct2"></select>
<hr />
</body>
</html>
Anyone, please point out to me where is the exact problem...Let me try running it accordingly

Two changes. Change innerHtml to innerHTML and assign an = sign in
if(s1.value == "Chevy"){
var optionArray ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
correct the above to
if(s1.value == "Chevy"){
var optionArray = ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
JSFIDDLE

Try the following:
<select id="slct1" name="slct1" onchange="populate(this, 'slct2')">
js:
populate = function(s1,s2) {
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if(s1.value == "Chevy"){
var optionArray = ["|", "camaro|Camaro", "corvette|Corvette",
"impala|Impala"];
}
else if(s1.value=="Dodge"){
var optionArray=["|", "avanger|Avanger", "challenger|Challenger",
"charger|Charger"];
}
else if(s1.value=="Ford"){
var optionArray=["|", "mustang|Mustang", "shelby|Shelby"];
}
for(var option in optionArray){
var pair=optionArray[option].split("|");
var newOption=document.createElement("option");
newOption.value=pair[0];
newOption.innerHTML=pair[1];
s2.options.add(newOption);
}
}
demo:
https://jsfiddle.net/xkyffr4h/1/

Related

JavaScript onchange event for dynamic dropdown in HTML

I am not sure if I am wording this correctly. I have a dropdown menu, that when an option is selected, the second dropdown pops in and has options for the selected value. This all works great, but now I am trying to give a button to add more dropdowns in JavaScript. The first works, but I cannot get the second value to show.
HTML code:
<table class="table-container">
<tbody><tr><td>
<select class="custom-select" id="mediaSel" name="mediaSel" onchange="dropDownSelect(this.id, 'mediaSel2')">
<option value="">--Select--</option>
<option value="Illustration" name="Illustration">Illustration</option>
<option value="GraphicDesign" name="GraphicDesign">Graphic Design</option>
<option value="MotionGraphics" name="MotionGraphics">Motion Graphics</option>
<option value="WebDesign" name="WebDesign">Web Design</option>
</select>
</td><td>
<select class="custom-select" id="mediaSel2" name="mediaSel2"></select>
</td><td class="buttonRow">
<div id="addRow" class="addButton" onclick="addSelection()"><span class="plus"></span></div>
</td></tr></tbody>
</table>
So from here I was able to add the second dropdown when the onchange event has been fired.
JS code:
function dropDownSelect(s1,s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
var hideSel = document.getElementById("mediaSel2");
s2.innerHTML = "";
if(s1.value == "Illustration") {
var optionArray = ["Select|--select--","ChildrensBooks|Childrens Book Design","FanArt|Fan Art","WallArt|Wall Art"];
}
else if(s1.value == "GraphicDesign") {
var optionArray = ["Select|--select--","Logo|Logo","BusinessCards|Business Cards","Flyers|Flyers","Billboards|Billboards","MagazineAds|Magazine Ads","CatalogeDesign|Cataloge Design","NewsPaperAds|Newspaper Ads"];
}
else if(s1.value == "MotionGraphics") {
var optionArray = ["Select|--select--","LogoAnimation|Logo Animation","Explainers|Explainer Videos","ShortFilms|Short Film Animation","CharacterDesign|Character Design","ProductDesign|Product Design","Animation|Animation"];
}
else if(s1.value == "WebDesign") {
var optionArray = ["Websites|Websites"];
}
if(s1.value == "GraphicDesign" || s1.value == "Illustration" || s1.value == "MotionGraphics" || s1.value == "WebDesign") {
s2.style.display="inline-block";
} else {
s2.style.display="none";
}
for(var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
}
Like I said this all works great. but the final step is where I am struggling. I have the addButton in HTM that when clicked runs the next js code and gives me the dropdown.
I can't seem to figure out how to attach the function dropDownSelect from above.
addButton JS:
function addSelection() {
var html = '<tr><td><select class="custom-select addClick" id="mediaSel" name="mediaSel" onchange="dropDownSelect2(this.id, "mediaSel2")"><option value="">--Select--</option><option value="Illustration" name="Illustration">Illustration</option><option value="GraphicDesign" name="GraphicDesign">Graphic Design</option><option value="MotionGraphics" name="MotionGraphics">Motion Graphics</option><option value="WebDesign" name="WebDesign">Web Design</option></select></td><td><select class="custom-select" id="mediaSel2" name="mediaSel2"></select></td><td class="buttonRow"><div id="removeRow" class="removeButton" onclick="removeSelection()"><span class="minus"></span></div></td></tr>';
$('tbody').append(html);
}
any thoughts?
You need to escape the inner pair of double quotes around the parameter of the function call:
var html = '... onchange="dropDownSelect2(this.id, \"mediaSel2\")"><option ...`;

I want to display the price value for selected items using switch statement

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Switch Statement and Labeled Break</title>
<script>
addEvent(window, ‘load’, initialize);
function initialize()
{
// add an event to the drop down list
addEvent(document.getElementById(’chips’), ‘change’, getPrice);
}
function product(name, price)
{
this.name = name;
this.price = price;
}
var ICs = new Array();
ICs[0] = new product("Septium 900MHz", "$149");
ICs[1] = new product("Septium Pro 1.0GHz", "$249");
ICs[2] = new product("Octium BFD 750MHz", "$329");
var snacks = new Array();
snacks[0] = new product("Rays Potato Chips", "$1.79");
snacks[1] = new product("Cheezey-ettes", "$1.59");
snacks[2] = new product("Tortilla Flats", "$2.29");
// lookup in the ‘table’ the cost associated with the product
function getPrice()
{
var chipName = this.options[this.selectedIndex].text;
var chipType = this.options[this.selectedIndex].value;
var outField = document.getElementById(’cost’);
master:
switch(chipType)
{
case "ICs":
for (var i = 0; i < ICs.length; i++)
{
if (ICs[i].name == chipName)
{
outField.value = ICs[i].price;
break master;
}
}
break;
case "snacks":
for (var i = 0; i < snacks.length; i++)
{
if (snacks[i].name == chipName)
{
outField.value = snacks[i].price;
break master;
}
}
}
break;
default:
outField.value = "Not Found";
}
}
</script>
</head>
<body>
<h1>Switch Statement and Labeled Break</h1>
<p>Select a chip for lookup in the chip price table:</p>
<form id="theForm">
<p>
<label for="chips">Chip:</label>
<select id="chips">
<option></option>
<option value="ICs">Septium 900MHz</option>
<option value="ICs">Septium Pro 1.0GHz</option>
<option value="ICs">Octium BFD 750MHz</option>
<option value="snacks">Rays Potato Chips</option>
<option value="snacks">Cheezey-ettes</option>
<option value="snacks">Tortilla Flats</option>
<option>Poker Chipset</option>
</select>
<label for="cost"> Price:</label>
<input type="text" id="cost" size="10">
</p>
</form>
</body>
</html>
// In the above code snippets I am trying to show the price for selected chip ,but no price is being shown in the input field.I have attached the output screen shot.I have built two arrays with a custom object ,simulating two database tables.
I am also defining one function getPrice for associating the price related to the product.
Thanks in advance
output screenshot
This works.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Switch Statement and Labeled Break</title>
<script>
window.onload = initialize;
function initialize()
{
document.getElementById('chips').addEventListener('change', getPrice);
}
function product(name, price)
{
this.name = name;
this.price = price;
};
var ICs = new Array();
ICs[0] = new product("Septium 900MHz", "$149");
ICs[1] = new product("Septium Pro 1.0GHz", "$249");
ICs[2] = new product("Octium BFD 750MHz", "$329");
var snacks = new Array();
snacks[0] = new product("Rays Potato Chips", "$1.79");
snacks[1] = new product("Cheezey-ettes", "$1.59");
snacks[2] = new product("Tortilla Flats", "$2.29");
function getPrice()
{
var selectelem = document.getElementById("chips"), outField = document.getElementById('cost'), outvalue="";;
var chipName = selectelem.options[selectelem.selectedIndex].text;
var chipType = selectelem.value;
if(!chipType)
{
outField.value = ""; return;
}
switch(chipType)
{
case "ICs":
var arr = ICs.filter(function(item){
return item.name == chipName;
});
outvalue = arr[0].price;
break;
case "snacks":
var arr = snacks.filter(function(item){
return item.name == chipName;
});
outvalue = arr[0].price;
break;
default: outvalue = "Not Found"; break;
}
outField.value = outvalue;
}
</script>
</head>
<body>
<h1>Switch Statement and Labeled Break</h1>
<p>Select a chip for lookup in the chip price table:</p>
<form id="theForm">
<p>
<label for="chips">Chip:</label>
<select id="chips">
<option></option>
<option value="ICs">Septium 900MHz</option>
<option value="ICs">Septium Pro 1.0GHz</option>
<option value="ICs">Octium BFD 750MHz</option>
<option value="snacks">Rays Potato Chips</option>
<option value="snacks">Cheezey-ettes</option>
<option value="snacks">Tortilla Flats</option>
<option value="signals">TCP</option>
<option value="computer">Poker Chipset</option>
</select>
<label for="cost"> Price:</label>
<input type="text" id="cost" size="10">
</p> </form>
</body>
</html>
The switch is wrong. Should be something like this:
switch (chipType) {
case "ICs":
for (var i = 0; i < ICs.length; i++) {
if (ICs[i].name == chipName) {
outField.value = ICs[i].price;
break master;
}
}
break;
case "snacks":
for (var i = 0; i < snacks.length; i++) {
if (snacks[i].name == chipName) {
outField.value = snacks[i].price;
break master;
}
}
break;
default:
outField.value = "Not Found";
break;
}
Instead of AddEvent, you can use addEventListener. For example:
var chips = document.getElementById('chips');
chips.addEventListener('change', getPrice);

html select element that its options depends on another select

I have two select element and I want to show some options in second select based on what user choose at first select.
consider first select have two options : a , b ...
if user choose 'a' from first select :
the second select optiones should be -> c , d ...
and if user choose 'b' from first select :
the second select optiones should be : e , f ...
I have done some coding but the problem is at the start when user doesnt choose any option from first select the second select is always empty(it should show c , d)
<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>
If you can save the option values in a lookup object (or JSON):
function setOptions(select, values) {
for (var i = select.length = values.length; i--; )
select[i].innerText = values[i]
}
function value(select) { return select.value || select[0].value } // 1st item by default
var data = { 1: { 1.1: [1.11, 1.12], 1.2: [1.21, 1.22] },
2: { 2.1: [2.11, 2.12], 2.2: [2.21, 2.22], 2.3: [2.31, 2.32, 2.33] } }
s2.onchange = function() { setOptions(s3, data[value(s1)][value(s2)]) }
s1.onchange = function() { setOptions(s2, Object.keys(data[value(s1)])); s2.onchange() }
setOptions(s1, Object.keys(data)); s1.onchange(); // fill the options
<select id=s1 required size=3></select>
<select id=s2 required size=3></select>
<select id=s3 required size=3></select>
This code is based on JavaScript (No need for jQuery)
change Id name and value (x=="desire_value") according to your code
function myFunction() {
var x = document.getElementById("select1").value;
if (x == "3") document.getElementById("select2").style.display = "block";
else document.getElementById("select2").style.display = "none";
}
<select id="select1" onchange="myFunction()">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<select id="select2" style="display: none;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
You have to write the functionality outside of onchange(). Try the following:
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
let element = document.getElementById("s1");
let selOption = element.options[element.selectedIndex].value;
if(selOption == 'a'){
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required > </select>
Why don't you just put that hard coded...
<!DOCTYPE html>
<html>
<body>
<select id="s1" required>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required >
<option value="c">c</option>
<option value="d">d</option>
</select>
<script>
document.getElementById("s1").onchange = function() {
document.getElementById('s2').disabled = false; //enabling s2 select
document.getElementById('s2').innerHTML = ""; //clear s2 to avoid conflicts between options values
var opt0 = document.createElement('option');
var opt1 = document.createElement('option');
if (this.value == 'a') {
opt0.textContent = "c";
opt1.textContent = "d";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
} else if (this.value == 'b') {
opt0.textContent = "e";
opt1.textContent = "f";
document.getElementById('s2').appendChild(opt0);
document.getElementById('s2').appendChild(opt1);
}
};
</script>
</body>
</html>
One approach to contemplate is populating the dependant dropdowns with all values and use a data attribute for the parent-child relationship. Javascript then clones and removes the options for later insertion.
The functional javascript is now very lean and the dependency relationships are maintained in the DOM.
var s2Clone;
// Doesn't work in older IEs
//CLone the Dependant drop down and hide
document.addEventListener('DOMContentLoaded', function(){
s2Clone = document.getElementById("s2").cloneNode(true);
document.getElementById("s2").innerHTML = "";
}, false);
document.getElementById("s1").onchange = function() {
var selected = this.value;
//Get the nodes with a parent attribute of the selected data
var optionsToInsert = s2Clone.querySelectorAll("[data-parent='" + selected +"']");
//clear existing
var s2 = document.getElementById("s2");
s2.innerHTML = "";
//Add The new options.
for(i = 0; i < optionsToInsert.length; i++)
{
s2.appendChild(optionsToInsert[i]);
}
}
<select id="s1" required>
<option value="">Please select</option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select id="s2" required >
<option value="a1" data-parent="a">a - 1</option>
<option value="a2" data-parent="a">a - 2</option>
<option value="a3" data-parent="a">a - 3</option>
<option value="b1" data-parent="b">b - 1</option>
<option value="b2" data-parent="b">b - 2</option>
<option value="b3" data-parent="b">b - 3</option>
</select>

JavaScript Code Not Working

My java script code is not working, Currently when you select a value in the first drop down menu the second drop down menu becomes editable which is fine. But I want to make it as if when you select the option 'default' in the first drop down menu the second drop down menu reverts to 'default' and becomes disabled and read only, but if I select any other option other then 'default' the second menu should be editable.
<html>
<head>
<script type="text/javascript">
function mySecondFunction() {
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "Default")
{
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}
</script>
</head>
<body>
<select id="1" onchange="mySecondFunction()">
<option value="OptionZero">Default</option>
<option value="OptionOne">Car</option>
<option value="OptionTwo">Car2</option>
<option value="OptionThree">Car23</option>
</select>
<br>
<select disabled id="mySelection">
<option value="OptionZero">Default</option>
<option value="OptionOne">A</option>
<option value="OptionTwo">B</option>
<option value="OptionThree">C</option>
</select>
</body>
</html>
You should write
if(selectedValue == "OptionZero") {
It is the value attribute which set the value on an element.
Try as
function mySecondFunction() {
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OptionZero")
{
document.getElementById('mySelection').selectedIndex = 0;
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}
OR CAN WE TRY AS
function mySecondFunction() {
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].text;
if (selectedValue == "Default")
{
document.getElementById('mySelection').selectedIndex = 0;
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}
DEMO2
Demo
UPDATE DEMO
You need to use value OptionZero and not the Label Default, and set the value back in "mySelection"
if (selectedValue == "OptionZero")
{
document.getElementById("mySelection").disabled = true;
// set the value to default
document.getElementById("mySelection").value = "OptionZero"
} else {
document.getElementById("mySelection").disabled = false;
}
You have mistake with the value, this is the answer:
function mySecondFunction() {
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
document.getElementById("mySelection").disabled = selectedValue === "OptionZero"?true:false;
}
Please go through the following code.
<html>
<head>
<script type="text/javascript">
function mySecondFunction() {
var ddl = document.getElementById("1");
var selectedValue = ddl.options[ddl.selectedIndex].value;
if (selectedValue == "OptionZero")
{
document.getElementById("mySelection").value="OptionZero";
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}
</script>
</head>
<body>
<select id="1" onchange="mySecondFunction()">
<option value="OptionZero">Default</option>
<option value="OptionOne">Car</option>
<option value="OptionTwo">Car2</option>
<option value="OptionThree">Car23</option>
</select><br>
<select disabled id="mySelection">
<option value="OptionZero">Default</option>
<option value="OptionOne">A</option>
<option value="OptionTwo">B</option>
<option value="OptionThree">C</option>
</select>
</body>
</html>
Please change
selectedValue == "Default"
to
selectedValue == "OptionZero"
and add the following line in if condition
document.getElementById("mySelection").value="OptionZero";
Hope it will help you.Thank you.
Change your Script like this
function mySecondFunction() {
if (document.getElementById("1").value == "OptionZero")
{
document.getElementById("mySelection").value="OptionZero";
document.getElementById("mySelection").disabled = true;
}else {
document.getElementById("mySelection").disabled = false;
}
}
Here is Fiddle

How to populate a cascading Dropdown with JQuery

i have the following problem:
I started to create a form with HTML an JS and there are two Dropdowns (Country and City). now i want to make these two dynamic with JQuery so that only the cities of the selected countries are visible.
I've started with some basic JS which worked fine but makes some trouble in IE. Now i'm trying to convert my JS to JQuery for a better compatibility.
My original JS looks like this:
function populate(s1, s2) {
var s1 = document.getElementById(s1);
var s2 = document.getElementById(s2);
s2.innerHTML = "";
if (s1.value == "Germany") {
var optionArray = ["|", "magdeburg|Magdeburg", "duesseldorf|Duesseldorf", "leinfelden-echterdingen|Leinfelden-Echterdingen", "eschborn|Eschborn"];
} else if (s1.value == "Hungary") {
var optionArray = ["|", "pecs|Pecs", "budapest|Budapest", "debrecen|Debrecen"];
} else if (s1.value == "Russia") {
var optionArray = ["|", "st. petersburg|St. Petersburg"];
} else if (s1.value == "South Africa") {
var optionArray = ["|", "midrand|Midrand"];
} else if (s1.value == "USA") {
var optionArray = ["|", "downers grove|Downers Grove"];
} else if (s1.value == "Mexico") {
var optionArray = ["|", "puebla|Puebla"];
} else if (s1.value == "China") {
var optionArray = ["|", "beijing|Beijing"];
} else if (s1.value == "Spain") {
var optionArray = ["|", "barcelona|Barcelona"];
}
for (var option in optionArray) {
var pair = optionArray[option].split("|");
var newOption = document.createElement("option");
newOption.value = pair[0];
newOption.innerHTML = pair[1];
s2.options.add(newOption);
}
};
and here my Jquery:
http://jsfiddle.net/HvXSz/
i know it is very simple but i can't see the wood for the trees.
It should as simple as
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
Demo: Fiddle
I'm going to provide a second solution, as this post is still up in Google search for 'jquery cascade select'.
This is the first select:
<select class="select" id="province" onchange="filterCity();">
<option value="1">RM</option>
<option value="2">FI</option>
</select>
and this is the second, disabled until the first is selected:
<select class="select" id="city" disabled>
<option data-province="RM" value="1">ROMA</option>
<option data-province="RM" value="2">ANGUILLARA SABAZIA</option>
<option data-province="FI" value="3">FIRENZE</option>
<option data-province="FI" value="4">PONTASSIEVE</option>
</select>
this one is not visible, and acts as a container for all the elements filtered out by the selection:
<span id="option-container" style="visibility: hidden; position:absolute;"></span>
Finally, the script that filters:
<script>
function filterCity(){
var province = $("#province").find('option:selected').text(); // stores province
$("#option-container").children().appendTo("#city"); // moves <option> contained in #option-container back to their <select>
var toMove = $("#city").children("[data-province!='"+province+"']"); // selects city elements to move out
toMove.appendTo("#option-container"); // moves city elements in #option-container
$("#city").removeAttr("disabled"); // enables select
};
</script>
I have created cascading Dropdown for Country, State, City and Zip
It may helpful to someone. Here only some portion of code are posted you can see full working example on jsfiddle.
//Get html elements
var countySel = document.getElementById("countySel");
var stateSel = document.getElementById("stateSel");
var citySel = document.getElementById("citySel");
var zipSel = document.getElementById("zipSel");
//Load countries
for (var country in countryStateInfo) {
countySel.options[countySel.options.length] = new Option(country, country);
}
//County Changed
countySel.onchange = function () {
stateSel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
zipSel.length = 1; // remove all options bar first
if (this.selectedIndex < 1)
return; // done
for (var state in countryStateInfo[this.value]) {
stateSel.options[stateSel.options.length] = new Option(state, state);
}
}
Fiddle Demo
I have a handy code. you can just copy it:
Same as above
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
jQuery(function($) {
var locations = {
'Germany': ['Duesseldorf', 'Leinfelden-Echterdingen', 'Eschborn', 'asdasdasd'],
'Spain': ['Barcelona'],
'Hungary': ['Pecs'],
'USA': ['Downers Grove'],
'Mexico': ['Puebla'],
'South Africa': ['Midrand'],
'China': ['Beijing'],
'Japn': ['tokyo'],
'Shuidong': ['shuidongjie','maomingjie'],
'Russia': ['St. Petersburg'],
}
var $locations = $('#location');
$('#country').change(function () {
var country = $(this).val(), lcns = locations[country] || [];
var html = $.map(lcns, function(lcn){
return '<option value="' + lcn + '">' + lcn + '</option>'
}).join('');
$locations.html(html)
});
});
</script>
</head>
<body>1
<label class="page1">Country</label>
<div class="tooltips" title="Please select the country that the customer will primarily be served from">
<select id="country" name="country" placeholder="Phantasyland">
<option></option>
<option>Germany</option>
<option>Spain</option>
<option>Hungary</option>
<option>USA</option>
<option>Mexico</option>
<option>South Africa</option>
<option>China</option>
<option>Japn</option>
<option>Shuidong</option>
<option>Russia</option>
</select>
</div>
<br />
<br />
<label class="page1">Location</label>
<div class="tooltips" title="Please select the city that the customer is primarily to be served from.">
<select id="location" name="location" placeholder="Anycity"></select>
</div>
</body>
</html>
This is an example that I've done. I wish that will be useful for you.
$(document).ready(function(){
var ListNiveauCycle = [{"idNiveau":1,"libelleNiveau":"CL1","idCycle":1},{"idNiveau":26,"libelleNiveau":"Niveau 22","idCycle":24},{"idNiveau":34,"libelleNiveau":"CL3","idCycle":1},{"idNiveau":35,"libelleNiveau":"DAlf3","idCycle":1}];
console.log(ListNiveauCycle);
function remplirListNiveau(idCycle){
console.log('remplirListNiveau');
var $niveauSelect = $("#niveau");
// vider la liste
$niveauSelect.empty();
for (var i = 0; i < ListNiveauCycle.length; i++) {
if(ListNiveauCycle[i].idCycle==idCycle){
var opt1 = document.createElement('option');
opt1.innerHTML = ListNiveauCycle[i].libelleNiveau;
opt1.value = ListNiveauCycle[i].idNiveau;
$niveauSelect.append(opt1);
}
}
}
$("#cycles").change(function(){
remplirListNiveau(this.value)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Cycle</label>
<div class="col-sm-9">
<select class="form-control" id="cycles" required="">
<option value="">-----------</option>
<option value="1">Cycle1</option>
<option value="24">Cycle2</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Niveau</label>
<div class="col-sm-9">
<select id="niveau" class="form-control" required="" name="niveau.id">
</select>
</div>
</div>
</div>

Categories