简体   繁体   中英

Get value from options to javascript in Rails

In view , I have code

 <tr>
  <td><%= form.label :category_id %></td>
  <td><%= form.select :category_id, options_from_collection_for_select(Category.all, 'id', 'name'), :class => 'form-control',:onchange => 'addCategory(category_id)'%></td>
</tr>

and script

<script type="text/javascript">
  $('select').change(addCategory);
  function addCategory(category_id){
    alert(category_id.value);
 }
</script>

I don't know how to get value option selected to use as input function addCategory().

Try this one

<script type="text/javascript">
  $('select').change(addCategory);
  function addCategory(){
    alert($(this).val());
 }
</script>

$(this) refers to the new selected element, with val() method you get its value

Vanilla approach.

document.querySelector('select').addEventListener('change', function(e){
  alert(e.target.value);
})

or define an addCategory(e) function, and pass it as a callback to change event.

function addCategory(e) {
  alert(e.target.value);
}

document.querySelector('selector').addEventListener('change', addCategory);

e.target is the same with $(this) on Ursus' answer.

 document.querySelector('select').addEventListener('change', function(e){ alert(e.target.value); }) 
 <select> <option value="1">Volvo</option> <option value="2">Saab</option> <option value="3">Opel</option> <option value="4">Audi</option> <option value="5">Lada</option> </select> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM