Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new element to select box after the first option element using JQuery

Tags:

jquery

I have a combobox with the following options

<select id="history">
    <option></option>
    <option>element1</option>
    <option>element2</option>
    <option>element3</option>
    <option>element4</option>
</select>

I'm trying to add a new option after the first option. What is the best most effective way to accomplish this I tried

<script type="text/javascript">
    $("#history").prepend("<option>sdsadas</option>").after('#history:first-child');
    $("<option>asdsad</option>").insertBefore('#history option:first-child');
//    $('option[value="sadsaddsad"]', this).after('option:first');
</script>

but none of these are working as I want.

like image 923
Elitmiar Avatar asked Aug 28 '12 07:08

Elitmiar


1 Answers

You can do it like this:

$("#history option:first").after("<option>sdsadas</option>");

This gets the first <option> tag and then inserts a new option after it.


jQuery supports two ways of inserting in a position. The above version is target.after(content) and this other way is content.insertAfter(target):

$("<option>sdsadas</option>").insertAfter("#history option:first");

Note: One uses .after() and the other uses .insertAfter().

like image 145
jfriend00 Avatar answered Nov 11 '22 07:11

jfriend00