Njall
Njall

Reputation: 191

How to send the selected option from a select_tag to an onchange javascript function

I have a select_tag that, when changed, calls a javascript method using onchange.

I would like the value of the option selected in the select_tag to be sent as a parameter to the method.

<%= link_to_function select_tag :search_type, options_for_select(search_type_options, @search_type), :onchange => "showSearchables( **the option selected ** );return false;" %>

Upvotes: 2

Views: 2868

Answers (3)

Bob FiveThousand
Bob FiveThousand

Reputation: 137

In terms of HTML/JavaScript, this is pretty straight-forward:

<form>
  <select onChange="getVal( this )">
    <option>one</option>
    <option>two</option>
    <option>three</option>
  </select>
</form>

<script type="text/javascript">
  function getVal( oSelect ) 
  {
    var selectedValue = oSelect.options[ oSelect.selectedIndex ].value;
  }
</script>

Upvotes: 0

Yuriy Zubarev
Yuriy Zubarev

Reputation: 2871

Without JQuery, you can change the option selected to:

this.options[this.selectedIndex].value

Upvotes: 1

Baldrick
Baldrick

Reputation: 24350

If using JQuery, you can use

:onchange => "showSearchables($(this).val());"

Upvotes: 1

Related Questions