简体   繁体   English

javascript警报拒绝在表单验证中工作?

[英]javascript alerts refuse to work in form validation?

i keep trying everything to get these alerts to pop up correctly. 我一直在尝试一切以使这些警报正确弹出。 i started out using nested functions, then threw them out and put it all in one function, and now when I press enter after filling out any one text box it does nothing at all, just puts the strings in the url, instead of alerting like it was before. 我开始使用嵌套函数,然后将它们扔掉并将其全部放在一个函数中,现在当我在填写任何一个文本框后按Enter时,它什么都不做,只是将字符串放在url中,而不是像警告一样是以前。 I'm not sure if its my function call or anything else because I double checked everything and it all seems to check out to me. 我不确定它是我的函数调用还是其他调用,因为我仔细检查了所有内容,所有这些似乎都对我有用。 here is the entire code that doesnt do anything: 这是不执行任何操作的完整代码:

<html xmlns="http://www.w3.org/1999/xhtml">

<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">

    <!-- VARIABLE DECLARATION -->

    f1.city.focus();

    function check_form()
    {   
        at_sign = email.search(/@/);

        if(document.f1.city.value.length < 1)
        {
            alert('Please enter a city');
            f1.city.focus();
        }
        else if(document.f1.state.value.length != 2 || !(state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
        {
            alert('Please enter a state in abreviated form');
            f1.state.focus();
        }
        else if(document.f1.zip.value.length != 5 || document.f1.zip.value.isNaN()==true)
        {
            alert('Please enter a 5 digit zip code');
            f1.zip.focus();
        }
        else if((at_sign<1) || (email.length<3))
        {
            alert('Please enter a valid email address');
            f1.email.focus();
        }
        else
        {
            document.write("Form completed");   
        }

    }

</SCRIPT>
</HEAD> 

<BODY >

    <form name = "f1" action="smartform.html">
        <b>City</b>
        <input type = "text" name = "city" size = "18" value="" onSubmit = "javascript:check_form()">
        <b>State</b>
        <input type = "text" name = "state" size = "4" value="" onSubmit = "javascript:check_form()">
        <b>Zip Code</b>
        <input type = "text" name = "zip" size = "5" value="" onSubmit = "javascript:check_form()">
        <b>Email</b>
        <input type = "text" name = "email" size = "18" value="" onSubmit = "javascript:check_form()">

        <input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form()">
    </form>


</BODY>
</HTML>

edit: nothing seems to be working that everyone says.. here is my new code: 编辑:似乎什么都没有,每个人都说..这是我的新代码:

<html xmlns="http://www.w3.org/1999/xhtml">

<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">

    f1.city.focus();

    function check_form(f1)
    {   
        var at_sign = f1.email.search(/@/);

        if(f1.city.value.length < 1)
        {
            alert('Please enter a city');
            f1.city.focus();
            return false;
        }
        else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))
        {
            alert('Please enter a state in abreviated form');
            f1.state.focus();
            return false;
        }
        else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN()==true))
        {
            alert('Please enter a 5 digit zip code');
            f1.zip.focus();
            return false;
        }
        else if((at_sign<1) || (f1.email.length<3))
        {
            alert('Please enter a valid email address');
            f1.email.focus();
            return false;
        }
        else
        {
            //document.write("Form completed"); 
        }

        return false;

    }

</SCRIPT>
</HEAD> 

<BODY >

    <form name = "f1" onSubmit="return check_form(this)">
        <b>City</b>
        <input type = "text" name = "city" size = "18" value="">
        <b>State</b>
        <input type = "text" name = "state" size = "4" value="">
        <b>Zip Code</b>
        <input type = "text" name = "zip" size = "5" value="">
        <b>Email</b>
        <input type = "text" name = "email" size = "18" value="">

        <input type = "submit" name = "button" value = "Done" onclick = "return check_form(this)">
    </form>


    <b>hi</b>

</BODY>
</HTML>

still get no alerts... i put that hi up and got that.. but no alerts...... 仍然没有警报...我把它打起来并得到..但没有警报...

alright, I know I should probably be using getElementByID, but my new focus is to find out precisely why my code isn't working. 好吧,我知道我可能应该使用getElementByID,但是我的新重点是准确找出为什么我的代码无法正常工作。 Since my lecture outline examples didnt use this method, I want to figure out why the following code doesnt activate alerts like it used to. 由于我的讲课大纲示例未使用此方法,因此我想弄清楚以下代码为什么不像以前那样激活警报。 I simplified it to this: 我将其简化为:

<!DOCTYPE html>
<html>
<HEAD>
<TITLE>Smart Form </TITLE>
<SCRIPT LANGUAGE="JavaScript">



function check_form()
{   
    document.write("Form started");

    var at_sign = document.f1.email.search(/@/);

    if(document.f1.city.value.length < 1)
    {
        alert('Please enter a city');
        document.f1.city.focus();
        //return false;
    }
    else if(document.f1.state.value.length != 2 || !(document.f1.state.charCodeAt('0')>=65 && document.f1.state.charCodeAt('0')<=91))
    {
        alert('Please enter a state in abreviated form');
        document.f1.state.focus();
        //return false;
    }
    else if(document.f1.zip.value.length != 5 || isNaN(document.f1.zip.value)==true)
    {
        alert('Please enter a 5 digit zip code');
        document.f1.zip.focus();
        //return false;
    }
    else if((at_sign<1) || (document.f1.email.value.length<3))
    {
        alert('Please enter a valid email address');
        document.f1.email.focus();
        //return false;
    }
    else
    {
        document.write("Form completed");   
    }   
}

</SCRIPT>
</HEAD> 

<BODY onLoad= "javascript:document.f1.city.focus();">

<form name = "f1" action="smartform1.html" onSubmit="javascript:check_form();">
    <b>City</b>
    <input type = "text" name = "city" size = "18">
    <b>State</b>
    <input type = "text" name = "state" size = "4">
    <b>Zip Code</b>
    <input type = "text" name = "zip" size = "5">
    <b>Email</b>
    <input type = "text" name = "email" size = "18">

    <input type = "submit" name = "button" value = "Done" onclick = "javascript:check_form();">
</form>




</BODY>
</HTML>

I get no errors in console, and now when I type something in, I get the test line "form started" to appear for a split second, along with some mysterious error, and then it all disapears and shows the form. 我没有在控制台中看到任何错误,现在当我输入内容时,我得到了“ form start”测试行的出现,并伴随着一些神秘的错误,然后所有错误消失并显示了表单。 but my question is, why doesnt an alert happen along the way to this result? 但是我的问题是,为什么在达到此结果的过程中没有发生警报? it seems like even if the page got overwritten, it should still pop up. 即使页面被覆盖,它仍然应该弹出。 also, is there a way to pause it with code/and or debugging before it gets to the point where its overwritten? 另外,有没有一种方法可以在代码被覆盖之前通过代码/和/或调试将其暂停? so my basic question is: why don't the alerts pop up, and how do I get the alerts to popup and the focus to remain in the correct field where the function left off within the if/else statement? 所以我的基本问题是:为什么不弹出警报,以及如何使警报弹出,并且焦点保持在if / else语句中函数未使用的正确字段中?

update 2: i did a quick screen cap of the errors and it turns out f1.email etc were undefined and indeed causing the thing to not work. 更新2:我做了一个快速的错误的屏幕截图,事实证明f1.email等是未定义的,的确导致事情不起作用。 So I still want to know how to pause it with code or in the debugger, the posts and links didnt exactly seem to be clear 100% on it. 所以我仍然想知道如何使用代码或在调试器中将其暂停,帖子和链接似乎并没有100%清晰可见。 once im in the consonle and in debug mode, where exactly do i go from there to let the program pause on error? 一旦我处于协奏曲并处于调试模式,我到底从那里去让程序在出错时暂停?

also: if I declare the getElementByID variables at the top of my script in the header, then use them in the function, should that work without all the other event handling methods? 还:如果我在标头的脚本顶部声明了getElementByID变量,然后在函数中使用它们,那么在没有所有其他事件处理方法的情况下是否可以使用? I'm attempting this as i type. 我正在尝试输入。

You should put the submit listener on the form and pass a reference to the form, and return whatever value the function returns, eg 您应该将提交侦听器放在表单上,​​并传递对表单的引用,并返回函数返回的任何值,例如

<form onsubmit="return check_form(this);" ...>

You should reference the controls as properties of form using their name, don't use the name as a global variable. 您应该使用控件的名称将控件作为表单的属性来引用,不要将名称用作全局变量。 And declare all variables. 并声明所有变量。

So the function looks like: 因此该函数如下所示:

function check_form(form) {

  var at_sign = email.search(/@/);

  if (form.city.value.length < 1) {
        alert('Please enter a city');
        f1.city.focus();

        // cancel submit by returning false
        return false;

    } else if (form.state.value.length != 2 || !(form.state.charCodeAt(0) >=65 && state.charCodeAt(0)<=91)) {
        alert('Please enter a state in abreviated form');
        f1.state.focus();
        return false;
    }

    ...
}

You should probably be using a regular expression or lookup for validating the state value rather than charCodeAt . 您可能应该使用正则表达式或查找而不是charCodeAt来验证状态值。

Using document.write after the page has finished loading (eg when submitting the form) will erase the entire content of the page before writing the new content. 页面加载完成后(例如,提交表单时)使用document.write将在写入新内容之前擦除页面的全部内容。

Edit 编辑

Here's what's wrong with your new code: 这是您的新代码有什么问题:

<SCRIPT LANGUAGE="JavaScript">

Get rid of the language attribute. 摆脱语言属性。 It's not harmful (well, in a very specific case it might be). 这不是有害的(嗯,在非常具体的情况下可能是有害的)。

f1.city.focus();

f1 has no been defined or initialised (see comments above about element names and global variables) f1尚未定义或初始化(请参见上面有关元素名称和全局变量的注释)

function check_form(f1)
{
    var at_sign = f1.email.search(/@/);

f1.email is an input element, it has no search property, you can't call it. f1.email是输入元素,它没有搜索属性,您不能调用它。 It does have a value property that is a string, perhaps you meant: 它确实具有一个字符串形式的value属性,也许您的意思是:

    var at_sign = f1.email.value.search(/@/);

Then there is: 然后是:

    else if(f1.state.value.length != 2 || !(f1.state.charCodeAt('0')>=65 && state.charCodeAt('0')<=91))

again you have forgotten the value property for two of the three expressions, and forgotten to use f1 in the third. 同样,您忘记了三个表达式中的两个表达式的value属性,而忘记了在第三个表达式中使用f1 You want: 你要:

    else if(f1.state.value.length != 2 || !(f1.state.value.charCodeAt(0)>=65 && f1.state.value.charCodeAt(0)<=91))

Note that this requires users to enter the state in capital letters, it might help to tell them about that. 请注意,这要求用户使用大写字母输入状态,这可能有助于告诉他们。

Then there is: 然后是:

    else if((f1.zip.value.length != 5) || (f1.zip.value.isNaN() == true))

isNaN is a global variable, not a method of strings. isNaN是全局变量,而不是字符串方法。 If no value has been entered, then the value is the empty string and isNaN('') returns false. 如果未输入任何值,则该值为空字符串, isNaN('')返回false。 If you want to test that 5 digits have been entered then use: 如果要测试是否输入了5位数字,请使用:

else if (!/^\d{5}$/test(f1.zip.value))

There is no need to test against true, just use it, nor is there a need to group simple expressions: 无需使用true进行测试,也无需对简单表达式进行分组:

    else if (f1.zip.value.length != 5 || isNaN(f1.zip.value))

Then finally, if all the test pass: 最后,如果所有测试通过:

    return false;

that stops the form from submitting. 阻止表单提交。 You can omit this return statement, returning undefined will let the form submit. 您可以忽略此return语句,返回undefined将使表单提交。 Or return true if you really want. 或者,如果您确实想要,则返回true

Ok I want to answer your question but first things first lets walk through your code and clean it up. 好的,我想回答您的问题,但首先要首先浏览代码并进行清理。 Use this as a template of properly formated code: 将此用作正确格式的代码的模板:

<!DOCTYPE html>
  <html>
  <head>
    <title>Smart Form</title>
  </head>
  <body>
    <!-- Code goes here -->
    <script type="text/javascript">

    </script>
  </body>
</html>

Tags & attributes don't need to be capitalized. 标签和属性不需要大写。 Javascript comments are like this: JavaScript注释如下:

/** Comment. */

Html comments are like this: HTML评论是这样的:

<!-- Comment. -->

Also nitpick: attributes should be followed by an equal sign not a space. 另外,nitpick:属性后应跟等号而不是空格。 ie

<form name="f1" id="smartForm" action="smartform.html"> ... </form>

Next up proper event binding. 接下来进行适当的事件绑定。

var smartForm = document.getElementById('smartForm');
smartForm.addEventListener('submit', validateForm);

Next up I'm going to teach you how to fish real quick so you can figure out why this was broken for you and how to fix these bugs in the future. 接下来,我将教您如何快速真正地钓鱼,这样您就可以弄清楚为什么这对您来说很坏,以及将来如何修复这些错误。 Open up the developer console. 打开开发者控制台。 Evergreen browsers (Chrome, Firefox etc...) have good ones these day. 如今,Evergreen浏览器(Chrome,Firefox等...)拥有不错的浏览器。 The trick you should know is how to evaluate your code so that you can see if you did something wrong or not in how you're accessing your data. 您应该知道的技巧是如何评估代码,以便可以查看访问数据的方式是否做错了。 So look up how to open up the developer console in your browser for your platform and type this into your console: 因此,请查找如何在浏览器中针对您的平台打开开发者控制台并将其键入到控制台中:

1+1

Should evaluate to: 2. Next type: document If you click around you can see that you can walk through the dom a little bit. 应该评估为:2.下一个类型:document如果单击,您会看到可以稍微浏览一下dom。 Next load up your smartForm app with my changes above and type: 接下来,使用上面的更改加载您的smartForm应用程序,然后键入:

document.getElementById('smartForm')

You should see your element. 您应该看到您的元素。 This is how to properly query objects in the dom. 这是正确查询dom中对象的方法。 You'll notice that if you type document.smartForm doesn't work. 您会注意到,如果键入document.smartForm则不起作用。 You should get null, this should tell you that there should be a way to get the element from the document. 您应该得到null,这应该告诉您应该有一种从文档中获取元素的方法。 Hint, it's getElementById. 提示,它是getElementById。 So if you put id's on all your inputs then you can make a list of all the document objects you can query: 因此,如果在所有输入中都输入id,则可以列出可以查询的所有文档对象:

var cityElement = document.getElementById('city');
var stateElement = document.getElementById('state');
var zipElement = document.getElementById('zip');
var emailElement = document.getElementById('email');

Next you can start querying the values and such like you were doing: 接下来,您可以开始查询值,例如:

cityElement.value.length != 2

A cleaned up version would look like this: 清理后的版本如下所示:

<!DOCTYPE html>
  <html>
  <head>
    <title>Smart form</title>
  </head>
  <body>
    <form id='smartForm' action='smartform.html'>
      <b>City</b>
      <input type="text" id="city" size="18">
      <b>State</b>
      <input type="text" id="state" size="4">
      <b>Zip Code</b>
      <input type="text" id="zip" size="5">
      <b>Email</b>
      <input type="text" id="email" size="18">
      <input type="submit" value="done">
    </form>
  <script type="text/javascript">
    var validateForm = function(evt) {
      var error = false;
      var cityElement = document.getElementById('city');
      var stateElement = document.getElementById('state');
      var zipElement = document.getElementById('zip');
      var emailElement = document.getElementById('email');

      if (cityElement.value.length != 2 ||
          !(state.charCodeAt(0) >= 65 && state.charCodeAt(0) <= 91)) {
        error = true;
        alert('oops');
        cityElement.focus();
      }

      // etc..

      if (error) {
        evt.preventDefault();
      }
    };
    var smartForm = document.getElementById('smartForm');
    smartForm.addEventListener('submit', validateForm);
  </script>
  </body>
</html>

Ok a couple more things I noticed. 好吧,我注意到了另外两件事。 charCodeAt is for strings only. charCodeAt仅适用于字符串。 "hi".chatCodeAt not element.charCodeAt. “ hi” .chatCodeAt不是element.charCodeAt。 Also you have this random variable at_sign. 另外,您还有这个随机变量at_sign。 You can save yourself a TON of time and you can learn how to diagnose where the issues are by reading this: https://developer.chrome.com/devtools/docs/console Learning how to diagnose where the issues are is the single best skill you can learn while trying to get a grapple on javascript. 您可以节省大量时间,并且可以通过阅读以下内容来学习如何诊断问题所在: https : //developer.chrome.com/devtools/docs/console学习如何诊断问题所在是最好的选择尝试掌握JavaScript时可以学习的技巧。 I cannot emphasize this enough, learn how to debug, and you will learn how to program orders of magnitude faster. 我不能太强调这一点,学习如何调试,您将学习如何更快地编程数量级。 Trust me, let debugging tutorials be your bread at butter! 相信我,让调试教程成为您的最佳选择!

Full working example of your code: http://codepen.io/JAStanton/pen/tjFHn?editors=101 您的代码的完整工作示例: http : //codepen.io/JAStanton/pen/tjFHn?editors=101

A little less verbose version: http://codepen.io/JAStanton/pen/iBJAk?editors=101 稍微冗长一些的版本: http : //codepen.io/JAStanton/pen/iBJAk? editors= 101

onSubmit goes in the form, not the inputs, w/o the javascript: Solved =p onSubmit的形式,而不是输入,不带javascript:已解决= p

<form onsubmit="return check_form();" ...

There are several mishaps in your code that might also cause errors and prevent that from working 您的代码中有几处不幸事故,也可能会导致错误并阻止该错误发生

Also, check if there are mistakes (like the HTML comment inside script), if an error happens in javascript and is untreated, all javascript in that context stops working. 另外,请检查是否有错误(例如脚本中的HTML注释),如果javascript中发生了错误并且未进行处理,则该上下文中的所有javascript都将停止工作。 You can check that with any browser debugger (usually F12 will show you a window and display errors if they happen) 您可以使用任何浏览器调试器进行检查(通常F12会显示一个窗口,并在发生错误时显示错误)

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

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