form-fill-examples/name_utils.html

77 строки
2.1 KiB
HTML

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Name field utils</title>
<script src="name_utils.js"></script>
<style>
#message p {
color: lightgray;
}
#message p:first-child {
color: black;
}
</style>
</head>
<body>
<p>
<input type="text" id="fullname" name="fullname" placeholder="Full Name" autofocus>
<button id="testSplit">Split name</button>
</p>
<p>
<input type="text" id="given" name="given" placeholder="Given Name">
<input type="text" id="middle" name="middle" placeholder="Middle Name">
<input type="text" id="family" name="family" placeholder="Family Name">
<button id="testJoin">Join name parts</button>
</p>
<div id="message"></div>
<script>
let $ = id => document.getElementById(id);
function log() {
let message = Array.from(arguments).map(arg => {
if (typeof arg === "object") {
return JSON.stringify(arg);
}
return arg;
}).join(" ");
let p = document.createElement("p");
p.textContent = message;
$("message").insertBefore(p, $("message").firstChild);
console.log.apply(console, arguments);
}
$("testSplit").addEventListener("click", () => {
let fullname = $("fullname");
let nameParts = NameUtils.splitName(fullname.value);
fullname.focus();
log(fullname.value, "->", nameParts);
});
$("testJoin").addEventListener("click", () => {
let nameParts = {};
["given", "middle", "family"].forEach(id => nameParts[id] = $(id).value);
let fullName = NameUtils.joinNameParts(nameParts);
log(nameParts, "->", fullName);
$("given").focus();
});
let clickButton = evt => {
if (evt.keyCode == 13) {
evt.target.parentNode.querySelector("button").click();
evt.preventDefault();
}
};
["fullname", "given", "middle", "family"].forEach(id => {
let input = $(id);
input.addEventListener("keydown", clickButton);
input.addEventListener("focus", evt => evt.target.select());
});
</script>
</body>
</html>