Björn C
Björn C

Reputation: 4008

set multiple values in a select from string

I have this string:

var product = "bj,tg,ap,nl";

Now I´d like jQuery to select these values in a select2 option list. I know how to select just one:

$('#product').val('bj').trigger('change.select2');`

But how do i select all the comma separated values from that string? I guess it should look like:

$('#product').val('bj', 'tg', 'ap').trigger('change.select2');

So I need to put some ' and spaces into my string "product". How would i do that? Can i use regex?

Upvotes: 1

Views: 875

Answers (1)

Satpal
Satpal

Reputation: 133423

.val() method accepts an array for multiple option. You can use split() to create an array and pass it to .val() method.

$('#product').val(product.split(',')).trigger('change.select2');

Upvotes: 8

Related Questions