Categories: 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…

2 years ago

Merrimu Reservoir drone images

Merrimu Reservoir from drone. Click images to view larger.

2 years ago

Early September spring shots

Some early September spring shots from a bushwalk, It is still too early for wildflowers.

3 years ago

Cloning an NVMe to SK Hynix Platinum P41 NVMe

I recently needed to clone over a smaller NVMe to a 2TB SK Hynix Platinum…

3 years ago

Using Laravel’s deleteDirectory to delete folders and their contents

If you ever needed a simple solution in Laravel to delete an entire directory and…

3 years ago

How to allow only 1 user to register in a Laravel application

How to enforce only one user to register or be registered in a Laravel web…

3 years ago