Я предлагаю вам изменить свой подход. Вместо того, чтобы показывать и скрывать определенные элементы в вашем отчете, вы могли бы динамически генерировать эти элементы в JavaScript. Тогда вы можете добавлять элементы только после их заполнения, чтобы у вас были только соответствующие данные. Таким образом, вам не нужно искать каждое поле, если оно заполнено, и находить соответствующий абзац в отчете, чтобы показать или скрыть его.
Я также позволил себе продемонстрировать функцию, которая динамически добавляет новые Поля Room
и PM
, если нажать кнопку. Как и в случае с отчетом, новые поля создаются и добавляются в документ.
Информация из формы собирается с FormData
. Этот API делает для вас тяжелую работу и может извлечь каждую пару name-value (читай: каждый элемент textarea
с его именем и значением) и сохранить его в объекте. Это сохраняет вашу форму динамической c и позволяет вам добавлять и удалять любые поля input
или textarea
, которые вы хотите, без необходимости изменять JavaScript. Он просто получает все ваши данные, представленные в форме.
Было несколько других вещей, касающихся вашего HTML. Поля
input
, select
и textarea
могут иметь элемент label
. Этот элемент является описательным именем или названием вашего поля. Используйте это для маркировки элементов формы. Атрибуты
id
должны быть уникальными. Если в вашем HTML имеется более одного id
с одним и тем же значением, чем каждый идентификатор, кроме первого, то это значение недопустимо. Классы больше подходят для присвоения вашим элементам с общими стилями или свойствами идентификатора.
Диапазон заголовков от h1
до h6
. Технически вы можете иметь только один h1
на своей странице. Существуют исключения, например, при использовании article
, но попробуйте сделать так, чтобы заголовки имели иерархию. Как и у книги, у вас есть заголовок (h1) и главы (h2), а может быть, есть небольшие главы (h3) и т. Д.
И небольшая заметка на JavaScript.
Я предлагаю вам покопаться в петлях. Циклы позволяют вам делать одно и то же время столько раз, сколько вы хотите, записывая его только один раз. Как выбор нескольких элементов и переключение класса для каждого из этих элементов.
for (const textarea of document.querySelectorAll('textarea') {
textarea.classList.toggle('darkmode');
}
В приведенном выше примере используется for...of
l oop. Который может l oop через каждый повторяемый объект , массивоподобный объект или массивы.
Я понимаю, что вы изучаете, поэтому я имею в виду все в конструктивном манера. Ты прекрасно справляешься. Так держать!
Это много, чтобы принять, и я надеюсь, что все это поможет. Если мне неясно или у вас есть какие-либо вопросы, пожалуйста, дайте мне знать.
Обязательно ознакомьтесь с приведенным ниже примером.
const form = document.querySelector('.js-form');
const pmContainer = document.querySelector('.js-pm-container');
const pmButton = document.querySelector('.js-add-pm');
const report = document.querySelector('.js-report');
const clearButton = document.querySelector('.js-clear-report');
const copyButton = document.querySelector('.js-copy-button');
// Clear the report
function clearReport() {
while (report.firstElementChild) {
report.firstElementChild.remove();
}
}
// Clear report on clear button click.
clearButton.addEventListener('click', clearReport);
// Generate report based on values in the form.
function generateReport(formData) {
// Create a list.
const list = document.createElement('ul');
// Loop over all name - value pairs in the form.
// Each input has a name and a value associated with it.
for (const [name, value] of formData) {
// Don't do anything if the value is empty.
if (value !== '') {
// Create a list and two paragraphs.
const listItem = document.createElement('li');
const namePar = document.createElement('p');
const valuePar = document.createElement('p');
// Set the class and textContent.
listItem.classList.add('gen');
namePar.textContent = name;
valuePar.textContent = value;
// Append paragraphs to the list item
// and the list item to the list.
listItem.append(namePar);
listItem.append(valuePar);
list.append(listItem);
}
}
// Add the list to the report div.
report.append(list);
}
// On submit extract the values from the form
// and pass them to the generateReport function.
form.addEventListener('submit', function(event) {
// Collect the data in formData.
const formData = new FormData(event.target);
// Clear the report.
clearReport();
// Generate a report with the given FormData.
generateReport(formData);
// Prevent form from actually submitting.
event.preventDefault();
});
// Generate new Room and PM fields and add
// them to the pm-container div.
pmButton.addEventListener('click', function(event) {
const html = `
<label>
<span>#Room</span>
<textarea name='Room' cols="110" rows="6" value="" placeholder="Logs from #Room (if applicable)"></textarea>
</label>
<label>
<span>PM</span>
<textarea name='PM' cols="110" rows="6" value="" placeholder="PM Logs (if applicable)"></textarea>
</label>
`;
pmContainer.insertAdjacentHTML('beforeend', html);
});
function copyRedirect() {
copyClipboard(); // calling function copyClipboard()
myFunction1(); // calling function myFunction1()
}
function copyClipboard() {
// for Internet Explorer
if (document.body.createTextRange) {
var range = document.body.createTextRange();
range.moveToElementText(report);
range.select();
document.execCommand("Copy");
}
// other browsers
else if (window.getSelection) {
var selection = window.getSelection();
var range = document.createRange();
range.selectNodeContents(report);
selection.removeAllRanges();
selection.addRange(range);
document.execCommand("Copy");
}
}
copyButton.addEventListener('click', copyClipboard);
function myFunction1() {
if (confirm("Your report has been copied to your clipboard, would you like to proceed to the forums?")) document.location = 'https://*******';
}
label {
display: flex;
flex-direction: column
}
<form name='myform' class="js-form">
<h2> Report Generator</h2>
<label>
<span>Topic</span>
<textarea name='Topic' cols="110" rows="2" value="" placeholder="Name, Infraction, Action Taken"></textarea>
</label>
<label>
<span>Info</span>
<textarea name='Info' cols="110" rows="6" value="" placeholder="Chatter Information"></textarea>
</label>
<label>
<span>Summary</span>
<textarea name='Summary' cols="110" rows="6" value="" placeholder="Report Summary"></textarea>
</label>
<div class="js-pm-container">
<label>
<span>#Room</span>
<textarea name='Room' cols="110" rows="6" value="" placeholder="Logs from #Room (if applicable)"></textarea>
</label>
<label for="pm">
<span>PM</span>
<textarea id="pm" name='PM' cols="110" rows="6" value="" placeholder="PM Logs (if applicable)"></textarea>
</label>
</div>
<button type="button" class="js-add-pm">Add PM</button>
<button type='submit'>Generate Report</button>
<button type="button" class="js-clear-report">Clear Report</button>
</form>
<div class="report">
<h2>Generated report</h2>
<div id="generated" class="generatedReport js-report">
</div>
</div>
<button class="js-copy-button">Copy Report</button>