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

怎甘沉沦 提交于 2019-12-05 12:24:20

问题


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"); }
        }
    ] });
});

回答1:


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>



回答2:


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)




回答3:


I ended up doing this:

<input type="text" style="position: fixed; left: -10000000px;" disabled/>



回答4:


A solution is to set tabindex="-1" on ALL input fields to keep HTML placeholders visible.




回答5:


You can use jquery:

jQuery(document).ready(function(e) {
   $('input[name="login_id"]').blur(); 
});

This if you find it hard to trace the bug why autofocus is set into your first input field of the form. Make sure to insert this code before the closing </body> body tag of your document.




回答6:


Without JQuery and JavaScript, we can give a CSS-only solution.

  1. remove all focus's outline

    :focus {
        outline: 0;
    }
    
  2. add the new focus's outline

    :link:focus, :visited:focus {
        outline: none;
    }
    


来源:https://stackoverflow.com/questions/7827004/how-to-avoid-automatic-focus-on-first-input-field-when-popping-a-html-form-as-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!