tags:

views:

52

answers:

4

Hi folks,

I am facing an issue with this simple jQuery code.

I have attached the HTML structure as well,

The code is setting focus to the input field fine if I make a click anywhere on the div with id "scroll-pane", but if I click anywhere else in the screen, for example, code above the div id "scroll-pane", it doesnt bring the focus. what am I doing wrong here?

<script language="javascript">
$(function()
{
    $('.scroll-pane').jScrollPane();
    $('#outerBody').keydown(function() {
      $('#serialCode').focus();      
    });
});
</script>

<center id="outerbody">
<table id="tab1" class="Tab1" width="100%">
<tr>
    <td width="60"></td>
    <td width="113"><p align="center">C</td>
    <td width="105">&nbsp;</td>
</tr>
</table>

<table  id="tab2" class="Tab2" border="0" width="100%">
<tr>
    <td>&nbsp;</td>
    <td>A </td>
    <td>B </td>
    <td><input type="text" id="serialCode" class="serialCode" /></td>
</tr>
</table>

<div id="scroll-pane" class="scroll-pane">

</div>

A: 

Try $('#serialCode')[0].focus();

Calling focus on the jQuery object fires events associated with focus. You need to call focus on the dom element.

Stefan Kendall
Hi Stefan, I didnt get your reply. Could you please explain again.
t3ch
Hi Stefan, just tried your solution, it didnt work for me. My requirement is, as soon as user presses a key, that keys value should be shown in the input box.
t3ch
A: 

bind focus event on document.

Praveen Prasad
Hi Praveen, something like this? $.keydown(function() { $('#inputScanner').focus(); });
t3ch
Nah. He means $(document).keydown(). You'll likely still need to modify your call to focus as I showed in my post.
Stefan Kendall
+1  A: 

Either close the tag (</center>), or put the "outerBody" class on a div, Or:

<script language="javascript">
$(function()
{
    $('.scroll-pane').jScrollPane();
    $('#tab1,#tab2,#scroll-pane').keydown(function() {
      $('#serialCode').focus();      
    });
});
</script>
Nico
Hi Nico, Replaced center with DIV, still didnt work
t3ch
Tried this approach, $('#tab1,#tab2,#scroll-pane').keydown(function() { Didnt work either, focus is only going to input field, if I click inside the DIV
t3ch
your problem is keydown doesn't trigger for a context unless you are focused on an element that can have the focus on that context, I'm sure if you add an input to one of the tables and press a key on it, it will take you to the serial code input
Nico
A: 

Why not attach the keydown event to the entire document window?

$(document).keydown(function() {
  $("#serialCode").focus();
});​

This might work, or help you figure it out.

view: http://jsbin.com/iwuwa4
edit: http://jsbin.com/iwuwa4/edit

Sandro
Hi Sandro, worked perfectly, thanks :)
t3ch