繁体   English   中英

如何将下拉选项更改为使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM