2

when clicking this select element, the inline call "onchange" should call a javascript function:

<select onchange="if (this.selectedIndex) do_something();">
  <option value=1>1</option>
  <option value=2>2</option>
</select>

basically how do i submit the option selected to 'do_something()' function? or in the function how can I obtain the option value selected?

dave
  • 14,991
  • 26
  • 76
  • 110
  • Possible duplicate of [How to pass parameters on onChange of html select](https://stackoverflow.com/questions/5024056/how-to-pass-parameters-on-onchange-of-html-select) – Andrew Sep 30 '17 at 22:07
  • Possible duplicate of [Get selected value in dropdown list using JavaScript?](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Jonathan Laliberte Sep 30 '17 at 22:09

2 Answers2

2

you may try this :

function do_something(e) {
  alert(e);
}
<select onchange="if (this.selectedIndex) do_something(this.value);">
  <option value=1>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
  <option value=4>4</option>
</select>

You may notice that i won't work for 1 because of selectedIndex which is equal to 0 for the first index (the value 1)

so more generic it can be :

function do_something(e) {
  //we make do test on the element e
  alert(e.value);
}
<select onchange="do_something(this);">
  <option value=1>1</option>
  <option value=2>2</option>
  <option value=3>3</option>
  <option value=4>4</option>
</select>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
1

function do_something(i){
  console.log(i);
}
<select onchange="do_something(this.selectedIndex);">
  <option value=1>1</option>
  <option value=2>2</option>
</select>

Try adding it as a parameter in the do_something function.

Temani Afif
  • 245,468
  • 26
  • 309
  • 415