简体   繁体   中英

Javascript: Onclick Set Dropdown Menu Checked Value

UPDATE: I was trying lots of different methods for doing this and none of them worked... until... I changed my dropdown menu name from (date-range) to (dateRange) removing the (-), sorry for wasting time!


I have a search form and a custom reset form button, which resets all the values in the form. I now have a dropdown menu and when the reset button is pressed, I want the first option to be selected.

This is my form:

<select name="date-range" id="date-range">
<option value="Any">Any date</option>
<option value="Today">Today</option>
<option value="Yesterday">Yesterday</option>
<option value="1 Week">Within 1 Week</option>
<option value="1 Month">Within 1 Month</option>
<option value="3 Months">Within 3 Months</option>
<option value="6 Months">Within 6 Months</option>
<option value="1 Year">Within 1 Year</option>
</script>

... and this is my javascript function that now needs to select the first dropdown value "Any".

function resetSearchForm()
{
document.searchFrm.searchStr.value='';
document.searchFrm.vertical.checked = true;
document.searchFrm.horizontal.checked = true;
** dropdown select first **
}

What is the proper way to do this? Any help gratefully received :)

This will work:

document.getElementById('date-range').selectedIndex = 0;   

Example can be found here:

http://jsfiddle.net/yPmmG/3/

No javascript required, just add the selected attribute to the first option. That's what the attribute is for.

<option selected value="Any">Any date</option>

It is recommended that all select elements have one option with the selected attribute, that way there is always one selected by default. It will be the selected option when the page first loads and if the form is reset.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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