jQuery add blank option to top of list and make selected to existing dropdown
Solution 1
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 could also use .prependTo
if you wanted to reverse the order:
$("<option>", { value: '', selected: true }).prependTo("#theSelectId");
Solution 2
Solution native Javascript :
document.getElementById("theSelectId").insertBefore(new Option('', ''), document.getElementById("theSelectId").firstChild);
example : http://codepen.io/anon/pen/GprybL
Phill Pafford
Love development with PHP/Symfony/PHPStorm, iOS, PostgreSQL, Linux flavor Ubuntu, jQuery/Mobile, Foundation CSS, GitFlow AVH and HTML5 Personal Projects are Crypto Currencies, Home Automation, Mobile development, SMS/MMS and DIY electronics via Make and Hack A Day https://keybase.io/phillpafford https://onename.com/phillpafford #bitcoin: https://www.coinbase.com/phillpafford #DogeCoin: D67fwUKwKQQeL9pdbZmbWcevuAYW8XPqyz
Updated on May 07, 2020Comments
-
Phill Pafford almost 4 years
So I have a dropdown 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>
This 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 a blank option before and set it to this, want to enforce the user to select a value from the original list but would like it to be blank when they see the option they have to choose.
Trying this but not working
// Add blank option var blankOption = {optVal : ''}; $.each(blankOption, function(optVal, text) { $('<option></option>').val(optVal).html(text).preprendTo('#theSelectId'); });
and I have tried this but is clears out the other values
$('#theSelectId option').prependTo('<option value=""></option>');
-
tvanfosson almost 15 yearsIt would work with prependTo as well: $("<option value='' selected='selected'></option>").prependTo("#theSelectId");