I want to have a list of options containing different URL’s, and then redirect the user based on his selected option once he clicks on submit.
This works – but it works to fast, as the user doesn’t need to click any submit.
<select id="dynamic_select"> <option value="" selected>Pick a Website</option> <option value="http://www.google.com">Google</option> <option value="http://www.youtube.com">YouTube</option> <option value="https://www.netflix.com">Netflix</option> </select> <script> $(function(){ // bind change event to select $('#dynamic_select').on('change', function () { var url = $(this).val(); // get selected value if (url) { // require a URL window.location = url; // redirect } return false; }); }); </script>
How can I implement a submit button to this code, so the user doesn’t get redirected at once?
Advertisement
Answer
For this, simply by add a submit
button (via an input) you can just handle the submit
click then grab the value of the select
element. This way it will only trigger on the submit
click and not each change of the select
<select id="dynamic_select"> <option value="" selected>Pick a Website</option> <option value="http://www.google.com">Google</option> <option value="http://www.youtube.com">YouTube</option> <option value="https://www.netflix.com">Netflix</option> </select> <input type="submit" id="send_url" value="Submit" /> <script> $(function(){ // bind change event to select $('#send_url').on('click', function () { var url = $('#dynamic_select').val(); // get selected value if (url) { // require a URL window.location = url; // redirect } return false; }); }); </script>