- By using the getElementById we can select the id of the dropdown control.
- The selectedIndex property used to return the index of the selected option.
- By using the getAttribute() method we will get the attribute of the selected option.
Code:-
- <!DOCTYPE html>
- <html>
- <head>
- <meta name="viewport" content="width=device-width, initial-scale=1">
- </head>
- <body>
- <select id="ddl1">
- <option value="1" data-color="Yellow Color">Bannana</option>
- <option value="2" data-color="Black Color">Graps</option>
- <option value="3" data-color="Red Color">Apple</option>
- <option value="3" data-color="Orange Color">Mango</option>
- </select>
- <br />
- <input type="button" value="Check Color" onclick="chk_clor();">
- <script>
- function chk_clor()
- {
- // Plain old JavaScript
- var sel = document.getElementById('ddl1');
- var selected = sel.options[sel.selectedIndex];
- var clr = selected.getAttribute('data-color');
- alert(clr);
- }
- </script>
- </body>
- </html>
Set and get values from drop-down list:- JavaScript
Reviewed by Network security
on
November 05, 2019
Rating:
No comments: