// This program demonstrates JavaScript form validation.
//
// References:
// https://en.wikibooks.org/wiki/JavaScript
"use strict";
window.addEventListener("load", function () {
let elements = document.getElementsByTagName("input");
for (let i = 0; i < elements.length; i++) {
elements[i].addEventListener("focus", inputFocus);
elements[i].addEventListener("input", inputInput);
}
document.getElementById("get").addEventListener("click", getClick);
document.getElementById("post").addEventListener("click", postClick);
document.getElementById("number").focus();
});
function inputFocus() {
document.activeElement.select();
displayPrompt();
checkButtons();
}
function displayPrompt(id = null) {
const prompts = {
number: "Enter a number between 1 and 100",
text: "Enter your four-character code",
pattern: "Enter your SSN as xxx-xx-xxxx"
}
let elements = document.getElementsByTagName("output");
if (id == null) {
id = document.activeElement.id;
for (let i = 0; i < elements.length; i++) {
elements[i].innerText = "";
}
}
try {
document.getElementById(id + "-prompt").innerText = prompts[id];
}
catch {
// ignore when the active element is a button
}
}
function inputInput() {
let element = document.activeElement;
let id = element.id;
if (id == "pattern") {
checkPattern();
}
if (!element.checkValidity()) {
document.getElementById(id + "-prompt").innerText = element.validationMessage;
}
else {
document.getElementById(id + "-prompt").innerText = "";
}
checkButtons();
}
function checkPattern() {
let element = document.getElementById("pattern")
let value = element.value;
if (value.length > 3 && value.substr(3, 1) != "-") {
value = value.substr(0, 3) + "-" + value.substr(3);
}
if (value.length > 6 && value.substr(6, 1) != "-") {
value = value.substr(0, 6) + "-" + value.substr(6);
}
if (element.value != value) {
element.value = value;
}
}
function checkButtons() {
let elements = document.getElementsByTagName("input");
for (let i = 0; i < elements.length; i++) {
if (!elements[i].checkValidity()) {
document.getElementById("get").disabled = true;
document.getElementById("post").disabled = true;
return;
}
}
document.getElementById("get").disabled = false;
document.getElementById("post").disabled = false;
}
function getClick() {
let form = document.getElementById("form")
form.action = "http://postman-echo.com/get";
form.method = "GET";
form.submit();
}
function postClick() {
let form = document.getElementById("form")
form.action = "http://postman-echo.com/post";
form.method = "POST";
form.submit();
}