简体   繁体   中英

Display selected value on dropdown in jQuery

I have a dropdown in my edit form, but it doesn't display the selected value on the index.

下拉框图片

 var ingredients=<?php echo $boms->load('rawMaterial') ?>;
 console.log('BillOfMaterials', ingredients);

在此处输入图像描述

I put onClick=setIngredientsId on my edit button.

function setIngredientsId(id){

        ingredients.forEach(element => {

            if(element.id==id){
                console.log('hello', element.raw_material)
                $('#modal-title-new-ingredients').html("Edit Ingredient")
                $('#bom_id').val(element.id);
                $('#ingredients').val(element.raw_material_id);
                $('#consumption').val(element.quantity);
            }
        });
    }

hello 的控制台日志结果

Below is my dropdown HTML:-

<select class="noselecttwo form-control" name="ingredients" id="ingredients" required>
  <option disabled selected value> -- Select a Ingredient -- </option>
    @foreach ($ingredients as $ingredient)
       <option id="var{{$ingredient->id}}" value="{{$ingredient->id}}">{{ $ingredient->name.' - '. $ingredient->rawMaterialUnit->name}}</option>
    @endforeach
</select>

Only missed a single line, here for those who face the same problem!

$('#ingredients').trigger('change');

This way you let JS update the UI. Thanks Rob for helping at the comment section!

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