Un-Select a Radio-Button by clicking on it

Problem

The situation is kind of odd however, not uncommon, atleast, I would think so. We have got a Radio Button inside each row of a GridView. As per the requirement, user should be able to select only 1 radio button at a time. This has been achieved with javascript. More details can be found here. Now selecting radio button indicates the selection for that row of the gridview. Similarly, there should be an option for dis-selecting the radio button by clicking on the selected radio button (much like the checkboxes). However, this is against the normal behaviour of the radio button, and obviously there was no simple way of doing it. So I decided to put a check on the OnClick property of the Radio Button. The check was like this


if (rdBtn.checked == true {
	rdBtn.checked = false;
}

However, because of this, I was not able to select the Radio Button in the first place. Unlike, checkbox, once checked, a radio button will always return true when it is checked and my script was simply clearing the checked state thereby, not letting me select any option.

Solution

After doing a bit of R&D I realized that instead of making things complicated, I should put a simple check, & instead of relying on the checked property of the radio button I will check the id of the current selected radio button. If the current radio button’s id matches with that of the hiddenField value, I will simply clear the check of that radio button


<script language="javascript" type="text/javascript">
	function SelectSingleRadiobutton(rdbtnid) {
		var hd = document.getElementById('hdnFld');
		var rest = false;
		var rdBtn = document.getElementById(rdbtnid);
		var rdBtnList = document.getElementsByTagName("input");
		for (i = 0; i < rdBtnList.length; i++) {
			if (rdBtnList[i].type == "radio") {
				if (rdBtnList[i].id != rdBtn.id) {
					rdBtnList[i].checked = false;
				}
				else if (hd.value == rdBtnList[i].id) {
					rdBtnList[i].checked = false;
					rest = true;
				}
			}
		}
		hd.value = (rest) ? "" : rdbtnid;
	}
</script>

Inside the GridView’s ItemTemplate I have called the above script for the OnClick event of the Radio Button


<asp:TemplateField>
	<ItemTemplate>
		<asp:RadioButton ID="rdbOptions" runat="server" OnClick="javascript:SelectSingleRadiobutton(this.id)" />
	</ItemTemplate>
	<ItemStyle HorizontalAlign="Center" />
</asp:TemplateField>

That’s it …

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s