MKaama MKaama - 9 months ago 42
HTML Question

How to focus a newly created field in a HTML form?

I want to dynamically add input fields to a html form, when user clicks on a link. The newly created fields should receive keyboard focus.

The answer from How to Set Focus on Input Field using JQuery does not work for me (nor any other on StackOverflow). The newly created field does not receive keyboard focus. Tested in Firefox 43.0.1 and Chromium 18. Firefox starts to find text when I type (like CTRL+F), Chromium does nothing. I tried the code from a local file and through a webserver, with various versions of jQuery.

function addfield() {
n = $('table#t1 tr').length;
$('table#t1').append('<tr><td><input name=field'+n+' ></td><td><input name=value'+n+'></td></tr>');

a { background: tan; }

<script src=""></script>
<table id=t1>
<div><a onclick='addfield();return false;'>Add field</a></div>


You seems to have an issue regarding the name property in your jQuery selector which is supposed to focus the newly added field. The " part of the selector is misplaced.

You current code is


It should be:


You can check this JSFiddle for an example.