0

I have a dropdown input

<select id="training" name="TrainingTopic">
       <option value="training 10">training 10</option>
       <option value="training 9">training 9</option>
</select>

When I choose one of the options the dropdown text is changed to the selected option text, can I change this text on the dropdown placeholder via js? For example, when I open the dropdown I see training 10 and training 9 options, but when I choose one I need custom text in the placeholder, for example, "you selected training 9", and in the dropdown text of the option still should be "training 9" and the value of the dropdown input also.

Austin
  • 2,203
  • 3
  • 12
  • 28
  • it is unclear to me what you actually trying to do. A Select dropdown has no placeholder. It shows the selected option. – tacoshy Nov 03 '22 at 09:08
  • Does is have to be in the select box itself? Can't you prefix the select box with the words you want? – Wimanicesir Nov 03 '22 at 09:15
  • Does this answer your question? [How do I make a placeholder for a 'select' box?](https://stackoverflow.com/questions/5805059/how-do-i-make-a-placeholder-for-a-select-box) – Syed Arsalan Hussain Nov 03 '22 at 09:15

1 Answers1

0

Use a hidden option and the following JS

const elTrainingSelect = document.querySelector("#training");
const elTrainingHolder = elTrainingSelect.querySelector("option");

elTrainingSelect.addEventListener("input", () => {
  elTrainingHolder.value = elTrainingSelect.value;
  elTrainingHolder.textContent = `You selected: ${elTrainingSelect.value}`;
  elTrainingSelect.selectedIndex = 0;
});

// Test
const elForm = document.querySelector("form");
elForm.addEventListener("submit", (ev) => {
  ev.preventDefault();
  const formData = new FormData(elForm);
  console.log([...formData.values()])
});
<form>
<select id="training" name="TrainingTopic">
  <option hidden>Select a training</option>
  <option value="training 10">training 10</option>
  <option value="training 9">training 9</option>
</select>
<button type="submit">SEND</button>
</form>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313