Nevin Nevin - 7 months ago 17
Javascript Question

how to reset all the select box inside a div onclick of a button?

in my form

<div class="container">
<select name="sel1">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<select name="sel2">
<option value="0">Zero</option>
<option value="1">One</option>
<option value="2">Two</option>
</select>
</div>
<input type="button" onclick="resetAll()" value="Reset"/>


i need to reset both sel1,sel2 to default values. ie selectedIndex = 0;

function resetAll()
{
//what should i write here to do this
}


i have more than 20 selectboxes. any help?

Answer

Simply add an id to the container item, so you can easily reference it. This way you only reset the select boxes that reside in it, and not any other ones you may have on the page:

function resetAll() {
    var container = document.getElementById('container');
    var children = container.getElementsByTagName('select');
    for (var i = 0; i < children.length; i++) {
        children[i].selectedIndex = 0;
    }
}
Comments