The <optgroup> element in HTML is used to group related <option> elements inside a <select> dropdown. This helps to organize large lists of options into categories, making it easier for users to find what they are looking for. Each <optgroup> has a label attribute that defines the group name, which is displayed as a heading above the grouped options.
When you have a large number of options, organizing them into groups provides a clearer structure, reducing user confusion and enhancing the overall form experience. Without groups, a long list of unrelated options can confuse users. Grouping them makes navigation and selection easier.
Syntax
<select name="select_name" id="select_id" multiple size="number_of_visible_options"> <optgroup label="Group Label 1"> <option value="option_value1">Option 1</option> <option value="option_value2">Option 2</option> <!-- More options --> </optgroup> <optgroup label="Group Label 2"> <option value="option_value1">Option 1</option> <option value="option_value2">Option 2</option> <!-- More options --> </optgroup> </select>
group-options.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Optgroup Example</title> </head> <body> <form action="https://httpbin.org/post" method="POST"> <label for="vehicles">Choose a vehicle:</label> <select id="vehicles" name="vehicles"> <!-- Group 1: Cars --> <optgroup label="Cars"> <option value="volvo">Volvo</option> <option value="bmw">BMW</option> <option value="audi">Audi</option> <option value="mercedes">Mercedes</option> <option value="tesla">Tesla</option> </optgroup> <!-- Group 2: Motorcycles --> <optgroup label="Motorcycles"> <option value="harley">Harley Davidson</option> <option value="ducati">Ducati</option> <option value="kawasaki">Kawasaki</option> <option value="yamaha">Yamaha</option> <option value="suzuki">Suzuki</option> </optgroup> <option value="ford">Ford</option> <option value="chevrolet">Chevrolet</option> <option value="ram">Ram</option> <option value="gmc">GMC</option> <option value="toyota">Toyota</option> </select> <br><br> <input type="submit" value="Submit"> </form> </body> </html>
Above snippet generate below screen.
Previous Next Home
No comments:
Post a Comment