Is there a simple way to have a user go to a URL from a dropdown list on SUBMIT, rather than onChange.
I have this code:
<form name="cityselect">
<select name="menu" onChange="top.location.href=this.options[this.selectedIndex].value;" value="GO">
<option selected="selected">Select One</option>
<option value="">London</option>
<option value="">Glasgow</option>
</select>
Tried changing onChange to onSubmit, but it doesn't work.
Is there a simple way to have a user go to a URL from a dropdown list on SUBMIT, rather than onChange.
I have this code:
<form name="cityselect">
<select name="menu" onChange="top.location.href=this.options[this.selectedIndex].value;" value="GO">
<option selected="selected">Select One</option>
<option value="http://www.domain-one.">London</option>
<option value="http://www.domain-two.">Glasgow</option>
</select>
Tried changing onChange to onSubmit, but it doesn't work.
Share Improve this question asked Dec 6, 2016 at 0:41 SamSam 371 silver badge9 bronze badges 1- a select doesn not have a submit even. Submit event is with the form. – Manish Commented Dec 6, 2016 at 3:42
2 Answers
Reset to default 3Try this instead.
Also: You'll want to keep your JavaScript separated from your HTML. Do not use onchange
or similar HTML attributes. While it's technically not wrong, it's bad from a code quality/maintainability perspective.
var goBtn = document.getElementById("goBtn");
var menu = document.getElementById("menu");
goBtn.onclick = function() {
window.location = menu.value;
}
<select id="menu">
<option selected="selected">Select One</option>
<option value="http://www.domain-one.">London</option>
<option value="http://www.domain-two.">Glasgow</option>
</select>
<input type="button" id="goBtn" value="GO!">
Does this work for you?
You can use the onsubmit
event on the <form>
element, but you'll want to preventDefault on the event, and for the onsubmit
event you need to use a return
:
<form name="cityselect" onsubmit="return redirectTo(this)">
<select name="menu" value="GO">
<option selected="selected">Select One</option>
<option value="http://www.domain-one.">London</option>
<option value="http://www.domain-two.">Glasgow</option>
</select>
</form>
<script>
function redirectTo(elem) {
event.preventDefault();
top.location.href = elem.firstElementChild.options[elem.firstElementChild.selectedIndex].value
}
</script>
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745256927a4619013.html
评论列表(0条)