I have a function called validateForm() which checks for me form input. If the input is not as it should be (each field filled) alert message should appear and should be removed after 3 seconds and it does, but each time I call this function this element is created in DOM. How can I improve that code? What I want to get is div with alert message as below, but not created in the DOM each time the function is called, but once.
static validateForm() {
const title = document.querySelector('#title').value;
const author = document.querySelector('#author').value;
const isbn = document.querySelector('#isbn').value;
if (title === '' || author === '' || isbn === '') {
const div = document.createElement('div');
div.className = 'alert alert-dismissible alert-danger';
const message = document.createTextNode('Please fill all fields before adding.');
div.appendChild(message);
const bookForm = document.querySelector('#book-form');
bookForm.parentNode.insertBefore(div, bookForm);
setTimeout(() => {
div.classList.add('d-none');
}, 3000);
return false;
}
return true;
}
Try this:
//construct div globally
var div = document.createElement('div');
div.className = 'alert alert-dismissible alert-danger';
div.style.display = "none";
const bookForm = document.querySelector('#book-form');
bookForm.parentNode.insertBefore(div, bookForm);
static validateForm() {
const title = document.querySelector('#title').value;
const author = document.querySelector('#author').value;
const isbn = document.querySelector('#isbn').value;
if (title === '' || author === '' || isbn === '') {
const message = document.createTextNode('Please fill all fields before adding.');
div.html = message;
div.style.display = "block";
setTimeout(() => {
div.classList.add('d-none');
}, 3000);
return false;
}
return true;
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加