Computer User
Computer User

Reputation: 2879

select item of a Select box by its item number in jQuery

How do I select item of a Select box by its item number in jQuery?

<select id="selectbox" style="width: 220px;">
  <option value="Option 1">Option 1</option>
  <option value="Option 2">Option 2</option>
</select>

Like:

$("#selectbox").val() = $("#selectbox").Item[0].val();

I mean I want to toggle item to set it by its number.

Upvotes: 0

Views: 87

Answers (5)

Nishad K Ahamed
Nishad K Ahamed

Reputation: 1394

using javascript:

var select=document.getElementById("selectbox")
var options=select.getElementsByTagName("option")
select.value=options[0].innerHTML

Upvotes: 0

jotaen
jotaen

Reputation: 7049

To me, this would be the clearest approach:

$("#selectbox option").eq(1).prop('selected',true);

Note, that the parameter of eq() function is treated like you would access an array. So the second element is eq(1)

Upvotes: 0

Bill Criswell
Bill Criswell

Reputation: 32941

I wanted to make this into a plugin.

;(function($){
  $.fn.setByOptionIndex = function( idx ){
    return this.each(function(){
      var $select = $(this);
      $select.val( $select.find('option').eq(idx - 1).val() );
    });
  }
})(jQuery);

Then just use it with:

$('select').setByOptionIndex(2);

Upvotes: 0

Ruben Serrate
Ruben Serrate

Reputation: 2783

$("#selectbox").val($("#selectbox option:nth-child(0)").val());

Where 0 can be any number, of course

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

.val() is a function so you cannot assign a value to it, you need to use the setter version of .val() to set an input element's value

You can access the first option's value using the index value

var $select = $("#selectbox");
$select.val($select.children().first().val())
//$select.val($select.children().eq(0).val())

Demo: Fiddle

Upvotes: 1

Related Questions