Selectpicker: show already marked options when page is loaded - AJAX JSON

Asked

Viewed 67 times

1

I’m using the Bootstrap-Select (selectpicker) and I would like to know how to make the options inside this selectpicker already marked when the page is loaded and the same is clicked.

In case I’m trying to use the method $('.selectpicker'). selectpicker('val', ['values']); so that the selectpicker shows options already marked according to data received in JSON format from a php script that passes the result to ajax.

In case I have two tables in Mysql: table cars and table colors

table colors:

corID | cor      | 
------------------
01    | Branco   |
02    | Cinza    |
03    | Preto    |
04    | Vermelho |
------------------

table cars:

carroID | carro  | Cor (Foreing Key) e select multiple
-------------------------------------------------------
01      | Gol    | 01, 02, 03
02      | Fiesta | 02, 03, 04
03      | Golf   | 01, 03, 04
-------------------------------------------------------

Based on the two tables above, I would like the dropdownlist (selectpicker) field, already marked with the options White, Black, Grey referring to the ID record 01 for example. In this case the user opening the modal would be able to update this dropdownlist keeping or not the options already marked.

In this case, below follows a jquery function that is executed when a button is clicked and a modal is opened. When this occurs, data attached to an ID is shown in this modal.

Below follows a jquery function that opens the modal and shows table data cars:

    $(document).on('click', '.update', function(){
        var user_id = $(this).attr("id");

        $.ajax({
            url:"fetch_single.php",
            method:"POST",
            data:{user_id:user_id},
            dataType:"json",
            success:function(data)
            {

                $('#userModal').modal('show');
                $('#carros').val(data.carro);
                $('.selectpicker').selectpicker('val', [data.cor]);

            }
        })
    });

When the modal is opened, the above code shows the correct input data car but the selectpicker does not show the options already marked according to the method: $('.selectpicker'). selectpicker('val', [date.color]);.

In the case of how to make the picker already click beyond all options, the options marked as column data color table **cars?

1 answer

0


I was able to resolve the issue using the Javascript string split() method in the val method of the selectpicker as below:

$('.selectpicker').selectpicker('val', data.cor.split(','));

Now every time the modal opens, the selectpicker will load with the already marked options.

Browser other questions tagged

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