sarsnake
sarsnake

Reputation: 27723

Adding an item to drop down list with Jquery at a certain index

Is this possible?

I use append like this

$(".ddl").append($("<option></option>").val("").text("Select"));

But this appends it at the end....

Upvotes: 15

Views: 24410

Answers (4)

an alternative :

  <select name="nb_wanted">
    <option value="1" selected>1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="10">10</option>
    <option value="20">20</option>
    <option value="50">50</option>
    <option value="100">100</option>
  </select>

jQuery :

    var new_option = 15;

    $('select[name="nb_wanted"] option').removeAttr("selected");

    var options_len = $('select[name="nb_wanted"] option').length;

    for (var i = 0; i < options_len; i++) {

          var val = $('select[name="nb_wanted"] option').eq(i).val()*1;

          if( val > new_option ){

                if( i != 0 && ( $('select[name="nb_wanted"] option').eq(i-1).val()*1 ) != new_option ){


                    $('select[name="nb_wanted"] option').eq(i)
                    .before('<option value="'+new_option+'" selected>'+new_option+'</option>');

                    break;
                }
                else if( i != 0 && ( $('select[name="nb_wanted"] option').eq(i-1).val()*1 ) == new_option ){

                    $('select[name="nb_wanted"] option').eq(i-1).prop( "selected", true );

                    break;
                }

          }
          // END IF if( val > new_option )

    }
    // END FOR

Hope to help someone ...

Upvotes: 0

Jaider
Jaider

Reputation: 14924

If you already have the dll like var dll = $(".dll")

dll.children("option").eq(2).before($("<option></option>").val("").text("Select"));

Upvotes: 0

Niels
Niels

Reputation: 49919

if you want to add on like index 2 you can do this:

$(".dll option").eq(2).before($("<option></option>").val("").text("Select"));

this means, select index 2, and put the new option before that one.

Upvotes: 28

gilly3
gilly3

Reputation: 91587

Find the option at .eq(n) to specify the index you want the new option at. Then use .before() to insert the object. (See also .insertBefore(), .insertAfter(), or .after())

$(".ddl option").eq(n).before($("<option></option>").val("").text("Select")); 

Upvotes: 2

Related Questions