javascriptruby-on-railsjquery-select2select2-rails

Get selected text select2 using javascript


I have a select2 input field which successfully i can get all my data but i want to get the test of d selected data from the dropdown list

This is my select2 input field

<%= f.input_field :lender_id, collection: Lender.all.pluck(:code, :id), id: 'lender_field_code', name: 'lender_field_code', class: 'form-control legal-service lender_field_code', prompt: 'Please Select Banker', disabled: (f.object.new_record? ? false : true ) %>

and in my javascript file i have this

var str1= $('.lender_field_code').select2("data").text();
 console.log(str1);

when i select any data it returns all d data in my select2 not what i selected. how do i solve this?


Solution

  • try this

        $( document ).ready(function() {
            $( ".lender_field_code" ).change(function() {
                alert( $(this).find("option:selected").text() );
            });
        });