SBB
SBB

Reputation: 8970

Select2 Programmatic Access

I am using jQuery Select2 and I am running into an issue setting a value and triggering an event.

I have a simple select2 dropdown hooked up to an Ajax source. This works perfectly fine.

I also have an event waiting for a select2 option to be chosen:

 // On project select, we add the projects to the list along with the parties
$('.projSearch').on("select2-selecting", function(e) {

    // Set the value of the project
    var projectID = e.val,
        table = '';

        alert(projectID);
        console.log(e);

      ...

When using the select2 dropdown like normal, this event works fine. It detects the data of the option you select.

However, I am also including a button on the page that allows a user to set the data of the field. It sets the data just fine, however it never triggers the event select2-selecting.

I tried passing the data along with the event but not matter what when the select2-selecting event is fired, it returns undefined.

$(document).on("click", "[name=addProject]", function() {

    // Set the vars
    var projectName = $(this).attr('projectname'),
        projectID = $(this).attr('projectid'),
        projectNameLong = projectName + ' ('+projectID+')';

    // Add the project to the list  
    $("[name=projects]").select2("data", [{id: projectID, text: projectNameLong}]).trigger("select2-selecting", {val: projectID, data: {id: projectID, text: projectNameLong}});

});

How can I pass data along with the trigger to I can access it within the event?

Thanks for any info!

Upvotes: 1

Views: 686

Answers (1)

Kevin Brown-Silva
Kevin Brown-Silva

Reputation: 41671

Select2 normally triggers the select2-selecting event by creating a $.Event object with the custom data containing the val and data attributes that you are looking for. The second parameter of .trigger will allow you to get extra data directly from within the event handler, but it doesn't attach it to the event object.

$(document).on("click", "[name=addProject]", function() {
    // Set the vars
    var projectName = $(this).attr('projectname'),
        projectID = $(this).attr('projectid'),
        projectNameLong = projectName + ' ('+projectID+')';

    // Create the data object
    var data = {
        id: projectID,
        text: projectNameLong
    };

    // Create the custom event object
    var evt = $.Event("select2-selecting", {
        val: data.id,
        data: data
    });

    // Add the project to the list  
    $("[name=projects]")
        .select2("data", [data])
        .trigger(evt);
});

This should replicate the original select2-selecting event for you and allow you to reuse your event handler.

Upvotes: 2

Related Questions