1

I want to focus on specific id (ex. using $('#a')) after submit.

There is nothing special with my code yet.

My javascript code is

function get_info(id){
    $(user_id).submit();
    $('#a).focus();
};

After submit, it should focus on where id='a'.

But after submit window focus on id='a' and reset the page.


I tried using

function get_info(id){
    $(user_id).submit(function(e){
      e.preventDefault();
      $('#a').focus();
   });
};

But this code make program worse. I think it stops performing submit.

Can anyone help me?

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Junie
  • 59
  • 2
  • 10
  • 4
    Submitting a form makes the browser navigate to the URL stated in the form's `action` attribute. So unless you send the form data with AJAX, focusing on a field after submission is impossible. Please ask about your actual problem, not about your attempt at solving it (see: [XY problem](http://xyproblem.info/)) –  Dec 31 '18 at 15:11
  • If you want to focus on a previously determined field after submission i.e. on pageload, the question becomes about persisting a JS value, see here: https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads –  Dec 31 '18 at 15:43

2 Answers2

1

As Chris's comment says you couldn't focus on the element simply by using $('#a').focus(); after the submit since the page will be redirected/refreshed.

You need to use cookies or local storage, here a suggested sample using local storage like :

function get_info(id) {
    localStorage.setItem('focusItem', '#a');

    $(user_id).submit();
};

Then in the ready function, you could add :

$(function(){
    var focusItem = localStorage.getItem('focusItem');
    if( focusItem != null ){
        $(focusItem).focus();
        localStorage.removeItem('focusItem');
    } 
});
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
  • If this is what the OP is looking for, this question is a dupe: https://stackoverflow.com/questions/29986657/persist-variables-between-page-loads –  Dec 31 '18 at 15:21
0

function SetFocus(){    
$("#FocusingID").focus();}  

/***********another way **********************//*
  $("#submitbtnId").click(function(){    
  //your submession and other task;    
  $("#FocusingID2").focus();    
});
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type=text id=FocusingID>
<button type=submit onclick="SetFocus();">click</button>
Aishwarya
  • 637
  • 9
  • 21