1

So I have this string: 93, 94 which are the references of the values of a select.

I'm trying to set these values using:

let values = "93, 94";
$('#property-categories').selectpicker('val', values);

but not working, none of the value is selected in the select control.

If I write: $('#property-categories').selectpicker('val', [93,94]);

works, any idea?

sfarzoso
  • 1,356
  • 2
  • 24
  • 65

2 Answers2

2

To turn a comma delimited string in to an array, which is the type required here, use split().

let values = "93, 94";
$('#property-categories').selectpicker('val', values.split(', '));
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • please test your code before posting.[link](http://jsfiddle.net/2ascjdyr/) – jishan siddique Oct 12 '19 at 14:32
  • @jishansiddique It already works. https://jsfiddle.net/g4y02nfa/ – Rory McCrossan Oct 12 '19 at 14:35
  • Because you used a very outdated version of selectpicker, for some reason – Rory McCrossan Oct 12 '19 at 14:35
  • @RoryMcCrossan could I ask a little more help? The issue happen again if I provide non numerical values, eg: `modern,historic,seaside,minimalist`, could you please take a look at it? – sfarzoso Oct 12 '19 at 16:45
  • 1
    Text values work too. The difference with that string is that you're using just `,` to delimit the string instead of `, ` (note the trailing space after the comma). Fix that and it works fine https://jsfiddle.net/rgkmwd9v/. – Rory McCrossan Oct 12 '19 at 16:47
  • Old but gold .... this worked for me: $('.selectpicker').selectpicker('val', data.colors.split(',')); ...... thanks dude :b – Michel Xavier Apr 15 '20 at 00:23
1

Please check this one for simple select control

var values="93,94";
$.each(values.split(","), function(i,e){
    $("#strings option[value='" + e + "']").prop("selected", true);
});

For selectpicker you need to set below code

$('.selectpicker').selectpicker();
$('.selectpicker').selectpicker('val', ['93','94']);

Check here working demo - > Click here

jishan siddique
  • 1,848
  • 2
  • 12
  • 23