Tengo un formulario en mi plantilla con un menú desplegable para seleccionar una opción. ¿Cómo puedo cambiar un valor oculto al índice de lo que está seleccionado? Entonces, si eligen la opción 2 con el valor de "Principal", almacena 1 o si eligen la opción 1 con el valor de "Entrantes", almacena 0.
<div class="form-group"> <input type="hidden" id="arrayIndex" name="arrayIndex"> <label for="dishCategory">Choose a category:</label> <select type="text" class="form-control" name="dishCategory" id="dishCategory"> {{#entries}} {{#category}} <option value="{{catName}}">{{catName}}</option> {{/category}} {{/entries}} </select> </div>El siguiente fragmento agrega algo de lógica a su documento html. Cada vez que selecciona una nueva opción del menú desplegable, realiza las siguientes acciones:
#arrayIndex ) como el índice mencionado anteriormente 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 class="form-group"> <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" class="form-control" 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>