An HTML tutorial to retrieve the value of an option <option> from a <select> field and redirect the client to the chosen option (URL) with Alpine.js.

The French version of this post: Click here

Introduction

Alpine.js is a minimal JavaScript framework that allows you to manipulate the HTML DOM by offering the responsive nature of Vue and React, but with much more simplicity.

We want to see in this guide how to use it to retrieve the value of an option <option> from a drop-down list <select> and redirect the client to the address specified as the option value.

Install Alpine.js

To include Alpine.js in an HTML page, we can use the <script> tag by indicating its CDN link via the src attribute :

<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>

Alpine can also be installed as a module via npm :

npm install alpinejs

The Alpine.js documentation has more information about these two ways to include it in your project.

<select> field with <option>

The <select> tag is used to present a drop-down list with <option> options. The value of each option is indicated via the value attribute.

For our example, we will start with the following code:

<select>
	<!-- Options -->
	<option value="" disabled >Where do you want to go?</option>
	<option value="home.html" >Home</option>
	<option value="blog.html" >Blog</option>
	<option value="contact.html" >Contact</option>
</select>

Reactivity with Alpine.js

Alpine.js intervenes when we want to monitor the change of value of the drop-down list to redirect the client to the chosen option.

We will proceed as follows to make the <select> reactive:

  1. Let's insert the directive x-data="{ link : '' }" to define the link property that will contain the value (attribute value) of the chosen <option>.
  2. Link the value of the option with the link property using the x-model="link" directive
  3. At <select> element initialization time, let's call the $watch magic method to monitor the change of the link property and redirect the client to the option value: x-init="$watch('link', value => window.location = link)"

The complete HTML-Alpine.js code :

<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>HTML - AlpineJS : Redirect to a value of a select field</title>
</head>
<body>
	<!-- <select> with Alpine.js directives -->
	<select x-data="{ link : '' }" x-model="link" x-init="$watch('link', value => window.location = link)" >	
		<!-- Options -->
		<option value="" disabled >Where do you want to go?</option>
		<option value="home.html" >Home</option>
		<option value="blog.html" >Blog</option>
		<option value="contact.html" >Contact</option>		
	</select>

	<!-- We include Alpine.js 3.10.5 -->
	<script defer src="https://unpkg.com/alpinejs@3.10.5/dist/cdn.min.js"></script>
</body>
</html>

Be well! đŸ˜‰