Jquery – set focus on first checkbox if none selected

jquery

i was doing this in javascript, how can I set focus to first checkbox in jquery.

var chk = document.getElementsByName('program[]');
var len = chk.length;
var checked = false;
for(var i=0; i<len; i++) {
     if(chk[i].checked) {
        checked = true;
        break;    
      } 
}
if( !checked ) {
    chk[0].focus();
    document.getElementById('errpgm').innerHTML = "Please select at 
            least one program";
    errcount++;
}

Best Answer

Edit: My answer is valid assuming you want to focus when the page loads

Better use autofocus attribute.

In general, using javascript to set focus automatically isn't a good idea, because you have to wait until the element you want to focus has been loaded to the DOM. But if you wait to much, then the user could have focused another input, and your change of focus will be annoying.