发布方法不提供像计划的警报? [英] Post Method Not giving Alerts like planned?

查看:45
本文介绍了发布方法不提供像计划的警报?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<form action="" method="post">
<div align="center"><legend>Add a Code</legend>
<label for="code"></label>
<input type="text" name="code" id="code" maxlength="10" />
<input type='button' 
 onclick=
             "isAlphanumeric(document.getElementById('code'),'Your Submission Contained Invalid Characters'); 
              isBadPhrase(document.getElementById('code'), 'Please Enter A Correct Friend Code!');"     
     value='Check Field' />

function isAlphanumeric(elem, helperMsg){
var alphaExp = /^[0-9a-zA-Z]+$/;
if(elem.value.match(alphaExp)){
    return true;
}else{
    alert(helperMsg);
    elem.focus();   
    return false;
}

}

function isBadPhrase(elem,helperMsg){
var badPhrase=/EPW|ESW|\s/;
if (elem.value.match(badPhrase)){
    alert(helperMsg);
    elem.focus();
    return false;
}else{
    return true;
    }

}

这里有什么问题?

推荐答案

您没有从处理程序返回任何内容。您需要从处理程序返回一个值(true / false),尤其是在您想要停止默认值时。注意 - 我还将BadPhrase方法的名称更改为GoodPhrase,以便它与返回值的意义相匹配。

You aren't returning anything from your handler. You need to return a value (true/false) from the handler, especially if you want to stop the default. Note -- I'd also change the name of the "BadPhrase" method to "GoodPhrase" so that it matches the sense of the return value.

脚本:

function isAlphanumeric(elem, helperMsg){
    var alphaExp = /^[0-9a-zA-Z]+$/;
    if(elem.value.match(alphaExp)){
        return true;
    } else {
        alert(helperMsg);
        elem.focus();
        return false;
    }
}

function isGoodPhrase(elem,helperMsg){
    var badPhrase=/EPW|ESW|\s/;
    if (elem.value.match(badPhrase)){
        alert(helperMsg);
        elem.focus();
        return false;
    } else {
        return true;
    }
}

function checkInput(id)    {
    return isAlphanumeric(document.getElementById(id),'Your Submission Contained Invalid Characters')
        && isGoodPhrase(document.getElementById(id), 'Please Enter A Correct Friend Code!');
}

html:

<input type='button' onclick="return checkInput('code');" value='Check Field' />

编辑

如果您对表单提交进行验证,则无论表单的提交方式如何,都将运行。您可以在表单标记中将其添加为onsubmit处理程序,就像您对按钮的单击处理程序所做的那样。该按钮应该是一个提交按钮,如果它应该触发表单提交。

If you do the validation on form submit it will run regardless of how the form is submitted. You can add it as a onsubmit handler in the form tag, like you did for the click handler of the button. The button should probably be a submit button if it is supposed to trigger form submission.

注意:我的偏好是通过javascript而不是标签添加处理程序,但这超出了问题的范围。我也可能使用框架而不是原始javascript,但这也在范围之外。

Note: my preference would be to add the handlers via javascript rather than in the tag, but that's outside the scope of the question. I'd also probably use a framework rather than raw javascript, but that's also outside the scope.

这篇关于发布方法不提供像计划的警报?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆