show empty value in html select element

11,290

Solution 1

Out of the box, HTML selects do not provide such functionality. You will have to add an empty <option value="somethingwrong">Please, pick a value</option> element and use scripting to check if the user has selected this specific value. I'd suggest catching both onchange event of the dropdown and onsubmit event of whole form.

Solution 2

You can insert option in select, and remove that whenever it is changed to reduce problems with that options

Check the Demo here

Share:
11,290
Koen Peters
Author by

Koen Peters

Technical Director at ISAAC: http://www.isaac.nl

Updated on July 13, 2022

Comments

  • Koen Peters
    Koen Peters almost 2 years

    I have an HTML select element (combo box) in a form with a couple if options in it. As always each option has a specific value. During the page's initialization I get a value from the server that I must use as the selected option in the list. Sometimes however I get a value from the server that does not match any of the available options. (grrrr)

    I want to let the user know that the value I got from the server is not a valid option. What I'd like to do is show an empty select box (as if no selection was made) without having an actual empty option as one of the options. Also I'd like to use the default select element if possible. Is something like this possible?

    Edit: When you set the value for a combox to '' in IE9 (I used $('select').val('') ) it empties the text in the combo box which is exactly what I need. Unfortunately only IE9 does this, so this is not an option.

    • Frédéric Hamidi
      Frédéric Hamidi almost 12 years
      To appear empty, the <select> element needs an <option> with empty text (or no <option> at all). Maybe you can add this <option> element at run-time?
    • Koen Peters
      Koen Peters almost 12 years
      yup, I could do that, but I don't want to mess with the options. I seems that this is the only option though. sigh