1

ユーザーが送信した入力をブール値でテストするために、Web ページに単一のテキスト ボックス フォームを作成しようとしています。入力は、Web サイト ユーザーの郵便番号になります。true とテストされる郵便番号の所定の配列を作成したいと考えています。

true の場合 (入力された郵便番号が所定の配列に含まれている場合)、HTML を 1 ビット表示し、false の場合は別のビットを表示します。

私は自分の JavaScript の本 (学習を始めたばかり) を検索して調べましたが、答えが見つかりませんでした。誰かがこれで私を助けることができますか? ありがとう!

4

2 に答える 2

2

HTML:

<label id="input-label" class="invalid">
    ZIP code: <input id="zipcode" />
    <div class="valid-message">
        Valid
    </div>
    <div class="invalid-message">
        Invalid
    </div>
</label>

CSS:

#input-label.valid .valid-message { display: block; }
#input-label.valid .invalid-message { display: none; }

#input-label.invalid .valid-message { display: none; }
#input-label.invalid .invalid-message { display: block; }

Javascript

function isValidZip(z) {
    return ['12345','67890'].indexOf(z) != -1;
}

var label = document.getElementById('input-label');
var input = document.getElementById('zipcode');

input.onkeydown = function() {
    label.className = isValidZip(input.value) ? "valid" : "invalid";
}
于 2012-10-08T19:28:16.810 に答える
0

このようなことを試すことができます(少しずれている可能性があります。再確認してから返信します:)):

var zipArr = ['98671','97006'];//insert the zip/post codes here
var userInputEl = document.getElementById('userInput');//Get the element could use tag names or it would be better actually if you used jQuery but yeah
var elToShow = document.getElementById('elementToShowIfNotFound');
var otherElToShow = document.getElementById('idOfOtherelementToShow');
var userInput = userInputEl.value();//might be .text()
if(zipArr.indexOf(userInput) === -1){//-1 means it isn't found in the array
    zipArr.push(userInput);//pushes the new one onto the array        
    elToShow.style.display = 'block';//this changes the css display to block instead of it being hidden.    
}else{        
    otherElToShow.style.display= 'block';
}

これは最善の方法ではないかもしれませんが、jQuery を使用すると、このプロセスがはるかに簡単になることをお勧めします。

于 2012-10-08T19:27:42.303 に答える