Как вставить свою готовую form'у в html страницу?
Переделываю quiz с сайта codepen https://codepen.io/missditch/pen/VmzKNv
Всё устраивает как работает. В самом конце выводится сообщение тегом h2.
"Вам положена скидка 10%!"
А я хочу вставить свой блок с формой. Как это сделать?
В javascript я пока совсем не разбираюсь.
function showQuizButtons() {
if(index === 0) {
//there is no previous question when first question is shown
prevButton.classList.add("hide");
}
if (index > 0) {
prevButton.classList.remove("hide");
}
if(index === quizLength) {
//only if last question is shown user can see the score
scoreButton.classList.remove("hide");
nextButton.classList.add("hide");
//prevButton still visible so user can go back and change answers
var h2 = document.createElement("h2");
h2.innerHTML = "Вам положена скидка 10%!";
form.appendChild(h2);
}
else {
nextButton.classList.remove("hide");
scoreButton.classList.add("hide");
}
}
Вот эту форму хочу вставить после заголовка в конце quiz h2.innerHTML = "Вам положена скидка 10%!";
В учебниках для новичков понятно как вставить html тег. С этим я разобрался. Могу вставить любую надпись.
Не могу понять как вставить конкретный блок из группы html тегов. В моём случае эту форму:
<form id="form" class="popup" method="POST">
<div class="label">
<input type="tel" id="center_ok" class="form-control" name="phone" required>
<div class="label__text">
Ваш телефон
</div>
</div>
<div class="row-flex-popup"><input class="checkbox-form" type="checkbox" required >Согласен.
<a href="#" class="myModal-1" data-hystmodal="#myModal-1"> Политика конфиденциальности.</a>
</div>
<button type="submit" name="submit">Отправить</button>
</form>
Я смотрел много самоучителей. Логику я понял. Нужно выбрать элемент с ID. Потом сделать из него переменную или можно просто по ID. И вставить в нужное мне место. А как вставить не могу понять. Я не прошу бесплатное решение. Подтолкните в нужном направлении. Где это можно посмотреть. Дальше сам разберусь.
Ответы (1 шт):
Вероятно, вы ищите что-то вроде:
function showQuizButtons() {
const form = document.getElementById("form");
form.innerHTML = "";
const h2 = document.createElement("h2");
h2.textContent = "Вам положена скидка 10%!";
form.appendChild(h2);
const formEl = document.createElement("form");
formEl.className = "popup";
formEl.method = "POST";
const labelDiv = document.createElement("div");
labelDiv.className = "label";
const inputTel = document.createElement("input");
inputTel.type = "tel";
inputTel.id = "center_ok";
inputTel.className = "form-control";
inputTel.name = "phone";
inputTel.required = true;
const labelText = document.createElement("div");
labelText.className = "label__text";
labelText.textContent = "Ваш телефон";
labelDiv.appendChild(inputTel);
labelDiv.appendChild(labelText);
const rowFlex = document.createElement("div");
rowFlex.className = "row-flex-popup";
const checkbox = document.createElement("input");
checkbox.type = "checkbox";
checkbox.className = "checkbox-form";
checkbox.required = true;
const checkboxLabel = document.createTextNode("Согласен. ");
rowFlex.appendChild(checkbox);
rowFlex.appendChild(checkboxLabel);
const submitButton = document.createElement("button");
submitButton.type = "submit";
submitButton.name = "submit";
submitButton.textContent = "Отправить";
formEl.appendChild(labelDiv);
formEl.appendChild(rowFlex);
formEl.appendChild(submitButton);
formEl.addEventListener("submit", function (e) {
e.preventDefault();
alert("Форма отправлена");
});
form.appendChild(formEl);
const showBtn = document.getElementById("showBtn");
showBtn.style.display = "none";
}
.popup {
margin-top: 20px;
padding: 10px;
border: 1px solid #ccc;
}
.label {
margin-bottom: 10px;
}
.label__text {
font-size: 14px;
color: #666;
}
.row-flex-popup {
margin-bottom: 10px;
}
<div id="form"></div>
<button id="showBtn" onclick="showQuizButtons()">Показать форму</button>
Ну или как альтернатива - можно добавить форму в html и изначально сделать ее невидимой (display=none), а при переходе на определенный шаг - менять ее css display на "видимый".