Search code examples
phpjqueryajaxbootstrap-modalbootstrap-5

Send data vi ajax to dropdownlist is not completly set as selected


I send via ajax an ID to get a specific name (label) with his code, which i will show as selected value in my dropdown list in a Bootstrap Modal Form.

I get the code inside the value quotes, but not the label between the option tag like :

<option value="123" id="code" selected> </option>

But i want to get this :

<option value="75000" id="code" selected>Paris</option>

Here is my code:

<select class="form-select mb-3" id="label" name="label" required>

   <option value="" id="code" selected></option>

<?php  while ($row = $stmtGetLabel->fetch()) { ?>
    <option value="<?php echo $row['code'] ?>"><?php echo $row['label'] ?></option>
    <?php }?>
</select>
                                        
...

$(document).on('click', '.update , #act', function(){
    var id = $(this).attr("id");
    $.ajax({
        url:"inc/functions/ActRef.php",
        method:"POST",
        data:{id:id},
        dataType:"json",
        success:function(data)
        {
            $('#mymodal').modal('show');
            $('#label').val(data.label);
            $('#code').val(data.code);
            $('#id').val(id);
            $('#action').val("EDIT");
            $('#operation').val("edition");
        }
    })
});

Whats works wrong with my code ?

any ideas pls?

Thx in advance


Solution

  • If I understand correctly, you are trying to set the info on this portion of the HTML:

    <option value="" id="code" selected></option>
    

    Assuming I understand correctly, what you need to do is:

    $('#code').attr('value', data.code).html(data.label);
    $('#label').val(data.code);