Custom Fields
Re-Envisioned
Support General Select Advance triggers .on('change') event twice

  • Creator
    Topic
  • #13205
    Resolved pluginoven
    Participant

    When jQuery is used to detect a change in value for a select-advanced field type the change event it triggered twice.

    For example, for a slelect-advance with a field id of my_field_id:

    $(document).on('change', '#my_field_id', function() {
         console.log('phones ringing, dude.');
    }

    will fire the console.log twice on any change in selected values.

    Why might this be and is there a currently known work-around?
    Edit: Seems this is better documented at select2:
    https://select2.org/programmatic-control/events

Viewing 2 replies - 1 through 2 (of 2 total)
  • Author
    Replies
  • #13258
    Anh Tran
    Keymaster

    Hi,

    We are using a technique that preserves the order of selected options in select2. This technique triggers an event change after it reorder the options. So that might causes the duplication.

    In reality, you might cache in the event listener to make sure your code run only once.

    #13304
    pluginoven
    Participant

    Perfect, thank you.
    Jut for the record, the event listener was cached as follows:

    let select_cache = null
    $(document).on('change', '#my_field_id', function(event) {
        if (!select_cache) {
            setTimeout(() => {
                //do your thing
                console.log('phones ringing, dude.');
                //clear the cache
                select_cache = null
            }, 100)
        }
        select_cache = event
    }

    Issue can be marked as resolved.

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.