仅用于Alpha字符的输入框


// input intials box
var createInput = document.createElement("input");
createInput.setAttribute("type", "text");
createInput.setAttribute("id", "initials");
// Max character length of 4 for people who have 2 middle names
createInput.setAttribute("maxlength", "4");
// Placeholder text
createInput.setAttribute("value", "ABC");
createInput.setAttribute("onkeydown", "return alphaOnly(event);");
// Input my initials JMS is value is blank
createInput.setAttribute(
"onblur",
"if (this.value == '') {this.value = 'JMS';}"
);
// Clear placeholder text onClick
createInput.setAttribute(
"onfocus",
"if (this.value == 'ABC') {this.value = '';}"
);
createInput.textContent = "";
questionsDiv.appendChild(createInput);
function alphaOnly(event) {
var key = event.keyCode;
return (key >= 65 && key <= 90) || key == 8;
}

因此,我创建了一个输入,只使用JavaScript获取首字母缩写。输入框加载并恶化得很好,但我的功能并没有将键限制在65-90+8,因为有一个错误表明没有定义alphaOnly。我错过了什么?

这将只使用字母

createInput.setAttribute(
"onkeypress",
"return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))"
);

这限制了字符

createInput.setAttribute("maxlength", "4");

最新更新