user10332687
user10332687

Reputation:

Option:selected in javascript

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').

Upvotes: 0

Views: 238

Answers (3)

Pengcheng
Pengcheng

Reputation: 323

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;

Upvotes: 0

Osama
Osama

Reputation: 3030

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;

Upvotes: 1

Aragorn
Aragorn

Reputation: 5289

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;

Upvotes: 0

Related Questions