简体   繁体   中英

How to check element triggered by onBlur has certain class with jQuery

HTML

   <input type="text" id="trainingFee" name ="training Fee" class="number error" value="" onblur="callMe()">

jQuery

    function callMe(){
       if($this.id).hasClass('error')){
        alert("has error class");       
 }

}

but this is not working. What am I doing wrong?

You are trying to access the current id of the element using the this context.. You need to pass it to the function in order to do it

onblur="callMe(this)"

 function callMe(elem){
       if($(elem).hasClass('error')){
        alert("has error class");       
 }
}

Otherwise you can try this approach

FIDDLE

$(function() {
    $('#trainingFee').on('blur', function() {
        if ($(this).hasClass('error')) {
            alert("has error class");
        }
    });
});​

<input type="text" id="trainingFee" name ="training Fee" class="number error" value=""  /> 

You should remove the onblur attribute from HTML and just do it all with jQuery.

$('#trainingFee').blur(function () {
    if ($(this).hasClass('error')) {
        alert('has error class');
    }
}​);​

You can try:

if ($(this).is('.error')) {
  ...
}

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