Richard Ev
Richard Ev

Reputation: 54167

Adding jQuery conditional validation to dynamically-generated HTML

I have the following HTML scenario:

<div>
    <input id="txt0" type="text" /><input type="checkbox" id="chk0" /></div>
<div>
    <input id="txt1" type="text" /><input type="checkbox" id="chk1" /></div>
<!-- etc -->
<div>
    <input id="txtN" type="text" /><input type="checkbox" id="chkN" /></div>

If checkbox N is checked, then textbox N is a mandatory field.

I've just started to work with a (the?) jQuery validation module and am trying to figure out how to achieve this validation, which seems just that bit more complex than the examples.

Conceptually I think I want to add a CSS class to my checkboxes, then use addClassRules to add a custom rule. However, the challenge is how to specify the relevant textbox for each checkbox.

My HTML is generated using ASP.NET MVC, so I could dynamically generate the JavaScript that would specify a rule for each checkbox, but this seems a bit long-winded.

Upvotes: 2

Views: 1770

Answers (2)

Richard Ev
Richard Ev

Reputation: 54167

Solved, using the following approach...

I updated my HTML to include a specific CSS class to my textboxes (amount_text_box), and used the following jQuery:

$.validator.addClassRules("amount_text_box", { required: function(element) {
    var chkId = element.id.replace(/txt/, "#chk");
    return $(chkId)[0].checked;
}

One limitation is that this only fires when focus leaves the textbox - ideally the rule would also fire when the checkbox was clicked.

Upvotes: 1

Daniel Elliott
Daniel Elliott

Reputation: 22887

I have done a similar thing, Richard. Although I stoppped short of the custom rule. My approach was to add the class 'required' to the input tag.

In terms of your selector, could you not have your textbox and input "share" a class unique to them say class0 .. classN and select an input within that class?

Kindness,

Dan

Upvotes: 1

Related Questions