Я создаю небольшую программу, которая вычисляет год вашего рождения, чтобы попытаться применить то, что я узнал, но когда я меняю стиль контейнера div на «блоковый» с помощью JavaScript, он появляется, а затем очень быстро исчезает.
Ожидается: поле div появится после нажатия кнопки «Отправить» и завершения вычислений.
Результат: появляется поле div, а затем очень быстро исчезает.
Форма, собирающая данные для расчета года рождения:
let currentYear = new Date().getFullYear();
let age = null;
let birthYear = null;
let hadBirthDay = null;
let answerBox = document.getElementById("answerBox");
answerBox.style.display = "none";
function returnAge() {
age = document.getElementById("age").value;
//finds value of the radio input
document.getElementsByName("bday").forEach((radio) => {
if (radio.checked) {
hadBirthDay = radio.value;
}
});
if (age && hadBirthDay) {
calculateBirthYear();
}
}
function calculateBirthYear() {
// calculates birth year
if (hadBirthDay === "yes") {
birthYear = currentYear - age;
} else if (hadBirthDay === "no") {
birthYear = currentYear - age - 1;
}
}
function revealAnswer() {
answerBox.style.display = "block";
}#answerBox {
background-color: #2d415e;
color: #7194c9;
padding: 5px;
margin-top: 20px;
margin-left: 150px;
margin-right: 150px;
height: auto;
text-align: center;
border-radius: 50px;
}<form>
<section>
<label for = "age">Insert Age:</label>
<input type = "number" min = "0" id = "age" name = "age" required />
</section>
<br />
<section class = "bday">
<span>Have you had your birthday this year?</span>
<br />
<input type = "radio" id = "yes" name = "bday" value = "yes" class = "radio" required />
<label for = "yes">Yes</label>
<input type = "radio" id = "no" name = "bday" value = "no" class = "radio" required />
<label for = "no">No</label>
</section>
<br />
<button id = "submit" onclick = "returnAge()">Submit</button>
</form>
<!-- html of the div that isn't working : -->
<section>
<h2 id = "answerBoxText" class = "answer">YOU WERE BORN IN:</h2>
<div id = "answerBox" class = "answer">
<h3 id = "answerText" class = "answer">year</h3>
</div>
</section>


![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


В вашем коде не хватает двух вещей: вызова showAnswer() и фактического помещения ответа в div-элемент ответа.
Я добавил вызов showAnswer() сразу после вызова метода CalcultBirthYear() и модифицировал метод CalcultBirthYear(), чтобы добавить ответ в DOM.
Обновлено: Как отметил @Daniels118, я также добавил вызов event.preventDefault в обработчике событий returnAge(). Без этого форма будет отправлена, а html-страница будет заменена ответом.
let currentYear = new Date().getFullYear();
let age = null;
let birthYear = null;
let hadBirthDay = null;
let answerBox = document.getElementById("answerBox");
answerBox.style.display = "none";
function returnAge(event) {
event.preventDefault()
age = document.getElementById("age").value;
//finds value of the radio input
document.getElementsByName("bday").forEach((radio) => {
if (radio.checked) {
hadBirthDay = radio.value;
}
});
if (age && hadBirthDay) {
calculateBirthYear();
revealAnswer();
}
}
function calculateBirthYear() {
// calculates birth year
if (hadBirthDay === "yes") {
birthYear = currentYear - age;
} else if (hadBirthDay === "no") {
birthYear = currentYear - age - 1;
}
}
function revealAnswer() {
document.querySelector("#answerBox").innerText = birthYear;
answerBox.style.display = "block";
}#answerBox {
background-color: #2d415e;
color: #7194c9;
padding: 5px;
margin-top: 0px;
margin-left: 150px;
margin-right: 150px;
height: auto;
text-align: center;
border-radius: 50px;
}
h2 {
margin: 4px;
}<form>
<section>
<label for = "age">Insert Age:</label>
<input type = "number" min = "0" id = "age" name = "age" required />
</section>
<br />
<section class = "bday">
<span>Have you had your birthday this year?</span>
<br />
<input type = "radio" id = "yes" name = "bday" value = "yes" class = "radio" required />
<label for = "yes">Yes</label>
<input type = "radio" id = "no" name = "bday" value = "no" class = "radio" required />
<label for = "no">No</label>
</section>
<br />
<button id = "submit" onclick = "returnAge(event)">Submit</button>
</form>
<!-- html of the div that isn't working : -->
<section>
<h2 id = "answerBoxText" class = "answer">YOU WERE BORN IN:</h2>
<div id = "answerBox" class = "answer">
<h3 id = "answerText" class = "answer">year</h3>
</div>
</section>Спасибо @Daniels118, кажется, я не делал достаточно заметок, когда редактировал код.
Вы также можете добавить к своей кнопке атрибут type = "button", который позволит легко избежать отправки формы.
Проблема в том, что страница перезагружается, как только вы нажимаете кнопку. При нажатии кнопки (либо без определенного типа, либо с типом, определенным как «Отправить») в форме происходят два события: событие щелчка и событие отправки. Вы их смешиваете. В этом случае просто прослушайте событие отправки и обязательно позвоните e.preventDefault(), чтобы остановить отправку формы и тем самым перезагрузить страницу.
В общем, не используйте идентификаторы слишком часто (они должны быть уникальными) и не используйте слишком много глобальных переменных. В качестве примера я переместил let age = null; в функцию обратного вызова события отправки вместо того, чтобы определять его как глобальную переменную. Допустим, другая функция age дала неправильное значение — гораздо более предсказуемо определить переменную, когда вы собираетесь ее использовать.
let form = document.forms.form01;
let answerBox = form.querySelector(".answerBox");
answerBox.style.display = "none";
form.addEventListener('submit', e => {
e.preventDefault();
let form = e.target;
let age = form.age.valueAsNumber;
// calculates birth year
let currentYear = new Date().getFullYear();
let birthYear = currentYear - age;
if (form.bday.value == 'no') birthYear--;
// show answer
form.output.value = birthYear;
answerBox.style.display = "block";
});.answerBox {
background-color: #2d415e;
color: #7194c9;
padding: 5px;
margin-top: 0px;
margin-left: 150px;
margin-right: 150px;
height: auto;
text-align: center;
border-radius: 50px;
}
h2 {
margin: 4px;
}<form name = "form01">
<section>
<label>Insert Age: <input type = "number" min = "0" name = "age" required></label>
</section>
<section class = "bday">
<div>Have you had your birthday this year?</div>
<label><input type = "radio" name = "bday" value = "yes" class = "radio" required> Yes</label>
<label><input type = "radio" name = "bday" value = "no" class = "radio"> No</label>
</section>
<button type = "submit">Submit</button>
<section>
<h2>YOU WERE BORN IN:</h2>
<div class = "answerBox">
<h3 id = "answerText"><output name = "output"></output></h3>
</div>
</section>
</form>
Вы должны указать, что вы добавили
event.preventDefault, чтобы избежать отправки формы, которая очистит всю страницу.