Display selected value on dropdown in jQuery

Viewed 56

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

Dropdown box image

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

enter image description here

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);
            }
        });
    }

Console log result for 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>
1 Answers

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!

Related