Home > Article > Web Front-end > How to use jQuery to implement drop-down box selection jump function
jQuery is a widely used JavaScript library that helps developers handle DOM operations, event handling, and Ajax requests more easily, so it is widely used in web development. In this article, we will discuss how to use jQuery to implement the jump function of drop-down box selection.
First, let’s take a look at the basic HTML code as follows:
<select id="selectBox"> <option value="http://www.google.com">Google</option> <option value="http://www.baidu.com">Baidu</option> <option value="http://www.bing.com">Bing</option> </select>
This is a simple drop-down menu with three options, pointing to Google, Baidu and Bing. website. Now our goal is that when the user selects an option, immediately redirect them to the selected website.
In order to achieve this goal, we bind a change
event to the select
element:
$(document).ready(function() { $('#selectBox').change(function() { var url = $(this).val(); if (url != '') { window.location.href = url; } }); });
In this code, we first use $(document).ready()
Method to ensure that the page is fully loaded before executing the code. Next, we bind a change
event to the select
element, which is triggered when the option changes. We then use jQuery's val()
method to get the value of the selected option and store it in the url
variable. If url
is not empty, use window.location.href
to redirect the page to the selected website.
One thing to note here is that we use a conditional statement to check whether url
is empty. This is because by default in a drop-down box, the first option is usually "Please select" and its value is empty. If the user selects the default option without selecting another option, the page should not be redirected anywhere. So in this case we just terminate the function execution without doing anything.
To summarize, it is very simple to use jQuery to select and jump in the drop-down box. Simply use the change
event to get the value of the option, then use window.location.href
to redirect the page to the selected website. Hope this article helps you!
The above is the detailed content of How to use jQuery to implement drop-down box selection jump function. For more information, please follow other related articles on the PHP Chinese website!