Keith Power Keith Power - 2 months ago 12
Javascript Question

Reset all select dropdowns

I have have a function that gets called by onbeforeunload. Within I wish to reset all the dropdowns but I cannot find the right method to reset them back to the 0 value.

<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>

Answer Source
function displaymessage() {
    $("select").each(function() { this.selectedIndex = 0 });
}

this selects the first option (not necessarily having value = 0)