简体   繁体   中英

Uncaught TypeError: obj.attr is not a function JS

I have the following code:

<input type="text" name="email" id="email" class="required-input" value="test@yahoo.com">
function validate(obj) {
    const email_regex = /^[\w\-\.\+]+\@[a-zA-Z0-9\.\-]+\.[a-zA-z0-9]{2,4}$/;
    if (obj.attr("id") == "email") {
        regex = email_regex;
    }

    (!obj.val().match(regex) || obj.val().length == 0 || obj.val() == '') ? obj.removeClass('valid').addClass('invalid'): obj.removeClass('invalid').addClass('valid');
}

$('.required-input').each(function() {
    $(this).on('input keyup keypress blur change', function() {
         validate(this);   //EROR HERE
    });
});

The error is as follows Uncaught TypeError: obj.attr is not a function

Do you know the origin of this error? It is wrong parameter function validated?

Please can you help me solve this problem?

Thanks in advance!

As obj is native DOM object you are getting the error. Convert it to jQuery object

$(obj).attr("id")

OR, Better pass jQuery object to validate function.

validate($(this));

this is a reference to the DOMElement which you're attempting to call jQuery methods on - hence the error. You need to pass a jQuery object to the method instead. Try this:

validate($(this));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM