Me gustaría pasar la porción de texto (no el valor) de una opción de selección de formulario a un campo de entrada de texto oculto dentro del mismo formulario cuando el usuario hace una selección.
He explorado algunos 'ejemplos' de Java y PHP que encontré en mi investigación, pero ninguno de ellos parece funcionar para mí.
He publicado un ejemplo en bruto del formulario para ver si alguien me puede llevar al agua. Cualquier ayuda sería apreciada.
HTML
<html> <head> </head> <body> <form action="fruitBasket.php" method="post" enctype="multipart/form-data"> <select id="fruitSelector" name="fruitSelector"> <option value="0" selected="selected" disabled="disabled">Select Fruit</option> <option value="1">Grapes</option> <option value="2">Strawberries</option> <option value="3">Peaches</option> <option value="4">Blueberries</option> </select> <br> <br> <input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears here."> </form> </body> </html>No es tan fácil como obtener el valor de la opción seleccionada, que se puede recuperar simplemente como selectElement.value , pero no es nada difícil.
selectElement.options le dará una matriz de TODAS las opciones dentro del elemento de selección. Encontrará que el índice de la opción seleccionada es selectElement.selectedIndex .
Dicho esto, puede acceder a la opción seleccionada de esta manera: selectElement.options[selectElement.selectedIndex] .
Finalmente, puede obtener la propiedad de text de esta manera: selectElement.options[selectElement.selectedIndex].text
Aquí está el código:
// THIS CONSTANT REPRESENTS THE <select> ELEMENT const theSelect = document.getElementById('fruitSelector') // THIS LINE BINDS THE input EVENT TO THE ABOVE select ELEMENT // IT WILL BE EXECUTED EVERYTIME THE USER SELECTS AN OPTION theSelect.addEventListener('input', function() { // THIS IS HOW YOU GET THE SELECTED OPTION'S TEXT let selectedOptText = theSelect.options[theSelect.selectedIndex].text // FINALLY, THIS COPIES THE ABOVE TEXT TO THE INPUT ELEMENT: document.querySelector('.hiddenField').value = selectedOptText; }) <form action="fruitBasket.php" method="post" enctype="multipart/form-data"> <select id="fruitSelector" name="fruitSelector"> <option value="0" selected="selected" disabled="disabled">Select Fruit</option> <option value="1">Grapes</option> <option value="2">Strawberries</option> <option value="3">Peaches</option> <option value="4">Blueberries</option> </select> <br> <br> <input type="text" class="hiddenField" name="hiddenField" placeholder="Selected fruit appears here."> </form>bueno, si desea pasar la parte de texto, debe agregar los nombres como valores también como
--- code --- <option value="Grapes">Grapes</option> <option value="Strawberries">Strawberries</option> --- code ---