【问题标题】:form validation javascript stop new window from opening表单验证javascript阻止新窗口打开
【发布时间】:2014-09-11 03:07:35
【问题描述】:

作为我的第一个 JavaScript 项目,我编写了一个包含表单的大页面。我在这里得到了一些帮助,所以谢谢。我对目前所拥有的一切感到非常满意,但我还有最后一个问题需要解决。

我将在这里提交的代码是一个测试器。我有几个附加到 onClick 新窗口的功能。发生的情况是用户提交表单并且他们的信息出现在新窗口中。 (当然,我的原始页面更复杂。)如果为“状态”输入了特定值,则有一个名为 askForHelp 的函数会在新窗口中显示警报,还有一个非常简单的 validateForm 会在父级上显示警报?如果值留空,则窗口。

问题是 b/c 我的所有功能都在 onClick 上运行,我意识到它们同时运行,无论用户做什么,新窗口都会打开(警报显示在各个位置)。

基于此处的其他类似问题,我尝试在条件句中添加 return false 和 return true 语句,但这没有做任何事情。

现在我知道有更好的方法来做我正在做的事情,而且我的表单验证是基本的和薄弱的,但作为我第一次涉足编程,了解我所做的一切对我来说非常重要,到目前为止,我就是这样做的。

谁能告诉我如何解决这个问题,以便只有在表单验证时才会打开新窗口?如果可能的话,我宁愿没有 jquery 或没有激进的机会来编写代码。

感谢大家的意见。代码如下:

   <!doctype html>
      <html>
         <head>
           <title>test</title>
            <meta charset="utf-8">

       <script type="text/javascript">

          function newWindow() {
            allInfo= open("", "displayWindow");

              allInfo.document.open();

          allInfo.document.write('<!doctype html><html><head><title>Test</title><meta charset="utf-8"></head><body>');
          allInfo.document.write(document.getElementById ('state').value);
          allInfo.document.write('<p>' + document.getElementById ('zip').value);
          allInfo.document.write('</section></body></html>');

              allInfo.document.close();
             }

           function askForHelp () {

              var volunteer = document.getElementById('state').value;

                if ((volunteer == "New York") || (volunteer == "NY") || (volunteer == "New Jersey") || (volunteer == "NJ")) { 
                  allInfo.alert("test test test");
                     return false;
             }
                else {
                     return true; 
             }
             }

            function validateForm () {
              var x = document.getElementById("state").value;
              var y = document.getElementById("zip").value;
                if (x == null || x == "" || y == null || y == "") {
                  alert("Please fill out the required fields.");
                     return false;
             }
                else {
                     return true;
             } 
             }


       </script>

      </head>

          <body>
       <script type="text/javascript">
       </script>

           <form id="infoForm" method="post" name="infoForm">
              <p>State: </p>
                 <p><input type="text" id="state" placeholder="State or Region"></p>

              <p>Zip: </p>
                 <p><input type="text" id="zip" placeholder="Zip code" required /></p>

        <p><input type="button" value="Submit Information" onClick="newWindow(), askForHelp(), validateForm()" ></p>
           </form>
          </body>
       </html>   

【问题讨论】:

  • 你能格式化你的代码吗?像这样读起来很难。
  • 我尝试更好地格式化它。在下面得到了一个非常适合我想要的答案。

标签: javascript forms new-window


【解决方案1】:

这是一个无耻的插件,但我只是写了一个开源的 JS 库,试图解决这样的问题。我称之为“是”。

http://jumpkick-studios.github.io/Is/

它使用了 Maybe Monad 的概念:

http://en.wikibooks.org/wiki/Haskell/Understanding_monads/Maybe

所以它可以让你用更多的单一责任原则来解决这个问题。

var validateState=function(obj){
  return (obj.state!=null) //error check here
}
var validateZip=function(obj){
  return (obj.zip!=null) //error check here 
}
var openWindow=function(){
  //do open window stuff
}

var handleError(){
  //handle errors here
}

var onClick=function(e){
  var form={state:document.getElementById("state").value, zip:document.getElementById("zip").value})
  new jumpkick.Is(form)
    .is(validateState)
    .is(validateZip)
    .then(openWindow)
    .catch(handleError)
    .finally(function(){
      //anything else can go here
    });
}

ETA:解决此问题的更好方法可能是不使用单个句柄错误函数,因为您可能希望显示每个错误字段的消息。

因此,即使是这样的东西也可能会起作用(不过需要更多代码)。

var onClick=function(e){
      var validInput=true;
      var state=document.getElementById("state").value, zip=document.getElementById("zip").value
      new jumpkick.Is(state)
        .not().isLongerThan(0)        
        .then(function(){
            validInput=false;
            //display message for state
         });
       new jumpkick.Is(zip)
        .not().isLongerThan(0)        
        .then(function(){
            validInput=false;
            //display message for zip
         });
    if(validInput) // openWindow
    }

【讨论】:

  • 简洁但根本不是问题所在。
  • 怎么样?我真的不是故意发送垃圾邮件,但问题似乎是关于如何组织代码,以便在打开窗口之前进行一系列验证。无论如何都应该触发某些代码,并且最终结果应该在所有验证发生后才会发生。这不是一个很好的使用 mondadic 链吗?另外,将他的代码分解为 SRP 函数不应该也有助于解决问题吗?
  • 我读到的问题特别限于“为什么我总是得到一个弹出窗口以及如何防止它”。虽然值得称赞的是,它确实部分解决了这个问题。然而,它通过向相对先进的编程概念(当他们明确表示他们想要完全理解代码时)引入依赖关系和大量重组(OP 特别指出他们不想要的东西)来做到这一点。我同意 OP 的代码可以更好,而且你的库很整洁,但最好留给codereview stackexchange
  • 很公平!在我看来,将事物分解成更小的函数让我更容易理解,这就是我试图在回答中说明这一点的原因。但感谢您的反馈。
【解决方案2】:

而不是使用newWindow(), askForHelp(), validateForm() 进行 onClick 为什么不只执行其中一个(您想先检查),然后在准备好时让函数调用其他函数?

 function validateForm () {
   var x = document.getElementById("state").value;
   var y = document.getElementById("zip").value;
   if (x == null || x == "" || y == null || y == "") {
     alert("Please fill out the required fields.");
     return false;
   } else {
     newWindow(); //Validation was successful so lets open the new window
   }
 }

这样你就可以只在点击时触发validateForm(),其余的将在需要时触发。您还需要在 newWindow 函数中添加 askForHelp() 以在必要时触发该触发器。

【讨论】:

  • 好的,我试试,但我不需要在用户提交表单时执行该函数吗?
  • 是的,它会在他们提交表单时执行,但只有在验证通过后才会执行。 validateForm 会先执行,然后执行 newWindow
  • 太棒了!这使它完全按照我想要的方式工作,至少在这个测试代码上——但它也应该与真实页面一起工作。我把 onClick=validateForm() 和 newWindow() 作为 ese 条件放在 validateForm 函数中(正如你在上面所说的那样)——然后我将 askForHelp 添加到 newWindow 函数的底部。非常感谢。
猜你喜欢
  • 2013-08-10
  • 2010-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多