简体   繁体   English

我已将焦点设置为返回输入框,但似乎没有焦点?

[英]I have set focus to return to input box but it does not seem to focus?

I have created a form with an input box, if the entry is invalid it will create an alert box, I want the focus to return to the input box, however, the code I have written doesn't seem to do it.我已经创建了一个带有输入框的表单,如果输入无效它会创建一个警告框,我希望焦点返回到输入框,但是,我写的代码似乎没有这样做。 I am sure it is correct.我确定这是正确的。

I have copied the code snippet below:我复制了下面的代码片段:

HTML: HTML:

<form name="myform" onsubmit="validate()"> 
            Amount   <input name="num" id="principal"><br/>  </form>


        

JS: JS:

function validate(){  
  var num = document.myform.num.value;  
  if (isNaN(num) || num == 0 || num < 0 || num == null) {  
    alert("Please enter a valid entry")
    document.getElementsById("principal").focus(); }
  else {  
    return true;  
    }  
  }  

Please can someone show me where I am going wrong?请有人告诉我我哪里出错了?

Do you have any error outputs in your console?您的控制台中是否有任何错误输出? "getElementsById" is not valid. “getElementsById”无效。 It should be "getElementById".它应该是“getElementById”。

You also should implement something to prevent the default submit behaviour.您还应该实施一些措施来防止默认提交行为。 Here you can find a adapted and working fiddle:在这里你可以找到一个改编的和工作的小提琴:

 document.getElementById('submitbutton').addEventListener('click',function(event){ event.preventDefault(); validate(); }); function validate(){ var num = document.myform.num.value; if (isNaN(num) || num == 0 || num < 0 || num == null) { alert("Please enter a valid entry") document.getElementById("principal").focus(); } else { return true; } }
 <form name="myform" onsubmit="validate()"> Amount <input name="num" id="principal"><br/> <button id="submitbutton">Submit</button> </form>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM