.val() takes hardcoded values but not variables

Hello,

I’ve been trying for hours now to find out why I can’t asign multiselect values from a variable.

function FillFieldsForEdit(deal) {
    jQuery('#edit_deal_id').val(deal.bundle_id);
    jQuery('#deal_name').val(deal.bundle_name);
    jQuery('#deal_type').val(deal.bundle_type).change();

    let dealsWith = [];

    for (let dealWith of deal.bundle_with.split(',')) {
        dealsWith.push(dealWith);
    }
    
    jQuery("#deal_counts_with").val(dealsWith);
    jQuery("#deal_counts_with").trigger('change');

    jQuery("#deal_start").val(deal.bundle_start);
    jQuery("#deal_end").val(deal.bundle_end);
}

If I replace the dealsWith variable with a single hardcoded value or hardcoded array it works. But nothing changes with the code above. When I console log dealsWith it shows a normal array [‘123645’,‘125920’] .

Does anyone have any idea why? I’m working on a plugin in wordpress 6.1.1 and Woocommerce 9.0.2
Thank you.

I’m having the same problem with a select2() in a bootstrap modal window. I was able to get the type-ahead to work, but I can’t initialize it to the existing value for a user using .val();

Were you ever able to get this working?

Hey,

It took a while but I found out past me had decided to exclude selected values from the select list.
So when I wanted to select it with .val(array[]) it just couldn’t find the matching options from that array.

I’m not quite sure about your problem. But .val() takes a single value or an array. To assign it on the select2 you trigger the change event.

jQuery("#element").val(array[]);
jQuery("#element").trigger('change');