Insert multiple values in component

Asked

Viewed 182 times

2

well guys, I’m facing the following problem:

I have to set several values in one that is using the plugin below.

to set only one value I am using the following syntax

$("#s").select2('val',1);

now how can I insert more than one value?

Select2

  • You can check in the examples.: https://select2.github.io/examples.html#data

  • So man, I’m already basing myself on doc, I took a dump and did not succeed @Tiago Gomes

  • In the question you do not have this information, I suggest you report what you tried and what error has arisen. Putting an example in jsfiddle also helps in parsing constriction.

2 answers

2

You can do as follows below, using a variable data with the values of select, and if you want to select more than one item at a time in the dropdown and just add the attribute multiple="multiple" in your select:

HTML:

<select id="s" multiple="multiple">
</select>

JS:

var data = [
  { id: 0, text: 'enhancement', selected: true},
  { id: 1, text: 'bug' },
  { id: 2, text: 'duplicate' },
  { id: 3, text: 'invalid' }, 
  { id: 4, text: 'wontfix', selected: true}
];

$("#s").select2({
  data: data
});

Where in this Json object id’s represent the values of the select options, and the text’s the texts to be displayed.

Link to test.

  • then @Yure Pereira, this solution you gave me had already tried, but I did not succeed. I need something like that https://select2.github.io/examples.html#tags

  • I need this <select> to appear with the values I set in js

  • Thus: https://jsfiddle.net/YurePereira/69p84xyo/

  • You are wanting to select more than one item at a time?

  • If so, just add the attribute Multiple="Multiple" in select.

  • not @Yure Pereira, I want js power to set a value and in my html appear these values already selected..

  • Uses "Selected: true" on the items you want to leave selected, as in the example.

  • 1

    This is @Yure Pereira, I tried to use this rule but it didn’t work. follow the code I implemented $("#select option[value=" + 3 + "]").prop("selected", true);

Show 3 more comments

0


For those who ever need I implemented the following code and managed to get the result I wanted..

var values = "1,2,3"

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

$("#select").trigger("change");

Browser other questions tagged

You are not signed in. Login or sign up in order to post.