Set and get values from drop-down list:- JavaScript


  • 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:-

  1. <!DOCTYPE html> 
  2. <html> 
  3.  
  4. <head> 
  5.  <meta name="viewport" content="width=device-width, initial-scale=1"> 
  6. </head> 
  7.  
  8. <body> 
  9.  <select id="ddl1"> 
  10.     <option value="1" data-color="Yellow Color">Bannana</option> 
  11.     <option value="2" data-color="Black Color">Graps</option> 
  12.     <option value="3" data-color="Red Color">Apple</option> 
  13.     <option value="3" data-color="Orange Color">Mango</option> 
  14.   </select> 
  15.  
  16.  <br /> 
  17.  <input type="button" value="Check Color" onclick="chk_clor();"> 
  18.  
  19.  <script> 
  20.   function chk_clor() 
  21.   { 
  22.    // Plain old JavaScript 
  23.    var sel = document.getElementById('ddl1'); 
  24.    var selected = sel.options[sel.selectedIndex]; 
  25.    var clr = selected.getAttribute('data-color'); 
  26.    alert(clr); 
  27.   } 
  28.  </script> 
  29.  
  30. </body> 
  31.  
  32. </html>
Set and get values from drop-down list:- JavaScript Set and get values from drop-down list:- JavaScript Reviewed by Network security on November 05, 2019 Rating: 5

No comments:

Useful Information

Powered by Blogger.