php - Next Focus Input Field on KeyPress Enter
one text
Solution:
I hope this is what you want.
I've added this code to make the focus event on enter press:
$(document).on("keypress",".name_list",function(e) {
if (e.which == 13 ){
$(this).closest("tr").next().find(".name_list").focus()
}
});
And for the focus part when you click on add button:
$('#dynamic_field').find(".name_list").filter(function() { return $(this).val() == "" }).first().focus();
Demo
$(document).ready(function() {
var i = 1;
$('#add').click(function() {
i++;
$('#dynamic_field').append('<tr id="row' + i + '"><td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove">X</button></td></tr>');
$('#dynamic_field').find(".name_list").filter(function() { return $(this).val() == "" }).first().focus();
});
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
});
$(document).on("keypress",".name_list",function(e) {
if (e.which == 13 ){
$(this).closest("tr").next().find(".name_list").focus()
}
});
$('#submit').click(function() {
$.ajax({
url: "name.php",
method: "POST",
data: $('#add_name').serialize(),
success: function(data) {
alert(data);
$('#add_name')[0].reset();
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div class="container">
<br />
<br />
<h2 align="center">Dynamically Add or Remove input fields in PHP with JQuery</h2>
<div class="form-group">
<form name="add_name" id="add_name">
<div class="table-responsive">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td><input type="text" name="name[]" placeholder="Enter your Name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>
</tr>
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
Source