JavaScript onchange event for dynamic dropdown in HTML - javascript

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 ...`;

Related

Adding another option when the select dropdown is clicked?

I need to add a new select option in my HTML when they click it
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>
This new option is dynamic and will be coming from an API response... I'm parsing the var value from the API response but for now, I made it static just to test.
Right now, I have this:
$(document).ready(function () {
var k = 1
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var html = $(".statusButton").html();
if (k == 1) {
if (value == "Disable") {
new_v = "<option value='Disable' >Disable</option>";
}
else if (value == "Enable") {
new_v = "<option value='Enable' >Enable</option>"
}
var full = html + "" + new_v;
$(".statusButton").html(full);
k = 2;
}
});
});
It is working on JSFiddle but when I try to integrate it on my website, it's not reading it, even just the console log. WHat am I doing wrong?
I'm not sure exactly what's wrong, but I think a better approach might be to use jQuery's append method (https://api.jquery.com/append/).
Consider:
...
$(".statusButton").on('focus', function () {
var value = "Disable";
var new_v = "";
var $statusButton = $(".statusButton");
if(k == 1){
if(value == "Disable")
{
$statusButton.append("<option value='Disable' >Disable</option>");
}
else if(value == "Enable")
{
$statusButton.append("<option value='Enable' >Enable</option>")
}
...
If you do things that way, you don't have to mess around with any extra .html calls.
This is short answer without creating too many variable.
$(document).ready(function() {
var k = 1
$(".statusButton").on('focus', function() {
var value = "Disable";
if (k == 1) {
if (value == "Disable") {
$(".statusButton").append("<option value='Disable' >Disable</option>");
} else if (value == "Enable") {
$(".statusButton").append("<option value='Enable' >Enable</option>")
}
k = 2;
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="statusButtonChange statusButton " data-value="49506">
<option value="0" selected=""></option>
<option value="1">Close</option>
<option value="2" disabled="" style="color:grey;">Taken</option>
</select>

Javascript onchange event not working in my code

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/

How to create a select that depends on the value of another select?

I need to create a menu of regions hat display two lists: a <select> for the region and another <select> for the available municipalities of that region. For this, I have a <form> and I update the municipalities through JavaScript. I have problems assigning the municipalities as <option>s of the second <select>. The option matrix of the menu doesn't accept the assignment of the values.
Here's the code.
HTML.
<html>
<head>
<title>
Página menú principal.
</title>
<?!= incluirArchivo('ArchivoJS'); ?>
</head>
<body onLoad = "preparar();">
<form id="formularioConductor" name="formularioConductor" method="post" enctype="multipart/form-data" autocomplete = "on">
<select name="menuDepartamento" id="menuDepartamento" tabindex="2" accesskey="e" onChange="municipiosDepartamento();">
<option value="x" selected="selected">ELIJA UN DEPARTAMENTO</option>
<option value="0">Antioquia</option>
<option value="1">Atlántico</option>
</select>
<select name="menuMunicipios" id="menuMunicipios" tabindex="3" disabled>
<option value=0>TODOS LOS MUNICIPIOS</option>
</select>
</form>
</body>
</html>
Javascript code:
<script lenguage="javascript">
function preparar() {
document.forms[0].elements.numeroLicencia.focus();
document.forms[0].elements.nombreConductor.disabled = true;
document.forms[0].elements.botonEnviar.disabled = true;
document.forms[0].elements.botonActualizar.disabled = true;
}
function municipiosDepartamento() {
var arregloMunicipiosDepartamento = new Array();
var posicionMunicipio = document.forms[0].elements.menuDepartamento.value;
arregloMunicipiosDepartamento = municipiosColombia(posicionMunicipio);
if(document.forms[0].elements.menuMunicipios.options.length > 1){
var totalMunicipios = document.forms[0].elements.menuMunicipios.length;
for (var i = 1; i < totalMunicipios; i ++){
document.forms[0].elements.menuMunicipios.options[1] = null;
}
}
if(document.forms[0].elements.menuDepartamento.value === "x"){
document.forms[0].elements.menuMunicipios.selectedItem = 0;
document.forms[0].elements.menuMunicipios.disabled = true;
}
else
{
document.forms[0].elements.menuMunicipios.options.length = arregloMunicipiosDepartamento.length;
for (var i = 0; i < arregloMunicipiosDepartamento.length; i ++) {
var opcionTemporal = new Option(arregloMunicipiosDepartamento[i], (i+1));
***document.forms[0].elements.menuMunicipios.options[i+1].text = opcionTemporal.text;
document.forms[0].elements.menuMunicipios.options[i+1].value = opcionTemporal.value;***
}
document.forms[0].elements.menuMunicipios.disabled = false;
}
}
function municipiosColombia(posicion) {
var antioquia, atlantico, arregloTodos, arregloMunicipiosDepartamento = new Array();
antioquia=["Medellín","Abejorral","Abriaqui","Alejandria"];
atlantico = ["Barranquilla","Baranoa","Campo De La Cruz","Candelaria"];
arregloTodos = [antioquia, atlantico];
arregloMunicipiosDepartamento=arregloTodos[posicion];
return arregloMunicipiosDepartamento;
}
</script>
I have highlighted the work that doesn't work.
The way I would do what you describe is to clear out the options each time and recreate the required ones, then add them into the particular select, like so:
var regions = {};
regions['A'] = ['mu', 'ni', 'ci', 'pal', 'it', 'y'];
regions['B'] = ['I', 'like', 'bananas'];
var selRegion = document.getElementById('region');
selRegion.onchange = setMunicipalities;
var selMun = document.getElementById('municipality');
function setMunicipalities(e)
{
while(selMun.length > 0)
{
selMun.remove(0);
}
if(selRegion.selectedOptions[0].value === 'ALL')
{
for(var r in regions)
{
if(regions.hasOwnProperty(r))
{
addMunicipalities(regions[r]);
}
}
}
else
{
var reg = selRegion.selectedOptions[0].value;
addMunicipalities(regions[reg]);
}
}
function addMunicipalities(region)
{
var allMun = document.createElement('option');
allMun.setAttribute('value', 'ALL');
var allMunText = document.createTextNode('ALL');
allMun.appendChild(allMunText);
selMun.add(allMun);
for (var mi = 0; mi < region.length; mi++)
{
var m = region[mi];
var mun = document.createElement('option');
mun.setAttribute('value', m);
var munText = document.createTextNode(m);
mun.appendChild(munText);
selMun.add(mun);
}
}
setMunicipalities(null);
<label for="region">Region</label>
<select id="region">
<option selected="selected" value="ALL">ALL</option>
<option value="A">A</option>
<option value="B">B</option>
</select>
<label for="municipality">Municipality</label>
<select id="municipality">
</select>
I haven't read your entire code because I had a hard time reading code with contents not in English but anyway, I get what you're trying to do here. Suppose that your first select list contains "Region A" and "Region B" as options; "Municipality A1", "Municipality A2", "Municipality B1","Municipality B2" are the possible options for the second select list. Here's a function that will change the options of the second select list depending on what is selected on the first select list:
function optionChanger(v_selected){
var whatisselected= v_selected.options[v_selected.selectedIndex].value;
var municipalities= {};
municipalities['A'] = ['Municipality A1','Municipality A2'];
municipalities['B'] = ['Municipality B1','Municipality B2'];
v_selected.options.length=0; //remove the contents of the second select list
v_selected.options[0] = new Option(municipalities[whatisselected][0],municipalities[whatisselected][0],false,true);// set the first option of the second list as the default selected value
for(x=1;x<municipalities[whatisselected].length;x++){ //add the remaining options to the second list
v_selected.options[x] = new Option(municipalities[whatisselected][x],municipalities[whatisselected][x],false,false);
}
}
Then add this inside the tag of your FIRST select list:
onchange='optionChanger(this)'
PS: Please notice that the return value of the first select list must be 'A', 'B'

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