I want to learn how to use JavaScript (or the jQuery library) in order to go to a url indicated as a value of the option tag inside an optgroup tag.
With a simple, one-level select tag containing option tags, the solution can be similar to that described in this post:
<FORM NAME="nav"><DIV>
<SELECT NAME="SelectURL" onChange=
"document.location.href=
document.nav.SelectURL.options[document.nav.SelectURL.selectedIndex].value">
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/jsnav.html"
SELECTED>Please select an item:
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/">
Main page on HTML forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/choices.html">
Choices in HTML forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/tables.html">
Tables and forms
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/methods.html">
Form submission methods (GET and POST)
</SELECT><DIV>
</FORM>
I tried to use it with a two-level select tag with option tags inside optgroup tags – and it's not working for me. I'd appreciate help with adapting this code.
Use this to do it when the user selects an option:
$('select[name="SelectURL"]').change(function() {
window.location.replace($(this).val());
});
Or this when the user clicks a submit button:
$('form[name="nag"]').on('submit' function(e){
e.preventDefault();
window.location.replace($('select[name="SelectURL"]').val());
});
You should also clean up you HTML like this:
<FORM NAME="nav">
<DIV>
<SELECT NAME="SelectURL">
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/jsnav.html" SELECTED>Please select an item:</OPTION>
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/"> Main page on HTML forms</OPTION>
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/choices.html"> Choices in HTML forms</OPTION>
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/tables.html"> Tables and forms</OPTION>
<OPTION VALUE="http://www.cs.tut.fi/~jkorpela/forms/methods.html"> Form submission methods (GET and POST)</OPTION>
</SELECT>
<DIV>
</FORM>