JQuery adds an empty option to the top of the list and makes the existing dropdown menu selected

So I have a drop down list

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

Here is what I would like

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

Trying to add an empty parameter before this and set it to this, you must force the user to select a value from the source list, but it must be empty when they see the parameter that they should select.

Attempt but not working

 // Add blank option var blankOption = {optVal : ''}; $.each(blankOption, function(optVal, text) { $('<option></option>').val(optVal).html(text).preprendTo('#theSelectId'); }); 

and I tried this but clears other values

 $('#theSelectId option').prependTo('<option value=""></option>'); 
+56
jquery select drop-down-menu
Jul 01 '09 at 19:12
source share
3 answers

This worked:

 $("#theSelectId").prepend("<option value='' selected='selected'></option>"); 

Firebug Output:

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

You can also use .prependTo if you want to reorder:

 ​$("<option>", { value: '', selected: true }).prependTo("#theSelectId");​​​​​​​​​​​ 
+136
Jul 01 '09 at 19:15
source share

Javascript based solution:

document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);

example: http://codepen.io/anon/pen/GprybL

+3
Sep 23 '15 at 14:06
source share

$ ('# theSelectId option'). prependTo ('');

worked for me (safewebsolution.com)

0
May 7, '19 at 7:22
source share



All Articles