Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change dropdown placeholder text

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 option dropdown text is change to selected option text, can i change this text on dropdown placeholder via js? like when i open dropdown i see ‘training 10’ and ‘training 9’ option but when i choose one i need custom text in placeholder, for example "you selected training 9", and in dropdown text of option still should be "training 9" and value of dropdown input also

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading