How can I set the value and label of a Select2 field when another field changes?

How can I set the value and label of a Select2 field when another field changes?

NettSiteNettSite Posts: 36Questions: 11Answers: 2

Hi,

I have an application which has to allow for a user to search for an occupation, with or without an occupation_group filter.

Using a Select2 field to select a filter for the search works fine.

However, if the user decided not to use a filter, the occupation_group field needs to be set to the appropriate group for the chosen occupation.

Here is my code:

// Set the value of the title and description fields when the template changes
editor.dependent( 'occupation_id', function ( val ) {
  $.each(select_options, function( key,result ) {
    if(result.id == val) {
     editor.val('title',result.text);               // Works!
     editor.val('description',result.description);  // Works!
     //** Doesn't work**: editor.val('occupation_group_id',{value:result.occupation_group_id, label:result.occupation_group} );
     // **Doesn't work:** $('#DTE_Field_occupation_group_id').select2('data', {id: result.occupation_group_id, text: result.occupation_group});
     $('#DTE_Field_occupation').select2('close');   // Works!
     filter = '';
    }
  });
});

I have checked that the result contains the required information. "title" is a text field, and "description" is a textarea, and they are set to the correct values. "occupation_group_id" is a Select2 field.

I would really appreciate any pointers.

Answers

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    I forgot to mention that there are no error or other messages in the console.

  • allanallan Posts: 61,446Questions: 1Answers: 10,054 Site admin

    Rather than:

    {value:result.occupation_group_id, label:result.occupation_group}
    

    just pass in result.occupation_group_id (assuming that value is already in the list of options for the Select2 field).

    Allan

  • NettSiteNettSite Posts: 36Questions: 11Answers: 2

    Hi Alan,

    Thanks! Unfortunately, the value is not necessarily there, because if the user bypasses the occupation group field and goes directly to the occupation field, the occupation_group_id select doesn't have any options at all - they would normally be filled by an ajax request after a search.

    I did try with just result.occupation_group_id and it didn't work either - no doubt because the option wasn't available in the select.

    If there is no other way, I can pre-populate the occupation_group_id options as there aren't a massive number of them. That should enable your suggestion to work, right?

This discussion has been closed.