JavaScript
Article

jQuery check if item is currently selected

By Sam Deering

jQuery code snippets to check if element is selected (could be used to check if input is focused as well).

//this is one way to do it
console.log($(this).is(":focus"));

//this is another way
function itemHasFocus(id)
{
    var output = false;
    console.log(id);
    //loop for all fields in the form
    $.each($('#'+id+' :input'), function(i,v)
    {
       console.log($(this).is(":focus")); //check item has focus
       if ($(this).is(":focus"))
       {
         output = true;
         return false; //return false skips out of the loop
       }
    });
    return output;
}
//returns true or false

No Reader comments

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.