// 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;
}
So, I've created an input to take only initials using JavaScript. The input box loads and wors fine, but my function is not restricting the keys to 65-90 + 8 due to an error stating alphaOnly is not defined. What am I missing?
This will only use letters
createInput.setAttribute(
"onkeypress",
"return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))"
);
This restricts the characters
createInput.setAttribute("maxlength", "4");