如果条件满足,我想用jquery将以下选择的值'Saumon'设置为默认值。我知道如何处理条件,但真的找不到解决此问题的方法:
<div class="form-group" style="display: block;">
<label class="control-label col-sm-2">Sandwiches 1</label>
<div class="col-sm-10">
<select id="ordersdetailpartyloafsandwich1ID" name="child-partyloafsandwich1ID" class="form-control select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<option value=""></option>
<option value="1">Saumon</option>
</select>
<span class="select2 select2-container select2-container--default select2-container--below select2-container--focus" dir="ltr" style="width: 100px;">
<span class="selection">
<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-ordersdetailpartyloafsandwich1ID-container">
<span class="select2-selection__rendered" id="select2-ordersdetailpartyloafsandwich1ID-container" title="Saumon">Saumon</span>
<span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
</div>
我已经尝试过了:
https://jsfiddle.net/marcq/rL4nuhv6/1/
,但是该值当然是在选择框之外设置的。
我被困在这里,不胜感激,因为我不想更改我的应用程序的源代码,在这里我会很高兴。谢谢。马克
答案 0 :(得分:0)
在您的示例中,错误的选项选择器。我建议您将id用作html select的选择器。像这样
$('#ordersdetailpartyloafsandwich1ID').find('option[value=1]').attr('selected', true);
$('#ordersdetailpartyloafsandwich1ID').val('1');
答案 1 :(得分:0)
尝试在所需的选项中添加所选属性,如下所示:
<option value="Saumon" selected>Saumon</option>
答案 2 :(得分:0)
@marcq,您不必为此编写过多的代码,您只需添加特定选项的值即可,例如
$('select[name="child-partyloafsandwich1ID"]').val(1);
谢谢。
答案 3 :(得分:0)
您的小提琴有几个错误:
child-partyloafsandwich1ID
而不是name
。:eq
选择器接受从零开始的索引。id
,因此应将其用作选择器。现在,了解所有这些,请阅读 Set the selected index of a Dropdown using jQuery
顺便说一句,在这种情况下,您不需要jQuery来选择该选项。您可以按照以下步骤进行操作:
document.getElementById('ordersdetailpartyloafsandwich1ID').selectedIndex = 1;
<div class="form-group" style="display: block;">
<label class="control-label col-sm-2">Sandwiches 1</label>
<div class="col-sm-10">
<select id="ordersdetailpartyloafsandwich1ID" name="child-partyloafsandwich1ID" class="form-control select2 select2-hidden-accessible" tabindex="-1" aria-hidden="true">
<option value=""></option>
<option value="1">Saumon</option>
</select>
<span class="select2 select2-container select2-container--default select2-container--below select2-container--focus" dir="ltr" style="width: 100px;">
<span class="selection">
<span class="select2-selection select2-selection--single" role="combobox" aria-haspopup="true" aria-expanded="false" tabindex="0" aria-labelledby="select2-ordersdetailpartyloafsandwich1ID-container">
<span class="select2-selection__rendered" id="select2-ordersdetailpartyloafsandwich1ID-container" title="Saumon">Saumon</span>
<span class="select2-selection__arrow" role="presentation"><b role="presentation"></b></span>
</span>
</span>
<span class="dropdown-wrapper" aria-hidden="true"></span>
</span>
</div>
</div>