Home > Back-end >  Pass the text from a form Select-Option to a text input field
Pass the text from a form Select-Option to a text input field

Time:06-01

I would like to pass the text portion (not the value) of a form Select-Option to a hidden text-input field within the same form when the user makes a selection.

I have explored some java and PHP 'examples' I found in my research, but none of them seem to work for me.

I have posted a raw example of the form to see if anyone can lead me to water. Any help wouold be appreciated.

HMTL

<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"  name="hiddenField" placeholder="Selected fruit appears 
here.">

</form>

</body>    

</html>

CodePudding user response:

well if you want to pass the text portion you should add the names as the values too like

---
code
---
<option value="Grapes">Grapes</option>
<option value="Strawberries">Strawberries</option>
---
code
---

CodePudding user response:

It's not as easy as getting the selected option's value, which can be retrieved simply as selectElement.value, yet it's not difficult at all.

selectElement.options will give you an array of ALL the options inside the select element. You will find the selected option's index to be selectElement.selectedIndex.

With that said, you can access to the selected option like this: selectElement.options[selectElement.selectedIndex].

Finally, you can get the text property like this: selectElement.options[selectElement.selectedIndex].text

Here's the code:

// 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"  name="hiddenField" placeholder="Selected fruit appears 
here.">

</form>

  • Related