-
Notifications
You must be signed in to change notification settings - Fork 0
/
forms.html
110 lines (86 loc) · 3.23 KB
/
forms.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Javascript Forms</title>
<style>
.error {
border-color: red;
}
</style>
</head>
<body>
<form action="">
<label>Name:</label><br>
<input type="text" name="name" id="">
<button>Save</button><br>
<label>Options:</label><br>
<select name="options" id=""></select><br>
<label>Message:</label><br>
<textarea name="message" id="" cols="30" rows="10"></textarea><br>
<div class="symbolCount"></div>
<input type="checkbox" name="agree" id=""> <label>Agree:</label><br>
<div class="error">
</div>
<input type="submit" value="Register" disabled>
</form>
<script>
let errorText = `Проверьте форму на ошибки!`
const form = document.querySelector("form");
const errorDiv = document.querySelector(".error");
const symbolCount = document.querySelector(".symbolCount");
document.forms[0][1].onclick = function (event) {
event.preventDefault();
if (document.forms[0][0].value.length < 4) {
errorDiv.innerHTML = errorText;
document.forms[0][0].classList.add("error")
return false;
}
let inputText = document.forms[0][0].value;
document.forms[0][2].innerHTML += `
<option value="${inputText}">${inputText}</option>`;
document.forms[0][0].value = "";
errorDiv.innerHTML = "";
document.forms[0][0].classList.remove("error");
}
let maxSymbols = 500;
symbolCount.innerHTML = `Осталось: ${maxSymbols} символов`
document.forms[0][3].oninput = function () {
let count = maxSymbols - this.value.length;
symbolCount.innerHTML = `Осталось: ${count} символов`
}
document.forms[0][4].onchange = function (event) {
if (event.target.checked) {
document.forms[0][5].removeAttribute("disabled");
} else {
document.forms[0][5].setAttribute("disabled", "");
}
}
document.forms[0][5].onclick = function (event) {
event.preventDefault();
let data = new FormData(form);
data.append("hidden", "saveUser");
data.delete("name");
let output = {};
for (const [key, value] of data) {
output[key] = value;
}
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST",
body: JSON.stringify(output),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
}).then(function (answer) {
return answer.json();
}).then(function (data) {
document.body.innerHTML += JSON.stringify(data);
}).catch(function(error){
return console.log(error)
})
}
// console.log(document.forms[0]);
</script>
</body>
</html>