【问题标题】:Display selected value on dropdown in jQuery在 jQuery 的下拉列表中显示选定的值
【发布时间】:2021-08-19 11:46:09
【问题描述】:

我的编辑表单中有一个下拉菜单,但它没有在索引上显示所选值。

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

我将onClick=setIngredientsId 放在我的编辑按钮上。

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

下面是我的下拉 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>

【问题讨论】:

  • 我很确定你只会错过这个:` $('#ingredients').trigger('change');` 这样你就可以让 JS 更新 UI
  • $('ingredients option[value=' + element.raw_material_id + ']').prop('selected',true); ?
  • @RobBiermann 是的,终于!只漏了一行,非常感谢! :)
  • 嘿@Shree,我猜你的也是正确的,但它不适用于我的代码。无论如何,Rob的回答解决了这个问题。也谢谢你! :)

标签: javascript html jquery laravel-8


【解决方案1】:

只漏了一行,这里给遇到同样问题的人!

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

这样你就可以让 JS 更新 UI。感谢 Rob 在评论部分的帮助!

【讨论】:

    猜你喜欢
    • 2015-09-14
    • 1970-01-01
    • 2021-07-13
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多