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 要素から送信ボタンに移動します
  • 送信ボタンを「ボタン」タイプに変更して、プッシュ ボタンにします。プッシュ ボタンは、現在のフォームを自動的に送信しません。

注: これは、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()true/falseを返すように変更

ソリューションの変更時

このソリューションは、あなたのソリューションを最もよく再現しています。ただし、複雑さが増します。

フォーム:

<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;
    };
}

ノート

この問題を解決するには多くの方法があります。最も簡単な 2 つと、より優れたユーザー エクスペリエンスを提供すると思われる 1 つを選択しました。非送信ソリューションは、送信はしないが、フォームの送信を必要としない他のアクションを提供するボタンがある場合の良い例です。私の意見では、最後のものは最高のユーザーエクスペリエンスを持っていますが、それは単なる意見です.

オフトピック

時間があれば、利用可能な優れた 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 に答える