Question

I'm having trouble successfully listening to a change on a select2 list created with d3.js

list = d3.select('.root').append('input').attr('type', 'hidden');

$(list).select2({
    placeholder: "Default",
    data: { results: data, text: 'text' },
    matcher: function(term, text, datum) {
        return text.toUpperCase().indexOf(term.toUpperCase())>=0 || datum.type.indexOf(term.toLowerCase())>=0;
    }
});

This successfully creates the select2 list and I'm able to choose values.

However, I'm unable to bind a function to the change event, which I believe I should be able to like this:

list.on('change', function(){
    console.log('Selected: ' + $(this).val());
});

Am I able to do this or do I need to explicitly use a selector for the input element?

$('.root > input').on('change', function(){
    console.log('Selected: ' + $(this).val());
});

See a (non) working fiddle here :)

http://jsfiddle.net/LbLjc/1/

Était-ce utile?

La solution 3

The correct way to do this is to iterate over the items in the d3 object and attach the handler to all of them:

list.forEach(function(elem) {
  $(elem).on('change', log)
});

Working fiddle: http://jsfiddle.net/LbLjc/3/

If you are confident you only want the first one, you can shorten it to:

$(list[0]).on('change', log);

Autres conseils

Try to use event delegation here since your input elements have been added dynamically to the DOM:

$('body').on('change', '.root > input', function(){
    console.log('Selected: ' + $(this).val());
});

Since your ellements are created dynamically, you should use event delegation for that

$('.root').on('change',"input", function(){
 console.log('Selected: ' + $(this).val());
});
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top