Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add blank option to top of list and make selected to existing dropdown

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>'); 
like image 708
Phill Pafford Avatar asked Jul 01 '09 19:07

Phill Pafford


People also ask

How to add options dynamically in jQuery?

Method 1: Append the option tag to the select box The option to be added is created like a normal HTML string. The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection.

How to add options in dropdown using jQuery?

Add options to a drop-down list using jQuery. JavaScript Code: var myOptions = { val1 : 'Blue', val2 : 'Orange' }; var mySelect = $('#myColors'); $. each(myOptions, function(val, text) { mySelect.

How can select Hide option in jQuery?

Try this: $("#edit-field-service-sub-cat-value option[value=" + title + "]"). hide();

What is option in jQuery?

The jQuery Select Option is to control the multiple attributes and content for the user input information. It is special attributes used mostly in the dropdown list. It helps to user for reference of the input information or content.


1 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 could also use .prependTo if you wanted to reverse the order:

​$("<option>", { value: '', selected: true }).prependTo("#theSelectId");​​​​​​​​​​​ 
like image 139
Sampson Avatar answered Oct 03 '22 12:10

Sampson