Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get select option by value using javascript

I have selection menu:

<div class="selector">
<select>
<option value="valueA">Value A</option>
<option value="valueB">Value B</option>
<option value="valueC">Value C</option>
</select>
</div>

and I need Javascript (no jquery!) to get option by value and change it's text (innerHtml)

for example when I run the function I need to get option with the value "valueB" from class "selector" and change it's text to Value Whatever.

like image 547
Simon Avatar asked Nov 09 '14 19:11

Simon


People also ask

How do you get the selected option value?

The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How do I get the selected option value in TypeScript?

First, create the template variables for dropdown using #teams . Use the event binding to listen for the change event and link with the onSelect method. The onSelect method receives the reference variable and takes the value of the dropdown element. Next, create the onSelected(value) method in the TypeScript file.

What is option value in JavaScript?

Definition and UsageThe value property sets or returns the value of the option (the value to be sent to the server when the form is submitted). Tip: If the value property is not specified for an option element, then the text content will be sent to the server when the container form is submitted.


1 Answers

I'd suggest:

document.querySelector('div.selector option[value=valueB]').text = 'Value whatever';

Further, in answer to the questions raised in comments:

I need to get only the second <option> element with the same value as the other <option> and change text only to the second <option>

To get all <option> elements with value="valueB":

document.querySelectorAll('div.selector option[value=valueB]')[1].text = 'Value whatever';

The differences are that document.querySelector() returns only the first (if any) match to the supplied CSS selector, as a node (rather than a NodeList), so properties are available directly; document.querySelectorAll() returns all the elements, in a NodeList, that match the supplied selector; so we have to use the (zero-based) index ([1]) to retrieve a specific node, and get/set its properties.

like image 155
David Thomas Avatar answered Oct 18 '22 13:10

David Thomas