MKaama MKaama - 3 months ago 13
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>');
$('input[name="field"'+n+']').focus();
}


a { background: tan; }


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<table id=t1>
<thead>
<tr>
<th>field</th>
<th>value</th>
</tr>
</thead>
<tbody>
<tr>
<td>Bill</td>
<td>bill@yahoo.com</td>
</tr>
</tbody>
</table>
<div><a onclick='addfield();return false;'>Add field</a></div>



Answer

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

$('input[name="field"'+n+']').focus();

It should be:

$('input[name="field'+n+'"]').focus();

You can check this JSFiddle for an example.