JavaScript 验证和重定向不起作用

标签 javascript html forms

此代码不起作用:

 <form name="keeper" action="
                 javascript:if(this.value='')
                 {alert('password empty');};
                 else{location.href = window.document.keeper.page.value + '.php';}" 
  style="margin:2vh;"> 
    <div style="display:inline;"> 
        <input type="text" name="page"> 
        <input type="submit" value="Go"> 

        <noscript>
            <div style="display:inline;color:#ff0000; background-color:#ffff66; 
  font:normal 11px tahoma,sans-serif;"> 
               <br> Javascript is required to access this<br>area. Yours seems to be disabled.
            </div>
        </noscript>
    </div>
 </form>

如果文本框为空,当提交表单时,我想alert("密码为空")。如果不是这样,我希望脚本在当前页面中加载 window.document.keeper.page.value + '.php'

最佳答案

该内联 action block 非常不可读,不推荐。有更好的方法可以做到这一点,并且更符合标准。请执行以下操作:

document.querySelector("form[name=keeper]").addEventListener("submit", function(e){
   var input = document.querySelector("input[name=page]");
  //e refers to the event - submit
  if (input.value == '')
  {
      alert("password empty");
  }
  else
  {
     location.href = input.value + '.php';
  }
  e.preventDefault();  //this will cancel the normal submit and execute the code above.
  return false;
})
<form name="keeper" style="margin:2vh;">
  <div style="display:inline;">
    <input type="text" name="page">
    <input type="submit" value="Go">

    <noscript>
  
      <div style="display:inline;color:#ff0000; background-color:#ffff66; font:normal 11px tahoma,sans-serif;"> <br>Javascript is required to access this<br>area. Yours seems to be disabled.</div>
  
    </noscript>
  </div>
</form>

关于JavaScript 验证和重定向不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46910091/

相关文章:

javascript - AngularJS 表单提交不起作用

javascript - 输入类型=带和不带表单标签的按钮

javascript - 服务器集合更改时的 meteor 触发事件

javascript - 使用服务器路由 react 路由器浏览器历史记录

html - 申请提交时的 css 样式与 href 不同

javascript - 在多步骤表单中使用 POST 时出现问题

html - 如何使用 CSS 仅将 HTML 选项元素的首字母大写?

javascript - 折线标签定位算法

javascript - 检查复选框是否被选中?

html - 我们如何验证密码为 css