Dropdown List Actions using jQuery

Introduction

This blog will explain how to select and manipulate the dropdown list using jQuery.

I have given example for selecting the item using both dropdown values and text and also given code to select, enable/disable, adding and deleting the options.

Code

  1. <html>  
  2. <head>  
  3.     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>  
  4. </head>  
  5. <body>  
  6. <script type="text/javascript">  
  7.     $(document).ready(function(){  
  8.         $("#btnSelect").click(function () {  
  9.             var selValue = $('#ddlNames').val();  
  10.             selText = $("#ddlNames option:selected").text();  
  11.             $("#result").text(selValue + ' - ' + selText);  
  12.         });  
  13.     $("#btnRK").click(function () {  
  14.         // By Value  
  15.         $("#ddlNames").val("RK");  
  16.         // By Name  
  17.         $("#ddlNames option:contains(Ramakrishna)").attr('selected', true);  
  18.     });     
  19.     $("#btnDisIN").click(function () {        
  20.         $("#ddlNames option[value='IN']").attr("disabled", true);         
  21.     });  
  22.     $("#btnEnblIN").click(function () {       
  23.         $("#ddlNames option[value='IN']").attr("disabled", false);        
  24.     });  
  25.     $("#btnAdd").click(function () {  
  26.         if($("#ddlNames option[value='KI']").length == 0)  
  27.         {  
  28.             var newOption = "<option value='KI'>Kistappa</option>";   
  29.             $("#ddlNames").append(newOption);     
  30.         }  
  31.     });  
  32.     $("#btnDelete").click(function () {           
  33.         if($("#ddlNames option[value='KI']").length == 1)  
  34.         {  
  35.             $("#ddlNames option[value='KI']").remove();   
  36.         }         
  37.     });  
  38.   });  
  39. </script>  
  40. </head>  
  41. <body>  
  42.     <br/><br/><br/>  
  43.   
  44.     <select id="ddlNames">  
  45.         <option value="None">-- Select Name</option>  
  46.         <option value="RK">Ramakrishna</option>  
  47.         <option value="PK">Praveenkumar</option>  
  48.         <option value="IN">Indraneel</option>  
  49.         <option value="NE">Neelohith</option>  
  50.     </select>  
  51.     <p id="result" style="font-size:30px; color:red"></p>  
  52.     <br/><br/><br/>  
  53.     <input type='button' value='Selected Item' id='btnSelect'>  
  54.     <input type='button' value='Select Ramakrishna' id='btnRK'>  
  55.     <input type='button' value='Disable Indraneel' id='btnDisIN'>  
  56.     <input type='button' value='Enable Indraneel' id='btnEnblIN'>  
  57.     <input type='button' value='Add New Name' id='btnAdd'>  
  58.     <input type='button' value='Delete Added Name' id='btnDelete'>  
  59. </body>  
  60. </html>  
Output


Ebook Download
View all
Learn
View all