0

I am able to do the following in javascript:

document.querySelector('select[name="plan_type"] option')

However, how would I get the selected option? For example:

document.querySelector('select[name="plan_type"] option:selected')

(the equivalent in jquery would be: $('select[name="plan_type"] option:selected').

  • I thought one of the main features of jQuery was compatibility with CSS3 psuedo-selectors - not sure if vanilla JS has direct access (I could be wrong - someone lemme know if I am :)) – treyBake Oct 11 '18 at 16:07
  • https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript – Aragorn Oct 11 '18 at 16:12

3 Answers3

1

We can obtain a reference to this type of element using its name:

oSelectOne = oForm.elements["select_one_element_name"];

To get the index of the selected option in the JavaScript options array of the select element, we can use the selectedIndex property of the select element object

var e =document.querySelector('select[name="plan_type"]');
var strUser = e.options[e.selectedIndex];

We can now use this index to determine the value of the selected option:

var strUser_value = e.options[index].value;

If we needed to get the text corresponding to the selected option, we would need to use the text property of the option element, instead of the value property:

var strUser_text = e.options[index].text;
Osama
  • 2,912
  • 1
  • 12
  • 15
0

QuerySelector is meant to use css selectors on the DOM, similar to jQuery, but they don't support the pseudo selectors, read on MDN

What you can do is to take a two step approach, get the element and then get the value from that element.

Like this:

var myElement = document.querySelector('select[name="plan_type"]);
var myValue = myElement.querySelector('[selected]').value;

Other general way to do this without query selector (needs id for the element), (name would do too)

var e = document.getElementById("{id_goes_here}");
var selectedValue = e.options[e.selectedIndex].value;
Aragorn
  • 5,021
  • 5
  • 26
  • 37
0

The options collection returns a collection of all elements in a drop-down list. Using the property selectedIndex to get the selected option.

let options = document.querySelector('select').options;
let text = options[options.selectedIndex].text;
Pengcheng
  • 323
  • 1
  • 5
  • Thank you for this code snippet, which might provide some limited, immediate help. A [proper explanation](https://meta.stackexchange.com/q/114762/349538) would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please [edit] your answer to add some explanation, including the assumptions you’ve made. – mhodges Oct 11 '18 at 16:16