15
<select name="name">
    <option>Select an option.</option><br/>
    <option>A</option><br/>
    <option>B</option><br/>
    <option>C</option><br/>
</select>

HTML5 has required="required", and this is the kind of effect I want with the dropdown above. I don't want the user to select "Select an option", only "A", "B", or "C". I know I could set a default value of A and just remove the "Select an option" option entirely, but I don't want users to click haphazardly without reading the options available.

Can this be done with HTML and/or JS?

gator
  • 3,465
  • 8
  • 36
  • 76

3 Answers3

20

edit: this code is only to force users to choose a valid option, instead of the one by default... validation for submit/change/etc should be added

You should just disable the first option and setting it as selected by default:

<select name="name">
  <option disabled="disabled" selected="selected">Select an option.</option>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>

That should do the trick, demo here http://jsfiddle.net/pixshatterer/Q27HX/

pixshatterer
  • 979
  • 6
  • 12
6

If you use the Validation plugin (here: http://jqueryvalidation.org/) and update your <select> to supply value on each <option>, it will prevent form submission if the "empty" value is selected:

<select name="name" required>
    <option value="">Select an option...</option>
    <option value="A">A</option>
    <option value="B">B</option>
    <option value="C">C</option>
</select>

It's also worth noting that the only valid child elements of a <select> is either <optgroup> or <option>, so remove those <br />s.

If jQuery is not an option, you could always add an onclick to the select or an onsubmit to the form and do a quick check on an empty string (or whatever you set the default value to).

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
2

Just give display:none to the element option and disabled=disabled. Thanks to @pixshatterer

http://jsfiddle.net/Xh9nh/4/

EDIT : Put visibility:hidden by mistake.

Abijeet Patro
  • 2,842
  • 4
  • 37
  • 64