1

I am having an issue that once my page is rendered, the focus is not being set on the first input element of a dynamically created table/input.

In the .jsp I have the following:

<script type="text/javascript">
  $(document).ready(function(){

    if(_page != "one") {
      buildTable(shipQty);
      $('#shipItems[0].barCode').focus();
    }

</script>

There is an included .js which contains the buildTable function

function buildTable(shipQty)
{
  var _tbl = $('<table>').attr({
    id : 'barCodeTable',
    border : '1'
  });

  _tbl.append($('<tr>').append($('<td>').text('Box BarCode'),$('<td>').text('INBOUND Tracking Number')));

  for ( var _index = 0; _index < shipQty; _index++)
  {
    var _inputBarCode = $('<input>').attr({
            class : 'form-med',
            type : 'text',
            name : 'shipItems[' + _index + '].barCode',
            id : 'shipItems[' + _index + '].barCode',
            maxlength: '8'
        }).change(_barCodeChange);

    var _shippingTrackingCode = $('<input>').attr({
      class : 'form-med',
      type : 'text',
      name : 'shipItems[' + _index + '].shipCompanyBarCode',
      id : 'shipItems[' + _index + '].shipCompanyBarCode'
    }).change(_trackingNumberChange);

    _tbl.append($('<tr>').append($('<td>').append(_inputBarCode)).append($('<td>').append(_shippingTrackingCode)));

  }

  $('#tableWrap').append(_tbl);
}

I have taken a look at several different solutions here, here, here and others on stackoverflow but to no avail.

I do not understand the issue here.

Community
  • 1
  • 1
boyd4715
  • 2,701
  • 10
  • 48
  • 75

1 Answers1

4

It has nothing to do with the dynamic code. The problem is your jQuery selector does not match what you want. Your code is looking for an element with an attribute of zero.

You need to escape the ., [, and ].

$('#shipItems\\[0\\]\\.barCode').focus();

Running example: http://jsfiddle.net/NC4uz/


From the jQuery Selector docs:

To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^{|}~) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element withid="foo.bar"`, can use the selector $("#foo\.bar"). The W3C CSS specification contains the complete set of rules regarding valid CSS selectors. Also useful is the blog entry by Mathias Bynens on CSS character escape sequences for identifiers.

epascarello
  • 204,599
  • 20
  • 195
  • 236