質問

I have a select element which is decorated by Select2 via the SonataAdminBundle.

I am trying to listen to the change event. The ID of my select tag is "categorySelector".

This does not work:

var test = $('#categorySelector');

$(test).change(function() {

    var theSelection = $(test).select2("val");
    //$('#selectedID').text(theID);
   console.log(theSelection);
});

How do I do this?

役に立ちましたか?

解決

I think this should work for you...

$('#categorySelector').on("change", function(e) {
    var theSelection = e.val();
    console.log(theSelection);
}); 

他のヒント

All public events are relayed using the jQuery event system, and they are triggered on the element that Select2 is attached to. You can attach to them using the .on method provided by jQuery:

$('#categorySelector').on('select2:select', function (e) {
  // Do something
});

When select2:select is triggered, data from the selection can be accessed via the params.data

In param.data you received object like:

{selected: true, disabled: false, text: "India", id: "101", title: "", …} 

then you can simple apply text or id property.

$('#categorySelector').on('select2:select', function (e) {
    var theSelection = e.params.data.id;
    console.log(theSelection );
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top