Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add an option in the beginning?

I have html select,

<select id="myselect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>

I need to add new option in this select. If I try like this:

$('#myselect').appendTo($('<option>my-option</option>')); 

the my-option have added to the end

<select id="myselect">
    <option>1</option>
    <option>2</option>
    <option>3</option>
    <option>my-option</option>
</select>

How can I add an option in the beginning (as first)? Like this:

<select id="myselect">
    <option>my-option</option>
    <option>1</option>
    <option>2</option>
    <option>3</option>
</select>
like image 353
cackle Avatar asked May 09 '11 08:05

cackle


People also ask

How do you add dynamic options?

Add Options Dynamically To Select Element Inside the loop, create an option element and store in the variable called option. Then, set a value attribute to the option element and assign its value to the value of the property from the countriesData object on each iteration.

How do I append select options?

Method 1: Append the option tag to the select box 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. Hence the option is added to the select element.


3 Answers

In POJS you'd use insertBefore(), e.g.

var select = document.getElementById('mySelect');
var opt = new Option('', 'my-option');
select.insertBefore(opt, select.firstChild);
like image 40
RobG Avatar answered Sep 22 '22 06:09

RobG


First, you mean append, rather than appendTo. append adds the content of the parameter to the selection; appendTo appends the selection to the element designated in the parameter.

Second, perhaps intuitively, you can use prepend:

$('#myselect').prepend($('<option>my-option</option>')); 
like image 99
lonesomeday Avatar answered Sep 20 '22 06:09

lonesomeday


Use prependTo()

$('#myselect').prependTo($('my-option'));//typo? 
You might have meant this

$('#myselect').prepend($('<option>my-option</option>'));  

http://api.jquery.com/prependTo

http://api.jquery.com/prepend/

But your code is actually the other way around. This might be a typo. In any case, the methods available are prepend() and prependTo()

like image 39
JohnP Avatar answered Sep 22 '22 06:09

JohnP