0

我对 Javascript 做的不多。

我想做的是有一个表格,用户可以在其中输入他们的邮政编码,以查看他们是否在选定数量的邮政编码(客户的服务区域)内。

如果他们的邮政编码在列表中,我想将他们发送到一个 URL 以安排约会。如果它不在列表中,我想要某种警报,上面写着“抱歉,您的邮政编码不在我们的服务区域”。

我有一些适应这种工作的东西,但无论他们输入什么,都会将用户发送到页面。

任何帮助是极大的赞赏!

<form name = "myform" action="http://www.google.com/">
Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5" onchange = "checkZip()">
<button id="submit">Submit</button>
</form>

<script type = "text/javascript">
    function checkZip() {

        var z = document.myform.zip;
        var zv = z.value;
        if (!/^\d{5}$/.test(zv)) {
            alert("Please enter a valid Zip Code");
            document.myform.zip.value = "";
            myfield = z; // note myfield must be a global variable
            setTimeout('myfield.focus(); myfield.select();', 10); // to fix bug in
                                                                  // Firefox
            return false;
        }

        var codes = [ 12345, 12346, 12347, 12348, 12349, 12350 ]; // add as many
                                                                  // zip codes as
                                                                  // you like,
                                                                  // separated by
                                                                  // commas (no
                                                                  // comma at the
                                                                  // end)
        var found = false;
        for ( var i = 0; i < codes.length; i++) {
            if (zv == codes[i]) {
                found = true;
                break;
            }
        }

        if (!found) {
            alert("Sorry, the Zip Code " + zv + " is not covered by our business");
            document.myform.zip.value = "";
            return false;
        } else {
            alert("Press okay to go forward to schedule an appointment");
        }
    }
</script>
4

2 回答 2

4

非提交按钮(简单)解决方案

<form name = "myform" action="http://www.google.com/">
    Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
    <button type="button" onclick="checkZip();" id="submit">Submit</button>
</form>

注意:带有 type="button" 的按钮是一个按钮,不提交w3c

并将最后一个块更改checkZip()为:

if (!found) {
    alert("Sorry, the Zip Code " + zv + " is not covered by our business");
    document.myform.zip.value = "";
    //do nothing
} else {
    alert("Press okay to go forward to schedule an appointment");
    document.myform.submit();
}

我所做的更改如下:

  • 将 onclick 属性从 input 元素移动到提交按钮
  • 将提交按钮更改为“按钮”类型,使其成为按钮。按钮不会自动提交当前表单。

注意:这不会停止在输入元素内按 enter 提交表单的情况。根据下一个解决方案,您将需要一个 onSubmit="" 处理程序来处理该用例。

提交按钮(简单)解决方案

<form name = "myform" action="http://www.google.com/" onsubmit="checkZip()">
    Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
    <button onclick="checkZip();" id="submit">Submit</button>
</form>

注意:没有类型的按钮默认是提交按钮w3c

并将最后一个块更改checkZip()为:

if (!found) {
    alert("Sorry, the Zip Code " + zv + " is not covered by our business");
    return false;
} else {
    alert("Press okay to go forward to schedule an appointment");
    return true;
}

我所做的更改如下:

  • checkZip()调用移至表单上的 onsubmit 属性
  • 更改checkZip()为返回真/假

改变解决方案

该解决方案最接近复制您的解决方案。然而,它增加了更多的复杂性:

表格:

<form name = "myform" action="http://www.google.com/" onsubmit="onFormSubmit();">
    Enter Your Zip Code
    <input type = "text" id="zipCode" name = "zip" size = "5" maxlength = "5" onchange = "onZipChange()">
    <button id="submit">Submit</button>
    <div id="invalidZipMsg" style="display:none;">
            Sorry, but we do not service your area.
    </div>
</form>

JavaScript:

/**
 * Returns true if we receive a valid zip code.
 * False otherwise.
 * 
 * @param zipCode The zip code to check
 * @returns True/fase if valid/invalid
 */
function isValidZip(zipCode){
    var validZipCodes = {'12345':true, 
                         '12346':true, 
                         '12347':true, 
                         '12348':true, 
                         '12349':true, 
                         '12350':true
                        };

    //can do other checks here if you wish
    if(zipCode in validZipCodes){
        return true;
    } else {
        return false;
    };
}

/**
 * Run on invalid zip code.
 * Disables form submission button and shows
 * error message.
 */
function invalidZipCode(){
    var invalidZipMsg = document.getElementById('invalidZipMsg');
    invalidZipMsg.style.display = "block";

    var submitButton = document.getElementById('submit');
    submitButton.disabled = 'true';
}

/**
 * Run on valid zip code. Enables form
 * submission button and hides the error message.
 * @returns
 */
function validZipCode(){
    var invalidZipMsg = document.getElementById('invalidZipMsg');
    invalidZipMsg.style.display = "none";

    var submitButton = document.getElementById('submit');
    submitButton.disabled = 'true';
}

/**
 * onChange handlers for the zip code input element.
 * Will validate the input value and then disable/enable
 * the submit button as well as show an error message.
 * @returns
 */
function onZipChange(){
    var zipCode = document.getElementById('zipCode');
    if(isValidZipCode(zipCode.value)){
        validZipCode();
    } else{
        invalidZipCode();
    };
}

/**
 * Run on form submission. Further behavior is the same
 * as @see onZipChange. Will stop form submission on invalid
 * zip code.
 */
function onFormSubmit(){
    var zipCode = document.getElementById('zipCode');

    if(isValidZipCode(zipCode.value)){
        validZipCode();
        return true;
    } else{
        invalidZipCode();
        return false;
    };
}

笔记

有很多方法可以解决这个问题。我只选择了两个最简单的,一个我觉得可以提供更好的用户体验。当您有不提交但提供不需要表单提交的其他操作的按钮时,非提交解决方案是一个很好的例子。在我看来,最后一个具有最好的用户体验,但这只是一种观点。

无关

如果您有时间,我建议您查看许多可用的优秀 JavaScript 库。它们通过有意义的简单解决方案帮助引入复杂/高级问题,并且很可能跨浏览器兼容。我按照我的偏好顺序推荐它们:

但请注意,他们需要时间来理解。我知道在处理一个不是首要任务的项目时。

一般来说,开始使用 jQuery 和 JavaScript 的最快方法是:First Flight。无论如何,我与 codeschool.com 没有关联,也没有从他们那里获得任何利润。这个示例是免费的,它是我的团队在工作中为刚开始使用 jQuery 的人们传递的示例。

于 2012-06-21T20:04:55.103 回答
1

我假设您的问题是即使邮政编码无效,用户仍然可以提交表单。

我建议将支票移动到这样的表单提交事件中

<form name = "myform" action="http://www.google.com/" onsubmit = "checkZip()">
  Enter Your Zip Code <input type = "text" name = "zip" size = "5" maxlength = "5">
  <button id="submit">Submit</button> 
</form>

然后,当检查未能取消提交到 google.com 时,您可以返回 false

于 2012-06-21T19:59:39.007 回答