Check what options are selected in dropdown javascript

Viewed 33

so i need to check which options are selected from select1 and select2 code:

<select id="select1">
  <option value="val_a1"> abc </option>
  <option value="val_b1"> abc </option>
  <option value="val_c1"> abc </option>
</select>
<select id="select2">
  <option value="val_a2"> abc </option>
  <option value="val_b2"> abc </option>
  <option value="val_c2"> abc </option>
</select>
1 Answers

While this question needs more clarification, this is what you can do the least to get the selected option (the text) and value (the value attribute).

  1. Get the select element
  2. Get the options list using the option property to get the options
  3. Use selectedIndex long for the index value of the selected option
  4. Use the onchange event to trigger the function when an option is selected (change)

var e = document.getElementById("select1");
function onChange() {
  var value = e.value;
  var text = e.options[e.selectedIndex].text;
  console.log(value, text);
}
e.onchange = onChange;
onChange();
<select id="select1">
  <option value="val_a1"> abc </option>
  <option value="val_b1" selected="selected"> def </option>
  <option value="val_c1"> ghi </option>
</select>

Related