简体   繁体   中英

Autofocusing on a newly added element via javascript

This should be simple but I can't get it to work so would appreciate any pointers.

I have a function in my webpage that adds a new line into a table with inputs etc. This is a pretty basic POST that looks something like this...

$.post(url, {
    newRow : newRow
}, function(data) {
    $('#' + tableName + ' > tbody > tr').eq(rowLoc).before(data);
}).done(function() {
    reNumberTableIDName($tb)
});

The reNumberTableIDName function is pretty straightforward, it runs through all the objects in the table and changes their id/name so that they are in order relevant to the row they are in the table for other reasons.

Now, one of the elements added in to this table is an auto complete input which looks like so...

<input id="autoLook[9]" class="required yui-ac-input" type="text" title="" value="" name="autoLook[9].id" style="width:500px" autocomplete="off" required="required">

Note that the name and ID are not altered as part of the reNumberTableIDName function.

I tried adding in a line to the "done"portion of the post to then put the focus/carat into that new input but it doesn't work (focus stays on the button previously clicked to add the row).

$("#autoLook[" + (newRow -1) + "]").focus();

I've checked with an alert that "#autoLook[" + (newRow -1) + "]" does indeed come up with the right string so I'm at a loss as to why this doesn't work. What obvious litle gotcha am I missing?

Its also worth noting that I tried to add in a autofocus property to the input being added, but I'm working in grails and this type of auto complete doesn't allow me to do this.

Thanks!

Worth noting that the solution should be to use setTimeout as mentioned below else it will continually put focus back to the object!

The selector #autoLook[9] matches an element with the id autoLook and the attribute 9 ; which is obviously wrong. Add backslashes around the square brackets to escape them:

$("#autoLook\\[" + (newRow - 1) + "\\]").focus();

Quote from jQuery Documentation: Selectors :

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 with id="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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM