0

I have a problem, here I use the selectpicker plugin from Bootstrap to select more than one, here I want to make a modal edit where it retrieves data from the previous data, which is a matter of previous data in the form of an array of how I set the value in the selectpicker this is my response data

0: {some data}
1: {some data}
2: Array(2)
0: "6"
1: "18"

How do i set the value in selectpicker with data from index array 2

this my HTML

<select class="selectpicker" name="loan_duration[]" id="loan_duration" class="form-control" multiple>
    <option value="6">6</option>
    <option value="9">9</option>
    <option value="12">12</option>
    <option value="15">15</option>
    <option value="18">18</option>
    <option value="21">21</option>
    <option value="24">24</option>                                 
</select>
Mukund Bharti
  • 251
  • 4
  • 19
misry
  • 341
  • 2
  • 4
  • 14
  • Does this answer your question? [How to set selected value on select using selectpicker plugin from bootstrap](https://stackoverflow.com/questions/14804253/how-to-set-selected-value-on-select-using-selectpicker-plugin-from-bootstrap) – N69S Dec 06 '19 at 08:13

3 Answers3

0

You could to something like this (if I understand your question correctly):

<option value="6" {{ in_array(6, $array) ? 'selected' : '' }}>6</option>

More about PHP in_array() method.

KiprasT
  • 370
  • 5
  • 14
0

Use @if @endif if the value is in array then add selected attribute

<select class="selectpicker" name="loan_duration[]" id="loan_duration" class="form-control" multiple>
              <option @if (in_array("6", $response[2])) "selected" @endif value="6">6</option>
              <option @if (in_array("9", $response[2])) "selected" @endif value="9">9</option>
              <option @if (in_array("12", $response[2])) "selected" @endif value="12">12</option>
              <option @if (in_array("15", $response[2])) "selected" @endif value="15">15</option>
              <option @if (in_array("18", $response[2])) "selected" @endif value="18">18</option>

                          </select>
Presmelito
  • 202
  • 3
  • 17
0

You can directly pass the array containing the values as a parameter to the val() method of your select element.

var data = [{}, {},
  [6, 18]
];

$('#loan_duration').val(data[2]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<select class="selectpicker form-control" name="loan_duration[]" id="loan_duration" multiple>
  <option value="6">6</option>
  <option value="9">9</option>
  <option value="12">12</option>
  <option value="15">15</option>
  <option value="18">18</option>
  <option value="21">21</option>
  <option value="24">24</option>
</select>

This will work with or without the bootstrap plugin.

David
  • 6,695
  • 3
  • 29
  • 46