javascript 如何在文本字段中设置焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14092055/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:41:07  来源:igfitidea点击:

How to set Focus in a textfield

javascript

提问by Sanchita

I have a sign up form. I want to implement some validation at client end itself. I am using a button to submit a form.

我有一个注册表单。我想在客户端本身实现一些验证。我正在使用按钮提交表单。

<button onclick="check_fields();"></button>

 function check_fields() {          
       if(document.contact_form.name.value=='')                                                     
           document.contact_form.name.focus();
       else 
           document.getElementById("contact_form").submit();    
   }

Focus is not happening, instead form is successfully submitting. Please help.

焦点没有发生,而是表单成功提交。请帮忙。

回答by Praveen Kumar Purushothaman

The best way to do is using an id

最好的方法是使用 id

Say, you have the textfield defined this way:

说,你有这样定义的文本字段:

<input type="text" name="contact" id="contact" />

In your JavaScript, it would be nice to give this way:

在您的 JavaScript 中,最好以这种方式给出:

document.getElementById("contact").focus();

回答by asgoth

Because document.contact_form.nameis probably not your textfield. What is your input field's name attribute?

因为document.contact_form.name可能不是您的文本字段。您输入字段的名称属性是什么?

If its name is e.g. myfield, you should use:

如果它的名字是例如 myfield,你应该使用:

if(document.contact_form.myfield.value === '') {
   document.contact_form.myfield.focus();
} else { ... }

回答by Iftah

It should work if you setup the html part correctly. If not you should see javascript exceptions in developer console (in chrome or firefox).

如果您正确设置了 html 部分,它应该可以工作。如果没有,您应该在开发者控制台(在 chrome 或 firefox 中)中看到 javascript 异常。

Note that you access the form in two ways, one document.contact_formsuggests you have name="contact_form" and one document.getElementById("contact_form")suggests you have id="contact_form", did you set both ways in the html? ie. are both name and id set for the form element?

请注意,您以两种方式访问​​表单,一种document.contact_form建议您有 name="contact_form" ,另一种document.getElementById("contact_form")建议您有 id="contact_form",您是否在 html 中设置了两种方式?IE。是否为表单元素设置了 name 和 id?

回答by Mrugen Deshmukh

Hi it looks like you are trying to transfer focus on form element on validation errors. I would suggest that you transfer control over to a input element which is part of your "form" element.

嗨,您似乎正在尝试将注意力转移到表单元素上的验证错误上。我建议您将控制权转移到作为“表单”元素一部分的输入元素。

Morever you can also validate the input on "onsubmit" event of the form rather than the button click. for example:

此外,您还可以验证表单的“onsubmit”事件而不是按钮单击的输入。例如:

<form name="myForm" onsubmit="return validate();"> </form>

//validate function on validation failure returns false else true.
// if validate returns false the browser wouldn't submit the form.

you can use following code snippet to get focus on element of your choice

您可以使用以下代码片段来关注您选择的元素

document.getElementById("elementId").focus();

回答by S. Mayol

I have this, I hope this help you, I use focus() in a JavaScript to prompt or set the focus in the and if I click on save or input button without supplying any value, an alert it will be trigger first then when you click ok, the focus will appear in the corresponding textfield:

我有这个,我希望这对你有帮助,我在 JavaScript 中使用 focus() 来提示或设置焦点,如果我点击保存或输入按钮而不提供任何值,警报将首先触发,然后当你单击确定,焦点将出现在相应的文本字段中:

<script type="text/javascript">
         function validate() /* Validate the if the user leave any field empty. */
         {
             var a = document.getElementById("userid");
             var b = document.getElementById("passwrd");
             var c = document.getElementById("fname");
             var d = document.getElementById("lname");
             var e = document.getElementById("email");
             var f = document.getElementById("phnno");
             var g = document.getElementById("cellphone");
             var h = document.getElementById("fax");
                          
             var valid = true;
             if(a.value.length<=0) {
              a.focus();
                 alert("Don't leave 'USER NAME' field empty!");
                 valid = false;
             }
             else if(b.value.length<=0){
              b.focus();
                 alert("Don't leave 'PASSWORD' field empty!");
                 valid = false;
             }
             else if(c.value.length<=0){
              c.focus();
                 alert("Don't leave 'FIRST NAME' field empty!");
                 valid = false;
             }
             else if(d.value.length<=0){
              d.focus();
                 alert("Don't leave 'LAST NAME' field empty!");
                 valid = false;
             }
             else if(e.value.length<=0){
              e.focus();
                 alert("Don't leave 'USER EMAIL' field empty!");
                 valid = false;
             }
             else if(f.value.length<=0){
              f.focus();
                 alert("Don't leave 'PHONE NUMBER' field empty!");
                 valid = false;
             }
             else if(g.value.length<=0){
              g.focus();
                 alert("Don't leave 'CELLPHONE NUMBER' field empty!");
                 valid = false;
             }
             else if(h.value.length<=0){
              h.focus();
                 alert("Don't leave 'FAX NUMBER' field empty!");
                 valid = false;
             }
                          
         return valid;
         };
         
     </script
<s:form action="userAction_createUser" method="get"  name = "userForm" accept-charset="utf-8" onsubmit="return validate();">
               
            <!-- Display the values in the application -->
                        <table class="createUserT">
       <s:textfield name="user.userid" id="userid" cssClass="tb5" label="User Name" /> 
       <s:textfield name="user.passwrd" id="passwrd" cssClass="tb5" label="Password" type="password"/>
       <%-- <s:textfield name="user.passwrd" cssClass="tb5" label="passwrd" type="password"/> --%>
      </table>
      <table class="createUserT">
          <s:textfield name="user.fname" id="fname" cssClass="tb5" label="First Name"/>
          <s:textfield name="user.lname" id="lname" cssClass="tb5" label="Last Name"/> 
      </table>
      <table class="createUserT">
       <s:textfield name="user.email" id="email" cssClass="tb5" label="User Email" type="email"/>
                            <s:textfield name="user.phnno" id="phnno" cssClass="tb5" label="Phone Number"/>
      </table>
      <table class="createUserT">
                            <s:textfield name="user.cellphone" id="cellphone" cssClass="tb5" label="Cellphone Number"/>
                            <s:textfield name="user.fax" id="fax" cssClass="tb5" label="Fax Number"/>
      </table>