Home > Net >  Javascript, change hidden value to dropdown index
Javascript, change hidden value to dropdown index

Time:04-10

I have a form in my template with a drop down to select an option. how can I change a hidden value to the index of whats selected. So if they pick option 2 with the value of "Mains" it stores 1 or if they choose option 1 with a value of "Starters" it stores 0.

<div >
        <input type="hidden" id="arrayIndex" name="arrayIndex">
            <label for="dishCategory">Choose a category:</label>
            <select type="text"  name="dishCategory" id="dishCategory">
            {{#entries}}
                {{#category}}
                <option value="{{catName}}">{{catName}}</option>
                {{/category}}
            {{/entries}}
            </select>
        </div>

CodePudding user response:

The following snippet adds some logic to your html document. Anytime you select a new option from the dropdown, it performs the following actions:

  • Updates an output message showing which index was picked among the options
  • Sets the value of the hidden type input (#arrayIndex) as that index mentioned before

document.addEventListener("DOMContentLoaded", function() {
 
  let select = document.getElementById('dishCategory');
  select.addEventListener('change', (event) => {
  
      //value of the selected option
      let selectedValue = select.value;
      //index of the selected option
      let selectedOptionIndex = select.selectedIndex;
      //the entire selected option element
      let selectedOption = select.options[select.selectedIndex];
      
      //updates the msg with information about which option was picked
      document.getElementById('msg').innerText =
        `The index of the option chosen was: ${selectedOptionIndex}`;
      
      //updates the value of the hidden input with such index
      document.getElementById('arrayIndex').value =
        selectedOptionIndex;
      
  });
  
});
#msg{
  border: solid 1px black;
  margin-bottom: 10px;
}
<div >

  <input type="hidden" id="arrayIndex" name="arrayIndex">
  <div id="msg">Select an option in the dropdown...</div>
  
  <label for="dishCategory">Choose a category:</label>  
  <select type="text"
          
          name="dishCategory"
          id="dishCategory">
      <option value="" disabled selected>Select your option</option>
    
      <option value="Tom">01-Tom</option>
      <option value="Jerry">02-Jerry</option>
      <option value="Mickey">03-Mickey</option>

  </select>
</div>

  • Related