question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Select2 triggering event don’t loading additional data

See original GitHub issue

I’m trying to load some important data on my select (select2) that will be used in other parts of the page in the future, but the Triggering Event is not loading the additional data. The code and results are shown below. If anyone has any suggestions, I’d be grateful.

$('#id_cc1').select2();
var data = {
	id: 1,
	text: 'text_default',
	text2: 'text_2',
	text3: 'text_3'
};
var newOption = new Option(data.text, data.id, true, true);
$('#id_cc1').append(newOption).trigger('change'); //until this point, everything works
$('#id_cc1').trigger({
	type: 'select2:select',
	params: {
		data: data
	}
});
console.log($('#id_cc1').select2('data')[0]['text']);// return text_default
console.log($('#id_cc1').select2('data')[0]['text2']);// return undefined

I believe the second ‘console.log’ should return: ‘text_2’.

Issue Analytics

  • State:open
  • Created 2 years ago
  • Reactions:1
  • Comments:7

github_iconTop GitHub Comments

1reaction
phantomGaming1commented, Apr 28, 2022

Hello guys. Good Morning. I create simple visual representation and a source code here: https://gist.github.com/phantomGaming1/31bde03725f2aa14d0695c741f08b7e9

select2_asd

For what I’m trying to do is first click the edit and second is get the additional data that is given in selec2 data (Please see the code for the further info).

Then about in this code: this actually working as intended and passed all additional data in params and access it. But it only works on event and not really store any data on it.

$('#id_cc1').trigger({
	type: 'select2:select',
	params: {
		data: data
	}
});

The docs said that: Notice that we manually trigger the select2:select event and pass along the entire data object. This allows other handlers to access additional properties of the selected item.

But I think the main problem is using the code $('#id_cc1').select2('data')[0]['text2'] or just $('#id_cc1').select2('data') itself when I’m manually preselecting data on remotely-sourced select2. But the code works just fine when using on remote data.

I think the best alternative solution is to have a global variable or the solution sir @luiseugenio provided. Thank you sir @luiseugenio for the replies I think this probably solve my issue.

1reaction
evandrophcommented, Apr 27, 2022

Hi @luiseugenio . Just like @evandroph , exactly same scenerio, I wanted to manually set the data in select2 (refer to this https://select2.org/programmatic-control/add-select-clear-items#preselecting-options-in-an-remotely-sourced-ajax-select2) and the problem lies that it can’t output any additional data. There must be a way/method to populate an additional data.

@phantomGaming1 Is your scenario the same? I can using exactly the same code from the link you showed. Here is a code snippet from my stimulujs controller.

bindEvents() {
    var controller = this
    this.select2.on('select2:select', function (e) {
      var data = e.params.data
      if (data.newTag) {
        controller.createSite(data)
      }
    })
  }

createSite(data) {
    var controller = this

    $.ajax({
      url: controller.data.get('url-create'),
      dataType: "json",
      type: 'POST',
      data: {
        'sites[]': {'url': data.text}
      },
      error: function (xhr) {
        let error = xhr.responseJSON.errors.map(function(error) {
          return `URL ${error.url.join(', ')}`
        })
        noty({ text: error })
        controller.select2.val(null).trigger('change') // clear selected option
      },
      success: function (response) {
        let site = response[0]
        var newSiteOption = new Option(site.url, site.id, true, true)
        controller.select2.append(newSiteOption).trigger('change')
      },
      complete: function() {
        data.newTag = false
      }
    })
  }

Take a look at the success: there I add a new option and I get it selected.

In your case, data.ID and data.TEXT returns OK. On my code, too! But if you need returns more data (in my case: anothertext key) select2 don’t load this data, only ID and TEXT

Read more comments on GitHub >

github_iconTop Results From Across the Web

Select2 triggering event don't loading additional data
I'm trying to load some important data on my select (select2) that will be used in other parts of the page in the...
Read more >
select2 doesn't trigger change event correctly - Stack Overflow
I have added a change event listener. However even when I change the option this event is not getting triggered.
Read more >
Options - Select2 - JeeSite
Can I load data into Select2 using an array? While Select2 is designed to be used ... Can I trigger an event other...
Read more >
Select2 3.5.3
Select2 3.5.3. Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.
Read more >
SCR19: Using an onchange event on a select element ... - W3C
This technique will not cause a change of context. When there are one or more select elements on the Web page, an onchange...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found