My question is. I’ve a barcode-scanner on my website in order to verify if a student is in classroom. The INPUT element of my form must always have focus in order to recieve the code from the barcode-scanner.
My code is:
$("#codebarre").focus()
$("body").click(function(){
$("#codebarre").focus()
})
The second entry in order to recover the focus if i click on the page. My problem is: i have the possibility to write a comment in another input in the page. With my code, it’s true that just after a click in my input, #codebar recover focus and i’m not able to write in my input. So my need is: always focus in #codebar except if i click (focus) in my remark INPUT.
I try this:
$("#codebarre").focus()
$("body").click(function(){
if( !$(".remark").focus() ){
$("#codebarre").focus()
}
})
My code don’t work. Can you tell me what I’m doing wrong ?
You can’t determine if a control has the focus in that manner. focus() will only set the focus to that control. See this answer for a detailed explanation of how to determine if a control has the focus: Using jQuery to test if an input has focus
If you are using jQuery 1.6, you should be able to do:
EDIT
If you are using an earlier version of jQuery, you can use
$(document.activeElement)to determine which control has the focus. In that case, the code should be: