I have following form with an input field. I want to make sure that focus get set back to the same input after enter / submitting the form:
<form action="/a/message/new" method="post" id="myform">
<div class="form-group">
<div class="input-group">
<input name="body" id="myField" class="form-control" placeholder="Write message here..." /> <span class="input-group-btn">
<button class="btn btn-default" type="submit" value="{{ _(' Post ') }}">Submit</button>
</span>
<input type="hidden" name="next" value="{{ request.path }}"> {% module xsrf_form_html() %}
</div>
</div>
</form>
</div>
I tried doing following:
<script>
$(function() {
//Start check on form submit
$('#myform').submit(function(){
$('#myField').focus();
});
});
</script>
but this didn't work
When the submit event is fired the form will submit and refresh / change the page if its not prevented, you can prevent a form submit using event.preventDefault();
$("#myForm").submit(function(event) {
event.preventDefault();
});
This will however not - as just mentioned - submit the form, which is properly not what you want, unless you are making an ajax request. You can on page load set focus on an input field and that way "keep" the focus on the field:
$(function() {
$('#myField').focus();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With