0

I'm trying to hack my way around some Opentext forms and I've created and array below containing my select2 objects. How do I use the array index of the object that has triggered an event? Or is there a better way to do this?

The joblink variable is a hidden element that stores a value written and read by opentext

for(var b = 0; b <= 15; b++){

            JobSelect[b] = $('#Job' + (b + 1) + 'Trans').select2({ width: '100%', Height: '100%' }).on('change', function(e){

                $(joblink[b]).val(this.value);

            });

            if ($(joblink[b]).val() != '')
            {
                $(JobSelect[b]).val($(joblink[b]).val()).trigger("change");
            }   
        }

1 Answers1

0

Here is a jsFiddle link to my suggested solution: https://jsfiddle.net/bindrid/ujna54an/3/

comments are inline:

    for (var b = 0; b <= 15; b++) {

        // in your event handler, add a second parameter
        JobSelect[b] = $('#Job' + (b + 1) + 'Trans').select2({ width: '100%', Height: '100%' }).on('change', function (e, eData) {
            // puts the selected value in the job link

            // and put the variable here
            $(joblink[eData]).val(this.value);

        });

        //If not blank,  makes what ever in job link the selected value so it will put the value back in the job link
        // seems circular.
        if ($(joblink[b]).val() != '') {

            // add b as second parameter 
            $(JobSelect[b]).val($(joblink[b]).val()).trigger("change", b);
        }
    }

However, if your only purpose is to sync the select to the link just replace the above code with this

    // set up all selects 
    $('select').select2({ width: '100%', Height: '100%' });

    $.each(joblink, function (idx, item) {
        var link = $(item).val();

        if (link.length > 0) {
            $('#Job' + (idx + 1) + 'Trans').val(link).trigger('change');

        }
    })
Bindrid
  • 3,655
  • 2
  • 17
  • 18