0

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.

5 Answers 5

1

.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

Sign up to request clarification or add additional context in comments.

2 Comments

One question, do I need to set a var for it? Is $("#selectbox").val($("#selectbox").children().first().val()) fine?
@ComputerUser yes it is fine but since the selector is used twice it is better to cache the the element
0
$("#selectbox").val($("#selectbox option:nth-child(0)").val());

Where 0 can be any number, of course

Comments

0

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);

Comments

0

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)

Comments

0

using javascript:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.