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
- <html>
- <head>
- <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
- </head>
- <body>
- <script type="text/javascript">
- $(document).ready(function(){
- $("#btnSelect").click(function () {
- var selValue = $('#ddlNames').val();
- selText = $("#ddlNames option:selected").text();
- $("#result").text(selValue + ' - ' + selText);
- });
- $("#btnRK").click(function () {
- // By Value
- $("#ddlNames").val("RK");
- // By Name
- $("#ddlNames option:contains(Ramakrishna)").attr('selected', true);
- });
- $("#btnDisIN").click(function () {
- $("#ddlNames option[value='IN']").attr("disabled", true);
- });
- $("#btnEnblIN").click(function () {
- $("#ddlNames option[value='IN']").attr("disabled", false);
- });
- $("#btnAdd").click(function () {
- if($("#ddlNames option[value='KI']").length == 0)
- {
- var newOption = "<option value='KI'>Kistappa</option>";
- $("#ddlNames").append(newOption);
- }
- });
- $("#btnDelete").click(function () {
- if($("#ddlNames option[value='KI']").length == 1)
- {
- $("#ddlNames option[value='KI']").remove();
- }
- });
- });
- </script>
- </head>
- <body>
- <br/><br/><br/>
-
- <select id="ddlNames">
- <option value="None">-- Select Name</option>
- <option value="RK">Ramakrishna</option>
- <option value="PK">Praveenkumar</option>
- <option value="IN">Indraneel</option>
- <option value="NE">Neelohith</option>
- </select>
- <p id="result" style="font-size:30px; color:red"></p>
- <br/><br/><br/>
- <input type='button' value='Selected Item' id='btnSelect'>
- <input type='button' value='Select Ramakrishna' id='btnRK'>
- <input type='button' value='Disable Indraneel' id='btnDisIN'>
- <input type='button' value='Enable Indraneel' id='btnEnblIN'>
- <input type='button' value='Add New Name' id='btnAdd'>
- <input type='button' value='Delete Added Name' id='btnDelete'>
- </body>
- </html>
Output