Friday, June 29, 2012

Asp.Net jQuery Restrict dropdown list Selection without disabling

In this post, We will see on how to restrict the user from selecting an option in a DropDownList without disabling the control, using jQuery.

In the post Disable DropDownList without blur effect in Asp.Net, we saw how to achieve this effect using JavaScript, but this required us to set the onfocus and onchange event functions in all the dropdowns.


onfocus="javascript:setDefaultIndex(this);"
onchange="javascript:setSelectedIndex(this);"

Here we will see on how to achieve the same effect using jQuery, believe me this is very easy compared to the JavaScript approach.

Just add the below script to the page, that’s it, the user cannot change the selected values in any of the DropDownList in the page.

<script type="text/javascript" src="JavaScript/jquery-1.7.2.js">script>
<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        // Loop Through DropDowns
        $('select').each(function() {
            $(this).change(function(e) {
                $(this).prop("selectedIndex", $(this).prop("defaultIndex"));
            });
            $(this).focus(function(e) {
                $(this).prop("defaultIndex", $(this).prop("selectedIndex"));
            });
        });
    });
script>

We are capturing the focus and change events of all the DropDownList controls in the page. 
 - On focus we are getting the selectedIndex and setting it to defaultIndex
 - On change we are again getting the defaultIndex and setting it to the selectedIndex of the DropDownList controls 


Search Flipkart Products:
Flipkart.com

No comments: