Development

Building a URL with vanilla Javascript from select inputs

A dynamic URL builder using select inputs and vanilla Javascript.

CodePen example:

Setting the select inputs

Each of the select inputs needs to be assigned to a variable to get the value and also add an event listener for change later

One of the select inputs HTML:

<select class="form-select" id="stat-type-select" name="stat-type-select">
   <option value="team">Team</option>
   <option value="player" selected>Player</option>
</select>

Assigning to a variable by using getElementById()

let stat_select = document.getElementById("stat-type-select");

Setting the base URL to avoid repeating it in each of the event listeners:

let base_url = 'https://domain.com/';

On select input change

When any of the select inputs are interacted with then the URL needs to be modified to contain the new value. Each input gets an addEventListener for change:

stat_select.addEventListener('change', function () {
    //stat-type-select input was changed
});

In each of these event listeners is an assigner for the URL. In reality, it will be window.location.href = to redirect the browsing window. But for this example, it is assigning a text input the URL value.

url_input.value = base_url + season_select.value + '/' + stat_select.value + '/' + season_type_select.value + '/' + stat_mode_select.value;

View the full code here at CodePen.

Share

Recent Posts

Kennington reservoir drained drone images

A drained and empty Kennington reservoir images from a drone in early July 2024. The…

1 year ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

1 year ago

FTP getting array of file details such as size using PHP

Using FTP and PHP to get an array of file details such as size and…

2 years ago

Creating Laravel form requests

Creating and using Laravel form requests to create cleaner code, separation and reusability for your…

2 years ago

Improving the default Laravel login and register views

Improving the default Laravel login and register views in such a simple manner but making…

2 years ago

Laravel validation for checking if value exists in the database

Laravel validation for checking if a field value exists in the database. The validation rule…

2 years ago