Adding jQuery conditional validation to dynamically generated HTML

I have the following HTML script:

<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 the N box is checked, then the N input field is required.

I just started working with the module (<? Href = "http://bassistance.de/jquery-plugins/jquery-plugin-validation/" rel = "nofollow noreferrer"> jQuery validation and trying to figure out how to achieve this validation which seems just more complicated than the examples.

It is clear that I want to add a CSS class to my checkboxes and then use it addClassRules

to add a custom rule. However, the problem is how to specify the appropriate text box for each checkbox.

My HTML is generated using ASP.NET MVC, so I can dynamically generate JavaScript that will specify a rule for each checkbox, but that seems a bit long.

+2


source to share


2 answers


Solved using the following approach ...

I updated my HTML to include a custom CSS ( amount_text_box

) class in my text boxes 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 the focus leaves the text field - ideally, this rule also fires when the checkbox is clicked.

+1


source


I did a similar thing, Richard. Even though I don't follow the rules. My approach was to add the 'required' class to the input tag.

From the point of view of your selector, could you not have a textbox and enter a "generic" class unique to them, say class0 .. classN and select an entry in that class?



Kindness,

Dan

+1


source







All Articles