Reputation: 1
On my work-through I tried to implement moving focus from one text field to another by pressing enter. I have found possible answers in the following links:
How to go to next textbox when enter is pressed?
Move Cursor to next text Field pressing Enter
But none of these are working for me. My code:
<script>
$('input[type='text']').keyup(function(e) {
if(e.keyCode == 13) {
$(this).next().focus();
}
});
</script>
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
<input type='text' />
Upvotes: 0
Views: 2543
Reputation: 4387
Here's what's happening:
<!-- Start loading the page -->
<script>
// execute javascript. Note that there
// are no inputs on the page currently - they will be loaded later
// This selector matches nothing:
$("input[type='text']").keyup(function(e) {
if(e.keyCode == 13) {
$(this).next().focus();
}
});
</script>
<!-- JavaScript executed. Now add inputs to the page -->
<input type='text' />
<input type='text' />
What you can do is either move the <script>
below the inputs (easiest) or move the keyup
listener to a onload function:
$(function(){
// i.e. wrap your js here
// the js here will be executed only after page has loaded
});
Upvotes: 0
Reputation: 2555
Just update $('input[type='text']')
to $('input[type="text"]')
. You had unclosed strings.
Working codepen here.
Upvotes: 1
Reputation: 447
$(document).ready(function () {
$('form').on('submit', function (event) {
event.preventDefault();
})
$('input[type="text"]').keyup(function(event) {
if(event.keyCode === 13) {
$(this).next().focus();
}
});
})
<script src="https://code.jquery.com/jquery-3.2.1.slim.js"></script>
<form>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
<input type="text"/>
</form>
Upvotes: 2