Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid automatic focus on first input field when popping a HTML form as a JQuery dialog?

I have seen similar questions on SO, including this one, which is old. I read and followed links, but it is unclear whether there is a proper solution to this issue today.

My bottom issue is that I am using HTML's placeholder="..." on the input fields. By focusing automatically on the first field, its placeholder is not visible to the user anymore.

EDIT

Here is my HTML code:

<div id='LOGIN_FORM' title="Login">     <form action="">         <input type="text" name="login_id" required="required"                            placeholder="Enter user ID" /><br />         <input type="password" name="login_pwd" required="required"                            placeholder="Enter password" /><br />     </form> </div> 

Here is my JS code:

$("#login").click(function() {      $("#LOGIN_FORM").dialog({ modal: true }, { buttons: [     {             text: "Ok",             click: function() { $(this).dialog("close"); }         }     ] }); }); 
like image 667
Jérôme Verstrynge Avatar asked Oct 19 '11 19:10

Jérôme Verstrynge


People also ask

How do you remove input field focus?

The blur() method removes focus from an element.

How do you change the initial focus in HTML?

The autofocus attribute is a boolean attribute. When present, it specifies that an <input> element should automatically get focus when the page loads.

Does autofocus attribute always set focus on first input field in html5?

The first input or textarea in source order that has the autofocus attribute will be focused on page load. In browsers without autofocus support, no fields will be focused on page load, unless otherwise given focus with JavaScript.


2 Answers

What I did was I created an extra input and made it invisible (style="display:none") then gave it the property autofocus="true" put this at the end of your dialog content so it wont mess with anything. it should look like this:

        <div><!--dialog div-->            <button></button>            <button></button>            <input type="hidden" autofocus="true" />         </div> 
like image 146
Tyler Richardson Avatar answered Oct 12 '22 03:10

Tyler Richardson


Adding this tag as the first input field on the page works for me.

<input type="text" autofocus="autofocus" style="display:none" /> 

No need for javascript and keeps the tab order if you want to use the tab key to move through the fields.

(Tested on Chrome > 65, Firefox > 59 and Edge)

like image 38
Miguel Avatar answered Oct 12 '22 03:10

Miguel