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