Home > other >  Change dropdown placeholder text
Change dropdown placeholder text

Time:11-03

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

CodePudding user response:

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>

  • Related