rkevx21
rkevx21

Reputation: 3919

focus input after reloading

I need some help, how can focus() a field (itself after fill) after reloading, since I already set another focus() a field in default.

<form>
  Default: <input type="text" name="reload_1" id="default"><br>
  Reload: <input type="text" name="reload_2" id="reload">
</form> 

<script>
  document.getElementById("default").focus();
</script>

The form has a script that after fill in the field since it is suggestion especially in id="reload" will reload, I want that to be focus not the id="default".

Upvotes: 3

Views: 12201

Answers (4)

Rajesh kumar
Rajesh kumar

Reputation: 69

I know the answer has already been choosen but why are we not going with "autofocus" attribute? It persists after page reload as well..

 <input type="text" id="fname" name="fname" autofocus>

Upvotes: 3

Ajay Peter
Ajay Peter

Reputation: 153

put your code inside document.onload function

document.onload=function(){
 document.getElementById("default").focus();
}

Upvotes: 0

andrey.shedko
andrey.shedko

Reputation: 3238

  1. Save element id in localStorage.
  2. OnLoad get element id from localStorage and set focus to element.

Upvotes: 1

aelgoa
aelgoa

Reputation: 1201

you could store a value in the window.name property to emulate a session variable

...
document.getElementById(window.name==='reload'?'reload':'default').focus();
window.name='reload';
...

http://blogs.sitepointstatic.com/examples/tech/js-session/index.html

Upvotes: 3

Related Questions