简体   繁体   中英

foreach add data into selectpicker

I want to be able to complete this selectpicker with options, but this does not add the options with that js function. I try with class select and it works fine but with selectpicker does work.

HTML

  <select class="selectpicker form-control" data-style="btn-default"
        data-placeholder=".:: Dirección ::." tabindex="-1"
       data-minimum-results-for-search="10"  id="address" name="address">
  </select>

JS

$.each(response.result['address1'], function(k, v) {
    $('<option>').val(v.c_bpartner_location_id).text(v.address1).appendTo('#address');
 }); 

PHP

$address1[] = array();
foreach($records as $row) {
    $direccion = $row - > direccion;
    array_push($address1, array("address1" => $row -> address1,
        "c_bpartner_location_id" => $row -> c_bpartner_location_id))
}
$data['result'] = array(
    'direccion' => $direccion,
    'address1' => $address1);

What could be the mistake?

The callback for the $.each function has two parameters: key and value or index in array and value.

In your case, I assume you have in direccion and address1 values of scalar types. For your example, imagine we have an object like this:

$data = [
  'result' => [
    'direccion' => 'left',
    'address1'  => 'Street 1, City',
  ]
];

So for your JS code, you should use this code:

$.each(response.result['address1'], function(k, v) {
    $('<option>').val(v).text(v).appendTo('#address');
 }); 

Because for each part of the associative array $data['result'] you will get key and value pairs ( k , v ):

k: direccion, v: left
k: address1, v: Street 1, City

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM