keyz.Mist keyz.Mist - 14 days ago 9
PHP Question

Multiple form dynamic field javascript validation

I have multiple form like this:

<?php for($i=0;i>n;i++){ ?> // n is no. of value (no limit)
<form>
<input name="<?php echo i; ?>venue" type="text">
<input name="roster" type="text">
<input type="submit" name="btn_venue">

</form>
<?php } ?>
<form>
<input name="hospitality" type="text">
<input name="template" type="text">
<input type="submit" name="btn_hospitality">
</form>
...
...
<form>
<input name="element" type="text">
<input name="alignment" type="text">
<input type="submit" name="btn_xyz">
</form>


I want validate(field should not be blank) in all form so, how can I use validation ?

I tried jQuery validation:

$('document').ready(function () {
$('form').each(function (key, form) {
$(form).validate({
rules: {
'hospitality': {
required: true
},
...
...
'alignment': {
required: true
}
});
});
});


I have manage static name field validation but I don't idea about dynamic venue name validation.Can anyone help me ?

if only one form the easily maintain but dynamically multiple form submit validate how to validate.

at a time only one form submit but particular form field validate how it is possible?

Answer

Try this. It goes through each form and for each of them through each input (of type text) and builds a required rule for each of them. Then feeds the dynamically built rules to the validate function.

$('document').ready(function () {
    $('form').each(function (key, form) {
        // build the rules object dynamically
        var rules = {};
        // loop through each input in the form
        $(form).find('input[type="text"]').each(function(idx, obj) {
            // make a rule for this input
            rules[obj.name] = {"required": true};
        });
        $(form).validate({
            "rules": rules
        });
    });
});