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. <select id="ddlNames">
  44. <option value="None">-- Select Name</option>
  45. <option value="RK">Ramakrishna</option>
  46. <option value="PK">Praveenkumar</option>
  47. <option value="IN">Indraneel</option>
  48. <option value="NE">Neelohith</option>
  49. </select>
  50. <p id="result" style="font-size:30px; color:red"></p>
  51. <br/><br/><br/>
  52. <input type='button' value='Selected Item' id='btnSelect'>
  53. <input type='button' value='Select Ramakrishna' id='btnRK'>
  54. <input type='button' value='Disable Indraneel' id='btnDisIN'>
  55. <input type='button' value='Enable Indraneel' id='btnEnblIN'>
  56. <input type='button' value='Add New Name' id='btnAdd'>
  57. <input type='button' value='Delete Added Name' id='btnDelete'>
  58. </body>
  59. </html>
Output