Damian Rocks Damian Rocks - 4 months ago 6
Javascript Question

How to get an option element's value by name

First, I have absolutely no knowledge in JavaScript.

I try to return the value of an option from the HTML list below.

example:


  • I have the var:
    "NAME_1"

  • I need to return string :
    "number:50640"



How is this accomplished?



<select class="form-control select-field ng-pristine ng-valid ng-not-empty ng-touched" id="upsell_product" name="upsell_product" ng-change="productSelected()" ng-options="product.id as product.name for product in products" ng-model="upsell.product_id">

<option value="" class="" selected="selected">-- Select a Product --</option>

<option label="NAME_1" value="number:50640">NAME_1</option>
<option label="NAME_2" value="number:63732">NAME_2</option>
<option label="NAME_3" value="number:32673">NAME_3</option>
<option label="NAME_4" value="number:09723">NAME_4</option>
<option label="NAME_5" value="number:23832">NAME_5</option>

</select>




Answer

This is how get value:

var selectVal=document.querySelector("select.select-field").value;

This is how bind when user selects:

document.querySelector("select.select-field").addEventListener("change",function(){

var selectVal=  this.value;

});