JavaScript验证和重定向无效

时间:2017-10-24 12:03:08

标签: 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("Password empty")。如果是其他,我希望脚本在当前页面中加载window.document.keeper.page.value + '.php'

2 个答案:

答案 0 :(得分:0)

if condition重新获取==并检查this.value==null

所以它会起作用

<form name="keeper" action="javascript:if(this.value=='' || this.value==null){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>

答案 1 :(得分:0)

内联action阻止是非常难以理解的,不推​​荐使用。有更好的方法来做到这一点,更多地遵守标准。请做这样的事情:

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>