我正在寻找一个功能,当在邮政编码的第一个位置按下某个字符键(g)时发出警报,然后如果邮政编码中有一个字母G,则禁用提交按钮一开始。 这可能吗?
我目前检测邮政编码字段上的密钥的代码是:
$(document).ready(function() {
var someTextInputField = "#postal-code";
$(someTextInputField).on("keyup", function() {
alert('not a valid postal code');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="postal-code" />
&#13;
答案 0 :(得分:1)
document.addEventListener("input", function(e) {
if (e.target.id === "postal-code") {
var disable = /^g/i.test(e.target.value),
submit = document.getElementById("submit");
if (disable && !submit.disabled) {
alert("You cannot start a postal code with a G");
}
submit.disabled = disable;
}
});
&#13;
<input placeholder="Address" />
<input id="postal-code" placeholder="Postal Code" />
<button id="submit">Submit</button>
&#13;
$(document).on("input", "#postal-code", function (e) {
var disable = /^g/i.test(this.value),
$submit = $("#submit");
if (disable && !$submit.prop("disabled")) {
alert("You cannot start a postal code with a G");
}
$submit.prop("disabled", disable);
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Address" />
<input id="postal-code" placeholder="Postal Code" />
<button id="submit">Submit</button>
&#13;
答案 1 :(得分:0)
您可以使用this.value[0]
获取输入的第一个字符。然后测试它是否是允许的字符之一。
$("#input").on("keyup", function() {
if (this.value != '') {
var firstchar = this.value[0].toUpperCase();
if (firstchar != 'A' && firstchar != 'G') {
alert('not a valid postal code');
$("#submitID").prop("disabled", true);
} else {
$("#submitID").prop("disabled", false);
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>
&#13;
答案 2 :(得分:0)
检查这个小提琴http://jsfiddle.net/oyc2L9sy/12/
HTML:
<input id="test" type="text" />
的javascript:
$(document).ready(function() {
$("#test").on("keypress", function(e) {
if ((e.keyCode == '65') ||
(e.keyCode == '71')) {
alert('not a valid postal code');
return false;
}
});
});