I'm using Twitter Bootstrap for my UI, and am trying to use jQuery validation on my webforms. On some forms, I'm using a "btn-group" to provide input, but I'm struggling on how to use jQuery validation on the following HTML:
<div class="btn-group" id="divSaleType" data-toggle="buttons-radio" required="required" name="divSaleType">
<button name="New" class="btn btn-info SaleTypeToggle" id="ContentPlaceHolder1_ContentPlaceHolder1_btnNew" type="button">New</button>
<button name="Used" class="btn btn-info SaleTypeToggle" id="ContentPlaceHolder1_ContentPlaceHolder1_btnUsed" type="button">Used</button>
</div>
When a button is selected, the "active" class is appended to the chosen button, so that would be the "validation" Im looking for. I thought about using an approach similar to this: jQuery custom validation based on Class - where I would search for any "SaleTypeToggle" items that also have an "active" class, but don't know how to trigger such an event.
Any help is appreciated, thanks!
The jQuery Validate plugin is only meant for validating the data entered using the form's input elements. A
<button></button>
element is not a data input element... it's for triggering an action, therefore it is not something that would be part of any form validation.In other words, this plugin only validates the user data entered using these elements...
They must each contain a unique
name
attribute and also must be contained within a set of<form></form>
tags for the jQuery Validate plugin to operate.I was faced with the same issue, and while it is true that you can't validate a button, I was able to find a workaround.
I've posted a JSFiddle with the full example: http://jsfiddle.net/geekman/W38RG/17/
My solution is as follows:
I used a hidden element along with some simple jQuery to set the value of that hidden field each time a button was pressed (note: I removed the required attribute from divSaleType as it has no effect).
I then set the hidden field as the required element. I also add the value attribute to each button in the group, this is what I will set the value of the hidden field to.
Finally, I passed an option in to the jQuery validate plugin to tell it not to ignore hidden fields (which is the default). I simply passed an empty array to do this.
For me, this sufficiently validates the button group. Additionally, you get the added value of now having a HTML input that is POST'd to your webserver on submission, which you would have had to handle somehow with the button group as well either way.