Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

keep focus to same input field after submit/enter [closed]

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

like image 504
CurlyHead Avatar asked May 17 '26 20:05

CurlyHead


1 Answers

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();
});    
like image 151
Andreas Louv Avatar answered May 19 '26 10:05

Andreas Louv