Search code examples
javascriptjqueryruby-on-railsselect-options

Get attribute from model of selected option


I have an employee dropdown that lists all the employees. I want to be able to select an employee and get the address of the employee from the model so that I may display it. the following is the code of my collection_select.

<div class="form-group col-md-2 field">
<%= form.label :employee_id %>
<%= form.collection_select :employee_id, Employee.all, :id, :full_name,{:prompt=>"Select Employee"},{:id=>"emp_select",class:"form-control",:onchange=>"getEmployee();"} %>
</div>

Next is the code I am using to grab the value of the employee that was selected and it does work.

function getEmployee() {
    var selectedVal=$('#emp_select option:selected').val();}

From here what do I do to get the address of the employee that was selected?


Solution

  • Add address to option data-attribute:

    <%= form.select :employee_id, 
      options_for_select(Employee.all.map { 
        |e| [e. full_name, e.id, { 'data-address' => e.address  }] 
      }), 
      { prompt: "Select Employee" }, 
      { id: "emp_select", class: "form-control", onchange: "getEmployee();" } %>
    

    On change get it with js:

    function getEmployee() {
      var selectedVal=$('#emp_select option:selected').data("address");}
    

    And insert it to needed place