[英]How to get the # of options with the attr “selected” in a drop down using jQuery?
[英]how to change a drop down options to default selected using jquery
下面的代碼是我的html表單下拉菜單的一部分:
<div class="wrap-quest-resp" id="fa8">
<div class="input-quest-no-height">FA and port - 8</div>
<div class="input-resp-no-height">
<select id="fa-select-8" name="fa-select-8">
<option disabled="disabled" SELECTED >Dir</option>
<option <?php if ($_POST['fa-select-8']==1) {echo "selected='selected'"; } ?> >1</option>
<option <?php if ($_POST['fa-select-8']==2) {echo "selected='selected'"; } ?> >2</option>
<option <?php if ($_POST['fa-select-8']==3) {echo "selected='selected'"; } ?> >3</option>
<option <?php if ($_POST['fa-select-8']==4) {echo "selected='selected'"; } ?> >4</option>
<option <?php if ($_POST['fa-select-8']==5) {echo "selected='selected'"; } ?> >5</option>
</select>
<select id="proc-select-8" name="proc-select-8">
<option disabled="disabled" SELECTED >Proc</option>
<option <?php if ($_POST['proc-select-8']==a) {echo "selected='selected'"; } ?> >a</option>
<option <?php if ($_POST['proc-select-8']==b) {echo "selected='selected'"; } ?> >b</option>
</select>
<select id="port-select-8" name="port-select-8">
<option disabled="disabled" SELECTED >Port</option>
<option <?php if ($_POST['port-select-8']==0) {echo "selected='selected'"; } ?> >0</option>
<option <?php if ($_POST['port-select-8']==1) {echo "selected='selected'"; } ?> >1</option>
</select>
</div>
</div>
我使用這個jQuery來隱藏上面提到的div及其下拉選擇
$('#fa8').slideUp("fast");
我想在隱藏div
同時將option
更改為其默認的SELECTED
選項。 這是所有三個下拉菜單的以下選項
<option disabled="disabled" SELECTED >Dir</option>
<option disabled="disabled" SELECTED >Proc</option>
<option disabled="disabled" SELECTED >Port</option>
使用來自slideUp
的回調並將每個的0索引設置為通過prop()
進行選擇
$('#fa8').slideUp("fast", function() {
//Set the 0 index as selected
$("#fa-select-8 option").eq(0).prop("selected", true);
//do the same for the rest, change the ID
});
由於您似乎希望所有選擇均使用默認值,因此建議使用以下方法:
$('#fa8').find("select").find("option:first").prop("selected", true);
根據tymeJV的建議,取決於代碼的實現方式,您可以使其成為回調的一部分,也可以將其放在代碼中slideUp
調用之后的下一行。
如果使用回調,則可以使用$(this)
代替$('#fa8')
:
$('#fa8').slideUp("fast", function() {
$(this).find("select").find("option:first").prop("selected", true);
});
如果您采用“多行”方法,請將$('#fa8')
的選擇器存儲在變量中,以免再次運行select:
var $wrapReqResp = $('#fa8');
$wrapReqResp.slideUp("fast");
$wrapReqResp.find("select").find("option:first").prop("selected", true);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.