Showing posts with label Restrict Selection. Show all posts
Showing posts with label Restrict Selection. Show all posts

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 

Friday, April 27, 2012

Disable DropDownList without blur effect in Asp.Net

In View mode, we will set the .Enabled property of controls false, to prevent the users from modifying the values in the control, but this will create a blur effect on the controls and the text in the controls will not be visible clearly.  Especially in the DropDownList control, when the control is disabled the user will not be able to see the other options available in the DropDownList control.

We can overcome this with the help of some JavaScript, adding this script will enable the users to view the other options in the dropdown, but still makes sure that the user cannot change the currently selected option in the View mode.