2

I am trying to add value to the text box of the drop down <select> tag in HTML with JavaScript. This is my code:

function disableTip() {
  document.getElementById('cars').value = 'Hello';
}
<label for="cars">Choose a car:</label>

<select name="cars" id="cars">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>

<button onclick="disableTip()">Click me</button>

When i click the button the textbox becomes empty doesn't write "Hello". Any idea what is wrong with my code?

Thanks in advance.

Andy
  • 61,948
  • 13
  • 68
  • 95
  • you want to add another option to the select or force the select value ? – jeremy-denis Jun 09 '22 at 09:42
  • @jeremy-denis no just on the textbox of that drop down to write hello –  Jun 09 '22 at 09:44
  • 1
    There is no text box. Select elements create drop down menus, not comboboxes. – Quentin Jun 09 '22 at 09:45
  • 2
    Your code is trying to set the value of the `select` element, not add anything. If you want to add an option you could do `document.getElementById('cars').appendChild( new Option( 'Hello' ) )`. The `select` empties because the value 'Hello' doesn't exist in your `select` element, so no selection is made. – somethinghere Jun 09 '22 at 09:45
  • @somethinghere But even if i replace the Hello with saab which exists inside the select still wont show. –  Jun 09 '22 at 10:00
  • 1
    All I can say is that when you have `` using `select.value = 'saab'` should show saab as the selected value. – somethinghere Jun 09 '22 at 11:26

0 Answers0