重置所有选择下拉列表

Reset all select dropdowns

本文关键字:下拉列表 有选择      更新时间:2023-09-26

我有一个函数被onbeforeunload调用。我希望重置所有的下拉菜单,但我找不到正确的方法将它们重置回0值。

<head>
    <script type="text/javascript">
        function displaymessage() {
            document.getElementsByTagName('select').value = 1;
            //or
            document.getElementsByTagName('select').options.length = 0;
        }
    </script>
</head>
<body>
    <form>
        <input type="button" value="Click me!" onclick="displaymessage()" />
    </form>
    <select name="data[Rate][15][12][num_rooms]" id="r15ro12">
        <option value="0">0</option><option value="1">1 Rooms</option>
        <option value="2">2 Rooms</option><option value="3">3 Rooms</option><option value="4">4 Rooms</option>
        <option value="5">5 Rooms</option><option value="6">6 Rooms</option><option value="7">7 Rooms</option>
        <option value="8">8 Rooms</option><option value="9">9 Rooms</option>
    </select>
    <select name="data[Rate][15][12][num_rooms]" id="r15ro12">
        <option value="0">0</option><option value="1">1 Rooms</option>
        <option value="2">2 Rooms</option><option value="3">3 Rooms</option><option value="4">4 Rooms</option>
        <option value="5">5 Rooms</option><option value="6">6 Rooms</option><option value="7">7 Rooms</option>
        <option value="8">8 Rooms</option><option value="9">9 Rooms</option>
    </select>
</body>
</html>
function displaymessage() {
    $("select").each(function() { this.selectedIndex = 0 });
}

选择第一个选项(不一定value = 0)

这是一种使用原生JavaScript在所有select中选择第一个选项的方法;

var elements = document.getElementsByTagName('select');
for (var i = 0; i < elements.length; i++)
{
    elements[i].selectedIndex = 0;
}

…但是jQuery非常方便,使大多数事情变得更容易。

不如这样写:

$(window).unload(function () {
    $("select").val("0");
});

使用原始javascript代码,我们可以做以下操作:

elements = document.getElementsByTagName("select")
for(i=0; i < elements.length ; i++){
 elements[i].selectedIndex= 0;
}

试试这个:

function displaymessage() {
    $("select").val("0");
}

首先,你不应该为不同的标签使用相同的名称/id。对于每个标签它应该是唯一的

在标签中调用函数,如

然后改变你的乐趣函数功能displaymessage() {var x= document.getElementsByTagName('select');(var i = 0; i<2,我+ +){. getelementbyid (x[我].id) .options[0]。Selected = "0";}}

另起蹊径

$('select option:first-child').attr('selected', 'selected');
演示

目前为止我看到的jQuery解决方案没有考虑到删除之前的selected属性(如果存在的话),因此我认为需要这个额外的步骤:

$("#myControlId").find("select").each(function (index) {
        var ctrl=$(this);       
        if (ctrl.children().length > 0) {
            $(ctrl.children()).each(function(index) {
                if (index===0) $(this).attr('selected', 'selected'); 
                else $(this).removeAttr('selected');
            });
        }
});

这个解决方案只保留一个selected属性在第一个选项,并删除所有其他(如果适用)。

试试这个:

$( 'select' ).each( function () {
    if ( $( this ).children().length > 0 ) {
        $( $( this ).children()[0] ).attr( 'selected', 'selected' );
    }
} );

(# dropDownListID)美元.val (" "),

$ (' # dropDownListID ') .val("0");