Using depends with the jQuery Validation plugin

Posted by Glenn Slaven on Stack Overflow See other posts from Stack Overflow or by Glenn Slaven
Published on 2008-12-19T00:57:46Z Indexed on 2010/04/11 5:33 UTC
Read the original article Hit count: 999

I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.

When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.

When I click the checkbox and disable the textbox, I still get the invalid field error despite the depends clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.

Here is a sample of the list of checkboxes & textboxes:

<ul id="ItemList">
<li>
	<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
	<input name="OneSelected" type="hidden" value="false" />
	<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
	<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
	<input name="TwoSelected" type="hidden" value="false" />
	<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>

And here is the jQuery code I'm using

//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
	var textBox = jQuery(this).siblings(':text');
	textBox.valid();
	if (!jQuery(this).attr("checked")) {
		textBox.attr('disabled', 'disabled');
		textBox.val('');
	} else {
		textBox.removeAttr('disabled');
		textBox[0].focus();
	}
});

//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
	jQuery(this).rules('add', {
		required: {
			depends: function(element) {
				return jQuery(element).siblings(':checkbox').attr('checked');
			}
		},
		number: {
			depends: function(element) {
				return jQuery(element).siblings(':checkbox').attr('checked');
			}
		}
	});
});

Ignore the hidden field in each li it's there because I'm using asp.net MVC's Html.Checkbox method.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery