How to uncheck checkbox in custom form elements using JavaScript

Ryan Fait has added a wonderful script which can help you customize the look and feel of the form elements on your web page like check boxes, radio buttons and select drop downs. The name of the script is custom form elements and there is a nice example on his website which shows you how to use it on your web page.

I was working on a project which required me to uncheck a check box upon the click of another check box. I was using jQuery for this purpose. I thought this would be a simple task and I would just need to use the attr() method to uncheck the checkbox however this was not working properly. The code executed however the actual uncheck action happened after I clicked some where on the web page.

I then re-read Ryan’s web page especially this paragraph

How does it work?

In a nutshell, the JavaScript looks for every form element with class=”styled” on it; hides the real form element; sticks a span tag with a CSS class on it next to the element; and, finally, mouse events are added to the span that handles the visual stages form inputs go through when they are clicked.

This was the HTML written on the web page before the page was loaded in the browser

Select required options

  • Option A

  • Option B

  • Option C

  • Option D

After loading the web page in the browser the HTML became


Select required options

  • Option A

  • Option B

  • Option C

  • Option D

I added the following JavaScript event handler code for the span tag which unchecked the check box I wanted to uncheck.

$("span.checkbox").live('click',function () {
        var new_label = $(this).prevAll('p:first');
        if ($(this).next('input').is(':checked')) {
		if (new_label == "Option A") {
			if ($(":checkbox[value='Option C']").is(':checked')) {
				$(":checkbox[value='Option C']").prev('span').trigger("onmouseup");
			}	
		}
		else if (new_label == "Option C") { 
			if ($(":checkbox[value='Option A']").is(':checked')) {
				$(":checkbox[value='Option A']").prev('span').trigger("onmouseup");
			}	
		}

        }
});

After adding the above code the check box check and uncheck feature started to work properly.

Please follow and like us:

1 Comment

Leave a Reply

Your email address will not be published.


*