1

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

1

3 Answers 3

2

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.

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

3 Comments

How does this work on an array of options? Where my variable options has more than one <select>? The problem is it's saying .val and .attr are not functions of option[0]
@TylerL Please share your HTML code, then only I can help you better.
Thank you so much @Shiladitya. codepen.io/TylerL-uxai/pen/NaxyJK?editors=1010 // listDropDown
1

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

Comments

0

$(".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”

1 Comment

Code-only answers are discouraged because they do not explain how they resolve the issue in the question. Consider updating your answer to explain what this does and how it addresses the problem - this will help not just the OP but others with similar issues. Please review How do I write a good answer

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.