Akshay Shrivastav Akshay Shrivastav - 27 days ago 5
jQuery Question

How to add multiple ID's in the ON function using JQUERY

This is my JQUERY CODE :

$("body").on("click keypress", "#admin-username",function(){
if($("#admin-username").hasClass("error")){
$("#admin-username").removeClass("error");
setTimeout("$('.message').slideUp('slow');", 50);
}
});


i have used an id
#admin-username
i.e only one id in the above JQuery code

where as in my Front-end code i have 3 input boxes

1.)
admin-username

2.)
admin-email

3.)
admin-password


however i want to achieve something like this

$("body").on("click keypress", "#admin-username, #admin-password, #admin-email",function(){
if($("#admin-username").hasClass("error")){
$("#admin-username").removeClass("error");
setTimeout("$('.message').slideUp('slow');", 50);
}
});


But if i use multiple id's like this then by default it is working only for the first id i.e
#admin-username


can anyone provide me a solution here ?

Answer

Your selector is corrent but you need to use this-inside the callback function to access the element that raised the event

$("body").on("click keypress", "#admin-username, #admin-password, #admin-email",function()
        {
            if($(this).hasClass("error"))
                {
                    $(this).removeClass("error");
                    setTimeout(function() {
                      $('.message').slideUp('slow');
                     }, 50);
                }
        });

Also "corrected" the setTimeout with a callback-function.

Comments