Single-choice dropdowns are a standard HTML component. Their usage, although straightforward, can sometimes be frustrating, both for the developer and the user. The browser requires that a "selected" attribute is added to the selected item. To set the value of the select
element programmatically, the code must first find the item which is presently selected and remove its "selected" attribute, then find the item that has the specified value and add a "selected" attribute to it.
However, the developer might want an easier way to specify the value of the dropdown field. Simply adding an attribute containing the value should be enough. In this recipe, we're going to solve this problem by adding a new attribute to dropdowns.
Let's get started.
select
element. To add selection options, we add one or more option elements inside the select
element. Normally, we would specify the pre-selected option by adding a selected attribute to it:<select name="dropdown"> <option value="1">First</option> <option value="2" selected="selected">Second</option> <option value="3">Third</option> </select>
index.html
:<!DOCTYPE HTML> <html> <head> <title>Dropdown</title> </head> <body> <select name="dropdown" data-value="2"> <option value="1">First</option> <option value="2">Second</option> <option value="3">Third</option> </select> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"> </script> <script type="text/javascript" src="example.js"> </script> </body> </html>
example.js
:$(function() { $('body').on('change', 'select[data-value]', function() { $(this).attr('data-value', $(this).val()); }); window.updateDropdowns = function() { $('select[data-value]').each(function() { $(this).val($(this).attr('data-value')); }); } updateDropdowns(); });
The code in example.js
runs when the page is loaded. At that point, it finds all select elements that have a data-value attribute, and sets the selected option using jQuery's versatile function $.fn.val
. Additionally, it binds a global event for all present and future select items that have a data-value attribute, which syncs that value to the actual value.
This is a more natural model for single-choice dropdowns.
18.188.187.165