I didn’t find a reply so I’m creating a new post. I’m a newbie into JS and I’d like to create a kind of library.
Explanation:
We have a form with input “user” and “author” and “category”
Button – to submit form.
I’d like to display data from my form under it (like on the attached screenshot).
My problem is that I don’t especially know how to display new data from the form (please take a look at code). I’m certainly sure that I should kind of a loop to create and display new UL with nested LI but I don’t know how :/.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form action="">
<label for="title"></label>
<input type="text" name="title" id="title">
<label for="author"></label>
<input type="text" name="author" id="author">
<label for="category"></label>
<select name="category" id="category">
<option value="fantasy">Fantasy</option>
<option value="sci-fi">Sci-Fi</option>
<option value="romans">Romans</option>
</select>
<button type="submit" id="submit">Zatwierdź</button>
</form>
<script src="script.js"></script>
</body>
</html>
class Book {
constructor(title,author,category) {
this.title = title;
this.author = author;
this.category = category;
}
}
let btn = document.getElementById('submit');
let books = [];
function submitForm(event) {
event.preventDefault();
let title = document.getElementById('title').value;
let author = document.getElementById('author').value;
let category = document.getElementById('category').value;
let book = new Book(title,author,category);
books.push(book);
let elementUl = document.createElement('ul');
function addElement() {
let elementTitle = document.createElement('li');
let elementAuthor = document.createElement('li');
let elementCategory = document.createElement('li');
let titleContent = document.createTextNode("Title: " + books[0].title);
let authorContent = document.createTextNode("Author: " + books[0].author);
let categoryContent = document.createTextNode("Category: " + books[0].category);
elementTitle.appendChild(titleContent);
elementAuthor.appendChild(authorContent);
elementCategory.appendChild(categoryContent);
elementUl.appendChild(elementTitle);
elementUl.appendChild(elementAuthor);
elementUl.appendChild(elementCategory);
document.querySelector('body').appendChild(elementUl);
}
addElement();
}
btn.addEventListener('click',submitForm);