Reputation: 2210
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?
Upvotes: 0
Views: 3800
Reputation: 83
While all the above mentioned solutions work, I didn't wanted to use on Change
event and then I noticed that
var text = $('.lender_field_code').select2("data").text();`
returns the selected item plus whatever comes after it as array like, so I used the below solution
var text = $('.lender_field_code').select2("data")[0].text();
index[0] is the selected item
and if you want the value, well you don't need on change
even,
Select2 JS directly sets the .val()
attribute, you can get it on the fly like this
var value= $('.lender_field_code').val();
and if you have multiple selects
that use the Select2
, then you must specifiy your target with unique name, id, class, etc. or loop through them.
Upvotes: 0
Reputation: 11876
try this
$( document ).ready(function() {
$( ".lender_field_code" ).change(function() {
alert( $(this).find("option:selected").text() );
});
});
Upvotes: 0
Reputation: 2575
You can try this too
On change
event of select with id lender_field_code
, get the selected
item and read it's val with .val()
$('.lender_field_code').change(function() {
$('#select_val').append($('.lender_field_code :selected').val());
});
Upvotes: 0