문제

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