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>
Advertisement
Answer
You should give classes to your recurring elements,because when adding them you end up with multiple of the same id’s,which are supposed to be unique.
Your
keypress
event,targets#items
div and when you ask to give focus on thenext()
item,at the time of the event keypress the next item is the submit button.
3.You can also exclude an item from being focused,just give it the tabindex
attribute and set a negative value,for example -1 (see snippet)
$(document).ready(function () { $("#items").keypress(function(e) { if (e.which === 13) { e.preventDefault(); $('#items').append('<div><input class="sub" type="text" name="subtask">' + '<input type="button" value="delete" class="delete" /></div>'); $(".sub").last().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 class="sub" type="text" name="subtask"> </div> <input tabindex="-1" type="submit" value="submit"> </form>