I'm trying to add new input fields by pressing enter. Now, when I do press Enter, a new field is added, but the focus shifts directly to the Submit button, instead of to a newly added field. How can I prevent this?
Also, how can I add a sort of "prevention" so that a new field cannot be added, unless something has been written into the current one?
Here's how it currently works: JsFiddle
EDIT I also figure it out how to prevent adding the next field, if the current one is empty: JsFiddle
$(document).ready(function() {
$("#items").keypress(function(e) {
if (e.which === 13) {
e.preventDefault();
$('#items').append('<div><input id="sub" type="text" name="subtask">' +
'<input type="button" value="delete" id="delete" /></div>');
$(this).next().focus();
}
});
$("body").on('click', "#delete", function(e) {
$(this).parent('div').remove();
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<form action="">
<div id="items">
<input id="sub" type="text" name="subtask">
</div>
<input type="submit" value="submit">
</form>