Uncheck dynamically radiobuttonlist control using javascript

Jobi picture Jobi · Dec 13, 2012 · Viewed 8.7k times · Source

I have a RadioButtonList control in a web user control and it is loaded in a place holder of web page. The radio button list items will be loaded dynamically and the user can select any item.

As per the radio button behavior, we want to select another item to deselect already selected item. But I want to deselect an item if the user clicked on same item itself if it was already checked.

Also I have to do it using javascript not Server side code.

Answer

Amit Thakkar picture Amit Thakkar · Dec 13, 2012

Add this javascript function in <Head> tag.

<script type="text/javascript">


        function clearRadioButtonList() {

            var elementRef = document.getElementById('<%= yourRadioButtonListID.ClientID %>');
            var inputElementArray = elementRef.getElementsByTagName('input');

            for (var i = 0; i < inputElementArray.length; i++) {
                var inputElement = inputElementArray[i];

                inputElement.checked = false;
            }
            return false;
        }

    </script>

When you dynamically add listitem, add onclick attribute to listitem:

myListItem.Attributes.Add("onclick", "clearRadioButtonList");

Don't forget to replace "yourRadioButtonListID" in javascript function. This will uncheck the clicked radio button if it is checked.

Thanks.