JavaScript Redirect on Select Option in Select Box

01/12/2022
Contents
In this article, you will learn how to redirect when the select option of the select box is selected in JavaScript.
To redirect with JavaScript
Use the location interface to redirect with JavaScript.
You can move to a new page by assigning the URL to “location.href”.
The syntax is as follows.
location.href = 'https://plantpot.works';
Redirect on Select Option in Select Box
This time, I will redirect by using the value of the option as a part of the URL.
It is also possible to write the entire URL.
In that case, please change the value of the value attribute of option to the URL.
HTML
<select id="selectbox" name="selectbox">
<option value="js">JavaScript</option>
<option value="jquery">jQuery</option>
<option value="html">HTML/CSS</option>
</select>
JavaScript
function redirectValue(event) {
let loc = location;
let value = event.target.value;
if(loc.search !== '')
value += loc.search;
if(loc.hash !== '')
value += loc.hash;
location.href = 'https://plantpot.works/' + value;
//location.href = value;
}
let selectbox = document.getElementById('selectbox');
selectbox.addEventListener('change',redirectValue, false);