1

I'm trying to build a form with two select. Depending on the choice made in the first one, the list of possible choices in the second should be adapted.

So if select 1 choice value is 1 => Display object 1 as options in select 2.

I created this js code :

var EntiteGenerale = document.getElementById("TypeEntityId").value;
var select = document.getElementById("EntityId");
var index;

var Departement = {
  1: "Finances et Administration",
  2: "Service Logistique Transversale",
  3: "Institut de Formation",
  4: "Communication, Marketing & Commercial",
  5: "Volontariat",
  6: "Ressources Humaines",
  7: "Service francophone du sang",
  8: "Service ECM et DIH",
  9: "Service Tracing",
  10: "Département Secours"
};

var CentreSecours = {
  1: "CG BUTGENBACH BULLINGEN",
  2: "CS BLEGNY",
  3: "CS BRABANT OUEST",
  4: "CS CHARLEROI",
  5: "CS HAUTE SENNE",
  6: "CS HERSTAL - OUPEYE",
  7: "CS TOURNAI",
  8: "CS NAMUR",
  9: "CS OTTIGNIES",
  10: "CS OUGREE",
  11: "CS PHILIPPEVILLE",
  12: "CS ROCHEFORT",
  13: "CS SPA",
  14: "CS HESBAYE-CONDROZ",
  15: "CS JODOIGNE",
  16: "CS LIEGE",
  17: "CS LUXEMBOURG",
  18: "CS MONS",
  19: "CS MOUSCRON"
};




function DisplayEntiteL() {
  if (EntiteGenerale === 2) {
    for (index in Departement) {
      select.options[select.options.length] = new Option(Departement[index], index);
    }
  } else if (EntiteGenerale === 3) {
    for (index in CentreSecours) {
      select.options[select.options.length] = new Option(CentreSecours[index], index);
    }
  } else {
    console.log("rien à afficher");
  }
}

But when I try it, the else statement "rien à afficher" is always displaying because my options aren't added.

Could you tell me please what's wrong with my code ? See the full code in this JSFiddle.

Thank you in advance.

Best regards,

1
  • you get the value when ther page loads, but not when the select value chnages. Move the var EntiteGenerale = document.getElementById("TypeEntityId").value; line inside DisplayEntiteL() Commented Mar 8, 2019 at 9:56

3 Answers 3

1

If I understand your question correctly, you want the <option> eleemnts of the EntityId select to dynamically change based on the value of the TypeEntityId select element. Consider revising your code so that the change event is added to the TypeEntityId select via the addEventListener():

/* Bind change event via addEventListener() */
document.getElementById("TypeEntityId").addEventListener('change', DisplayEntiteL)

Also, you revise your if lines so that the values in the comparisons are strings, to ensure that the value match conditions can be satisfied:

/* Add event parameter to localize value extraction from corresponding
select element */
function DisplayEntiteL(event) {

  /* Get current value of TypeEntityId select */
  const value = event.currentTarget.value
  const entityId = document.getElementById("EntityId");

  /* Empty any previous options from EntityId select */
  while (entityId.hasChildNodes()) {
    entityId.removeChild(entityId.lastChild);
  }

    /* If value of TypeEntityId is 2 then show Departement items in
  entityId select */
  if (value === '2') {
    for (index in Departement) {
      entityId.appendChild(new Option(Departement[index], index));
    }

  }   
    /* If value of TypeEntityId is 3 then show CentreSecours items in
  entityId select */
  else if (value === '3') {

    for (index in CentreSecours) {
      entityId.appendChild(new Option(CentreSecours[index], index));
    }
  } 
  /* Otherwise log to console */
  else {
    /* entityId.appendChild(new Option('No options')); */
    console.log("rien à afficher");
  }
}

Also, the code above introduces the event parameter, allowing you to access the value of the TypeEntityId select within the event handler. For a full working sample see this JSFiddle, or the snippet below:

var EntiteGenerale = document.getElementById("TypeEntityId").value;

var Departement = {
  1: "Finances et Administration",
  2: "Service Logistique Transversale",
  3: "Institut de Formation",
  4: "Communication, Marketing & Commercial",
  5: "Volontariat",
  6: "Ressources Humaines",
  7: "Service francophone du sang",
  8: "Service ECM et DIH",
  9: "Service Tracing",
  10: "Département Secours"
};

var CentreSecours = {
  1: "CG BUTGENBACH BULLINGEN",
  2: "CS BLEGNY",
  3: "CS BRABANT OUEST",
  4: "CS CHARLEROI",
  5: "CS HAUTE SENNE",
  6: "CS HERSTAL - OUPEYE",
  7: "CS TOURNAI",
  8: "CS NAMUR",
  9: "CS OTTIGNIES",
  10: "CS OUGREE",
  11: "CS PHILIPPEVILLE",
  12: "CS ROCHEFORT",
  13: "CS SPA",
  14: "CS HESBAYE-CONDROZ",
  15: "CS JODOIGNE",
  16: "CS LIEGE",
  17: "CS LUXEMBOURG",
  18: "CS MONS",
  19: "CS MOUSCRON"
};

/* Add event parameter to localise value extraction from corresponding
select element */
function DisplayEntiteL(event) {
	
  /* Get current value of TypeEntityId select */
  const value = event.currentTarget.value
  const entityId = document.getElementById("EntityId");

  /* Empty any previous options from EntityId select */
  while (entityId.hasChildNodes()) {
    entityId.removeChild(entityId.lastChild);
  }

	/* If value of TypeEntityId is 2 then show Departement items in
  entityId select */
  if (value === '2') {
    for (index in Departement) {
      entityId.appendChild(new Option(Departement[index], index));
    }

  }   
	/* If value of TypeEntityId is 3 then show CentreSecours items in
  entityId select */
  else if (value === '3') {

    for (index in CentreSecours) {
      entityId.appendChild(new Option(CentreSecours[index], index));
    }
  } 
  /* Otherwise log to console */
  else {
  	/* entityId.appendChild(new Option('No options')); */
    console.log("rien à afficher");
  }
}

/* Bind change event via addEventListener() */
document.getElementById("TypeEntityId").addEventListener('change', DisplayEntiteL)
  input[type='checkbox'] {
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    border: 1px solid rgba(0, 0, 0, 0.1);
    width: 15px;
    height: 15px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  }

  input[type='radio'] {
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    border: 1px solid rgba(0, 0, 0, 0.1);
    width: 15px;
    height: 15px;
    -webkit-border-radius: 3px;
    -moz-border-radius: 3px;
    border-radius: 3px;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
    -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
    -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
    transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  }

  input[type='radio']:checked {
    background-color: red;
  }

  input[type='checkbox']:checked {
    background-color: red;
  }

  input::placeholder {
    font-size: 0.7rem;
  }

  select {
    border-radius: 20px;
    font-size: 0.8rem;
  }

  select:focus {
    border-color: #ff2400;
    outline: 0;
    box-shadow: none;
  }
<div class="row col-md-12">
  <div class="col-md-12">
    Votre entité générale :&nbsp;&nbsp;
    <select data-val="true" data-val-number="The field TypeEntityId must be a number." data-val-range="The field TypeEntityId must be between 1 and 2147483647." data-val-range-max="2147483647" data-val-range-min="1" data-val-required="Vous devez donner un TYPE d'entité"
      id="TypeEntityId" name="TypeEntityId">
      <option value="">Sélectionnez une entité générale</option>
                        <option value="2">Départements &amp; Services centraux</option>
                        <option value="3">Centre de secours</option>
                        <option value="4">Section locale (Bruxelles) </option>
                        <option value="5">Comité Provincial</option>
                        <option value="6">Relais</option>
                        <option value="7">SISU</option>
                        <option value="8">Centre ADA</option>
                        <option value="9">Maison Croix-Rouge</option>
                        </select>
    <span class="field-validation-valid text-danger" data-valmsg-for="TypeEntityId" data-valmsg-replace="true"></span>
  </div>

</div>
<br>
<div class="row col-md-12">
  <div class="col-md-12">
    Votre entité locale :&nbsp;&nbsp;
    <select data-val="true" data-val-number="The field EntityId must be a number." data-val-range="The field EntityId must be between 1 and 2147483647." data-val-range-max="2147483647" data-val-range-min="1" data-val-required="Vous devez donner une ENTITE"
      id="EntityId" name="EntityId"><option value="">Sélectionnez une entité locale</option>
</select>
    <span class="field-validation-valid text-danger" data-valmsg-for="EntityId" data-valmsg-replace="true"></span>
  </div>

</div>

Sign up to request clarification or add additional context in comments.

Comments

1
  1. You are store the selected value before to the change function.so each time is a same value.
  2. So call inside the change function.
  3. And also selected value return with string .you should convert to int .Otherwise === is return false.Because === validate the datatype also

var EntiteGenerale = document.getElementById("TypeEntityId");
var select = document.getElementById("EntityId");
var index;

var Departement = {
  1: "Finances et Administration",
  2: "Service Logistique Transversale",
  3: "Institut de Formation",
  4: "Communication, Marketing & Commercial",
  5: "Volontariat",
  6: "Ressources Humaines",
  7: "Service francophone du sang",
  8: "Service ECM et DIH",
  9: "Service Tracing",
  10: "Département Secours"
};

var CentreSecours = {
  1: "CG BUTGENBACH BULLINGEN",
  2: "CS BLEGNY",
  3: "CS BRABANT OUEST",
  4: "CS CHARLEROI",
  5: "CS HAUTE SENNE",
  6: "CS HERSTAL - OUPEYE",
  7: "CS TOURNAI",
  8: "CS NAMUR",
  9: "CS OTTIGNIES",
  10: "CS OUGREE",
  11: "CS PHILIPPEVILLE",
  12: "CS ROCHEFORT",
  13: "CS SPA",
  14: "CS HESBAYE-CONDROZ",
  15: "CS JODOIGNE",
  16: "CS LIEGE",
  17: "CS LUXEMBOURG",
  18: "CS MONS",
  19: "CS MOUSCRON"
};




function DisplayEntiteL() {
  EntiteGenerale = parseFloat(EntiteGenerale.value);
  if (EntiteGenerale === 2) {
    for (index in Departement) {
      select.options[select.options.length] = new Option(Departement[index], index);
    }
  } else if (EntiteGenerale === 3) {
    for (index in CentreSecours) {
      select.options[select.options.length] = new Option(CentreSecours[index], index);
    }
  } else {
    console.log("rien à afficher");
  }
}
input[type='checkbox'] {
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  border: 1px solid rgba(0, 0, 0, 0.1);
  width: 15px;
  height: 15px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

input[type='radio'] {
  -webkit-appearance: none;
  -moz-appearance: none;
  -o-appearance: none;
  border: 1px solid rgba(0, 0, 0, 0.1);
  width: 15px;
  height: 15px;
  -webkit-border-radius: 3px;
  -moz-border-radius: 3px;
  border-radius: 3px;
  box-shadow: inset 0 1px 1px rgba(0, 0, 0, .075);
  -webkit-transition: border-color ease-in-out .15s, -webkit-box-shadow ease-in-out .15s;
  -o-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
  transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}

input[type='radio']:checked {
  background-color: red;
}

input[type='checkbox']:checked {
  background-color: red;
}

input::placeholder {
  font-size: 0.7rem;
}

select {
  border-radius: 20px;
  font-size: 0.8rem;
}

select:focus {
  border-color: #ff2400;
  outline: 0;
  box-shadow: none;
}
<div class="row col-md-12">
  <div class="col-md-12">
    Votre entité générale :&nbsp;&nbsp;
    <select onchange="DisplayEntiteL()" data-val="true" data-val-number="The field TypeEntityId must be a number." data-val-range="The field TypeEntityId must be between 1 and 2147483647." data-val-range-max="2147483647" data-val-range-min="1" data-val-required="Vous devez donner un TYPE d'entité"
      id="TypeEntityId" name="TypeEntityId">
      <option value="">Sélectionnez une entité générale</option>
      <option value="2">Départements &amp; Services centraux</option>
      <option value="3">Centre de secours</option>
      <option value="4">Section locale (Bruxelles) </option>
      <option value="5">Comité Provincial</option>
      <option value="6">Relais</option>
      <option value="7">SISU</option>
      <option value="8">Centre ADA</option>
      <option value="9">Maison Croix-Rouge</option>
    </select>
    <span class="field-validation-valid text-danger" data-valmsg-for="TypeEntityId" data-valmsg-replace="true"></span>
  </div>

</div>
<br>
<div class="row col-md-12">
  <div class="col-md-12">
    Votre entité locale :&nbsp;&nbsp;
    <select data-val="true" data-val-number="The field EntityId must be a number." data-val-range="The field EntityId must be between 1 and 2147483647." data-val-range-max="2147483647" data-val-range-min="1" data-val-required="Vous devez donner une ENTITE"
      id="EntityId" name="EntityId">
      <option value="">Sélectionnez une entité locale</option>
    </select>
    <span class="field-validation-valid text-danger" data-valmsg-for="EntityId" data-valmsg-replace="true"></span>
  </div>

</div>

For why parseFloat

enter image description here

2 Comments

Why parseFloat(EntiteGenerale.value) and not parseInt(EntiteGenerale.value)? Or even +EntiteGenerale.value?
@iArcadia. Because parseFloat is better approach for number.The will convert to number both normal and decimal value see this image in my updated answer
0

Thank you so much @prasanth!

After a few more researches, I tried this who works perfectly. I added a function to clear the select before displaying new object inside.

  <select onchange="DisplayEntiteL(event)"></select>

--

 var EntiteGenerale = document.getElementById("TypeEntityId");
    var select = document.getElementById("EntityId");
    var index;

    var Departement = {
      1: "Finances et Administration",
      2: "Service Logistique Transversale",
      3: "Institut de Formation",
      4: "Communication, Marketing & Commercial",
      5: "Volontariat",
      6: "Ressources Humaines",
      7: "Service francophone du sang",
      8: "Service ECM et DIH",
      9: "Service Tracing",
      10: "Département Secours"
    };

    var CentreSecours = {
      1: "CG BUTGENBACH BULLINGEN",
      2: "CS BLEGNY",
      3: "CS BRABANT OUEST",
      4: "CS CHARLEROI",
      5: "CS HAUTE SENNE",
      6: "CS HERSTAL - OUPEYE",
      7: "CS TOURNAI",
      8: "CS NAMUR",
      9: "CS OTTIGNIES",
      10: "CS OUGREE",
      11: "CS PHILIPPEVILLE",
      12: "CS ROCHEFORT",
      13: "CS SPA",
      14: "CS HESBAYE-CONDROZ",
      15: "CS JODOIGNE",
      16: "CS LIEGE",
      17: "CS LUXEMBOURG",
      18: "CS MONS",
      19: "CS MOUSCRON"
    };


    function clearOption(){
      var x = document.getElementById("EntityId");
      while (x.length != 0) {
        x.remove(x.length-1);
      }
     }

    function DisplayEntiteL(event) {
      if (event.target.value === '1') {
        clearOption();
        for (index in Departement) {
          select.options[select.options.length] = new Option(Departement[index], index);
        }
      } else if (event.target.value === '2') {
        clearOption();
        for (index in CentreSecours) {
          select.options[select.options.length] = new Option(CentreSecours[index], index);
        }
      } else {
        console.log("rien à afficher");
      }
    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.