svager
svager

Reputation: 779

jQuery validate plugin fails to ignore checkbox

I have an AJAX form where I have tons of text fields. These text fields validate just fine with no issues however as soon as I add a checkbox via MVC framework(resulting HTML code bellow).

<input id="NotifyLocation" class="check-box" type="checkbox" value="true"
 name="NotifyLocation" data-val-required="The NotifyLocation field is required." 
 data-val="true" checked="checked"></input>

jQuery plugin throws an error from within this code inside of the plguin.

attributeRules: function(element) {
    var rules = {};
    var $element = $(element);

    for (var method in $.validator.methods) {
        var value;
        // If .prop exists (jQuery >= 1.6), use it to get true/false for required
        if (method === 'required' && typeof $.fn.prop === 'function') {
            value = $element.prop(method);
        } else {
            value = $element.attr(method);
        }
        if (value) {
            rules[method] = value;
       //ERROR is thrown on the next line
        } else if ($element[0].getAttribute("type") === method) {
            rules[method] = true;
        }
    }

    // maxlength may be returned as -1, 2147483647 (IE) and 524288 (safari) for text inputs
    if (rules.maxlength && /-1|2147483647|524288/.test(rules.maxlength)) {
        delete rules.maxlength;
    }

    return rules;
}

The error message is "TypeError: $element[0] is undefined". I have tried adding the following code to force jQuery to ignore the checkbox in my ready method

 $("#frmAjaxLocationUpdater").validate({
        ignore: "#NotifyLocation *"
    });

but still I get the same error within jQuery validation plugin. I have tried to add rules by class still same issue. According to numerous posts this should work but it doesn't.

Any ideas what is going on ? What can cause this?

Thank you.

Upvotes: 0

Views: 1343

Answers (1)

svager
svager

Reputation: 779

Here is a piece of JavaScript code that solved my issue

document.getElementById("NotifyLocation").setAttribute("data-val","false") ;

Upvotes: 1

Related Questions