Select2 Get selected option data
Asked Answered
A

6

32

$("#e2").select2("val") returns me the value, but I wan't to get the .$listtypes['name'] . ether from data-name or from the option tag display.

I want to get the option data-name for the selected option, how can I accomplish this?

This is my option generator

foreach($core->list_types() as $listtypes){
echo "
<option 
  data-name='".$listtypes['name'] ."' 
  value='".$listtypes['id']."'>
  ".$listtypes['name'] ."
</option>";
}
Apian answered 31/10, 2014 at 17:47 Comment(0)
W
46

you can use this

$("#e2 option:selected").text();
Whiffet answered 31/10, 2014 at 17:51 Comment(0)
L
33

Try this:

$('#e2').select2('data')

return selected option data

Lycian answered 3/1, 2017 at 9:53 Comment(1)
Might be worth noting that this returns a javascript array. Documentation link:select2.org/programmatic-control/…Polky
M
9

This work for me:

On simple select2 to get label value:

$('#myVar').select2('data')[0].<name_label_from_data_input>

May be helpful do an data dump from select2 variable:

$('#myVar').on('change', function (evt) {
  if ($('#myVar').select2('val') != null){
    console.log($('#myVar').select2('data')[0]);    
  }
});

And catch your the label's name attribute.

Good luck!

Morrie answered 9/3, 2017 at 0:7 Comment(1)
I wouldn't call it the "label value" because that implies (to me) $('#myVar').val(), but your answer is very useful because from $('#myVar').select2('data')[0] one can get properties id, text, title, and the underlying option element via the property element.Allegro
L
6

You can use this script

$('#editable-select').on('select2:select', function (e) {
            var data = e.params.data;
            console.log(data);
    alert(data['text']);
});
Lint answered 25/2, 2020 at 18:8 Comment(0)
T
3

Looks that @Kishan and @xploshioOn's answers won't work on v4.0+.

Try this: $("#e2").text().trim()

Tildatilde answered 21/12, 2016 at 5:43 Comment(0)
B
0

Use the attr method .attr("data-name") on your selector.

Bernitabernj answered 31/10, 2014 at 17:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.