Tyler L
Tyler L

Reputation: 845

Select the value of <select> using Jquery

I'm getting all the option drop downs like so

var options = $(".options");

Then I try a simple jquery .val to select the second option

options[0].val("1")

And I get the following error

options[0].val is not a function

Notes:

console.log(options[0]); // returns <select>...</select>

Update Edit

https://codepen.io/TylerL-uxai/pen/NaxyJK?editors=1010 Relevant code is near the bottom --> listsDropDown

Upvotes: 1

Views: 56

Answers (3)

Tyler L
Tyler L

Reputation: 845

$(".options") is document.getelementbyclassname which returns an HTML Collection instead of an array. To convert it to array, you use slice and call.

  var optionsArr = $(".options");
  optionsArr = [].slice.call(optionsArr);
  optionsArr.forEach(function (item, index){ 
    $('.selectList'+index+' option[value='+index+']').attr("selected", "selected");
  });

For more detail, see this answer Using forEach on an array from getElementsByClassName results in “TypeError: undefined is not a function”

Upvotes: 0

forqzy
forqzy

Reputation: 389

There are different methods to set the selection of an option:

1. $("#select_id").get(0).selectedIndex=1;  
2. $("#select_id").val(4);   
3. $("#select_id option[text='jQuery']").attr("selected", true);

Upvotes: 1

Shiladitya
Shiladitya

Reputation: 12161

Here you go with a solution https://jsfiddle.net/9tao32gm/

$('select option[value="2"]').prop("selected", "selected");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
  <option value="1">1</option>
  <option value="2">2</option>
</select>

If you are using jQuery version < 1.6 then use attr instead of prop

$('select option[value="2"]').attr("selected", "selected");

Hope this will help you.

Upvotes: 2

Related Questions