Почему select2 несколько значений массива для объединения при клонировании - PullRequest
0 голосов
/ 11 июля 2019

Когда я отправляю форму, данные select2 множественные объединяются в один массив.

AAA

Array ( [0] => 2 [1] => 3 [2] => 1 [3] => 3 [4] => 5 )

BBBB

Array ( [0] => 2 [1] => 3 [2] => 1 [3] => 3 [4] => 5 )

Как сделать?Выберите2 несколько данных для каждой строки отдельно.

форма результат

$(".selectReason").select2({
    multiple: true
  }).val();
$(".selectReason").val("").trigger("change");

$(".btnAdd").on("click", function() {
  $(".selectReason").select2("destroy");
  var row = $(".item").find("tbody").find("tr:last");
  var clone = row.clone();

  clone.find("input, select").attr("disabled", false).val("");
  clone.find("td:last").show();
  clone.find(".btnRemove").click(function() {
    $(this).closest("tr").remove();
  });
  row.after(clone);
  $(".selectReason").select2({
    multiple: true
  });
  clone.show();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>

<div class="row">
    <a href="javascript:void(0)" class="btnAdd">+ Add Item</a>
        <table class="table item">
          <thead>
            <tr>
              <th>Name</th>
              <th width="15%">Reason</th>
              <th>#</th>
            </tr>
          </thead>
          <tbody>
            <tr>
              <td>
                <input type="text" name="name[]" required>
              </td>
              <td>
                <select class="selectReason" name="reason[]">
                  <option value="1">AAAA</option>
                  <option value="2">BBBB</option>
                  <option value="3">CCCC</option>
                  <option value="4">DDDD</option>
                  <option value="5">EEEE</option>
                </select>
              </td>
              <td style="display:none;">
                <button class="btnRemove">-</button>
              </td>
            </tr>
          </tbody>
        </table>
    <button class="btn btn-success" name="btnInsert">
      <i class="fa fa-check mr-2"></i>OK
    </button>
</div>

...

1 Ответ

0 голосов
/ 11 июля 2019

Попробуйте приведенный ниже код. Я добавил детали в код.

Код jQuery.

  clone.find("input, select").attr("disabled", false).val("");

  //Add the code to replace the name attr of input field.
   clone.find("input,select").each(function() {
                        /*When click on add row button replace the name attr
                            second row to reason[1][] - will append all the option value of second row 
                            third row to reason[2][] - will append all the option value of third row 
                            ----
                            etc
                        */
                        this.name = this.name.replace(/\[(\d+)\]/,function(str,p1){return '[' + (parseInt(p1,10)+i) + ']'});

   });

HTML-код.

<!-- before you are adding all selected item in single array reason, change the name attribute to reason[0][] -->
                <select class="selectReason" name="reason[0][]">
                  <option value="1">AAAA</option>
                  <option value="2">BBBB</option>
                  <option value="3">CCCC</option>
                  <option value="4">DDDD</option>
                  <option value="5">EEEE</option>
                </select>
              </td>

PHP-код.

if(isset($_POST['name'])){

    $name = $_POST['name'];
    $reason = $_POST['reason'];

    for($i=0; $i<count($name); $i++){

        //value of name by row
        echo $name[$i].'<br/>';

       //Onsubmit get the value of select option seperated by each row
        echo "<pre>";
        print_r($reason[$i]);

    }
}

Выход -

AAA
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
BBB
Array
(
    [0] => 2
    [1] => 3
    [2] => 4
)
CCC
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
)
...