Cannot append localStorage data to an existing div class - javascript

Currently making a quick journal entry app in HTML, CSS, and JS. User inputs and submits text data along with the time and date. I'm trying to take that data from the localStorage to put inside an existing div class. Any advice?
This is the HTML code.
<div class="background-journal">
<button class="button-journal" onclick="openPopup()" id="entrybtn">New Entry</button>
<br><br><br><br><br><br><br>
<button class="show-journal" onclick="recallEntries()" id="showbtn">View Previous Entries</button>
<div class="journal-visual" id="data-viz">
</div>
<div id="popup" class="popup">
<form id="form" class="form">
<br>
<label for="journal-entry">何を勉強していますか?</label><br><br>
<textarea class="add-entry" id="journal-entry" rows="6" cols="150"></textarea><br>
<button type="submit" onclick="submitJournalEntry()">Submit</button>
<button type="button" onclick="closePopup()">Close</button>
</form>
</div>
This is the CSS code.
.background-journal{
position:absolute;
top: 35%;
left: 9.6%;
background-color:rgba(255,255,255,0);
z-index:1001;
width: 80%;
height: 600px;
overflow-y: auto;
overflow-x: hidden;
}
.button-journal {
background-color: #fff;
border: none;
color: #000;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
width: 90%;
height: 100px;
left: 4.5%;
position: absolute;
box-shadow: 3px 5px #888888;
}
.show-journal{
background-color: #fff;
border: none;
color: #000;
text-align: center;
text-decoration: none;
font-size: 16px;
cursor: pointer;
width: 90%;
height: 100px;
left: 4.5%;
position: absolute;
box-shadow: 3px 5px #888888;
}
.journal-visual{
background-color: #fff;
z-index:1003;
width: 70%;
height: 450px;
overflow-y: auto;
overflow-x: hidden;
margin-left: auto;
margin-right: auto;
display: none;
position: relative;
color: #000;
text-align: center;
}
.button-popup-journal{
position: relative;
}
.popup {
display: none;
position: absolute;
z-index: 1;
width: 100%;
height: 200px;
overflow: auto;
background-color: rgba(0, 0, 0, 0.5);
text-align: center;
box-shadow: 3px 5px #000;
}
.popup form{
margin: auto;
}
.add-entry{
margin: auto;
overflow: auto;
position:inherit;
left: 5%;
}
.background-journal label{
color: white;
opacity: 70%;
}
and this is the JS code.
// Journal Function
function openPopup() {
document.getElementById("popup").style.display = "block";
document.getElementById("entrybtn").style.display = "none";
document.getElementById("showbtn").style.display = "none";
}
function closePopup() {
document.getElementById("popup").style.display = "none";
document.getElementById("entrybtn").style.display = "block";
document.getElementById("showbtn").style.display = "block";
}
function submitJournalEntry() {
var journalEntry = document.getElementById("journal-entry").value;
var date = new Date();
var timestamp = date.toString();
localStorage.setItem(timestamp, journalEntry);
closePopup();
}
function recallEntries() {
document.getElementById("entrybtn").style.display = "none";
document.getElementById("showbtn").style.display = "none";
document.getElementById("data-viz").style.display = "block";
var keys = Object.keys(localStorage);
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
var journalEntry = localStorage.getItem(key);
var viz = document.getElementById('data-viz');
div.innerHTML = '<p><strong>' + key + '</strong>: ' + journalEntry + '</p>';
document.body.appendChild(viz);
}
}
I was expecting the text to show up in the div class="journal-entry" id="data-viz" but nothing is there. Any ideas?

Related

Why does my eventlistener for input search doesnt work?

I am working on an application to search for cities. It returns a card with the flag, capital, population and region; however, it works only until I try to add an eventListener to the input search, after which, it does nothing.
Am I calling the search incorrectly? should I maybe do a search function?
P. S: I started coding ~6 months ago and sorry if it is a not well-constructed code.
const APICALL = 'https://restcountries.eu/rest/v2/';
const form = document.querySelector('.recherche')
const input = document.querySelector('.inpRecherche');
const searchBtn = document.querySelector('.searchBtn');
const affichage = document.querySelector('.affichage');
let cities = [];
//API call
async function dataApi(cities) {
const call = await fetch(APICALL);
const data = await call.json();
cities = data;
//console.log(cities);
createCard(cities);
}
dataApi(cities)
function createCard(cities) {
for (let i = 0; i < cities.length; i++) {
const cardHTML = `
<div class="carte">
<img src="${[cities[i].flag]}" alt="flag" class="avatar">
<h2>${[cities[i].name]}</h2>
<ul class="cont-infos">
<li class="capital">Capital : ${[cities[i].capital]}</li>
<li class="population">Population: ${[cities[i].population]}</li>
<li class="subregion">Region : ${[cities[i].subregion]}</li>
</ul>
</div>
`;
affichage.innerHTML = cardHTML;
}
}
searchBtn.addEventListener('click', dataApi);
form.addEventListener('submit', (e) => {
e.preventDefault()
if (e.value > 0) {
//console.log('hello');
dataApi([cities[i]]);
input.value = "";
}
})
*,
::before,
::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
height: 100vh;
background-image: url("Background.jpg");
font-family: Arial, Helvetica, sans-serif;
background-size: cover;
}
h1 {
font-size: 35px;
text-align: center;
margin: 30px;
}
.inpRecherche {
display: block;
width: 250px;
padding: 3px;
font-size: 12px;
}
form,
.affichage {
display: flex;
width: 100%;
height: auto;
align-items: center;
justify-content: center;
border-radius: 2px;
}
.affichage {
position: absolute;
justify-content: center;
border: 2px solid whitesmoke;
border-radius: 5px;
width: 300px;
height: 300px;
margin: 20px 480px;
}
.searchBtn {
height: 25px;
padding: 2px 5px;
background-color: #2896F6;
box-shadow: none;
cursor: pointer;
color: whitesmoke;
font-weight: bold;
border-radius: 3px solid white;
}
.searchBtn:hover {
background-color: #167CD4;
}
/* a partir d'ici c'est à créer
*/
.card {
width: 500px;
height: auto;
position: relative;
margin-top: 200px;
padding-bottom: 20px;
border-radius: 5px;
background-color: beige;
}
.avatar {
height: 150px;
width: 150px;
margin-top: 80px;
border-radius: 50%;
position: absolute;
left: 50%;
transform: translate(-50%, -50%);
background-color: #000;
border: 1px solid black;
}
h2 {
margin-top: 100px;
text-align: center;
font-size: 25px;
}
.cont-infos {
border-top: 1px dashed black;
margin-top: 20px;
list-style-type: none;
}
li {
padding: 10px 20px;
text-align: justify;
font-size: 22px;
}
li:nth-child(1) {
margin-top: 15px;
}
<h1>City finder 🌍🏃</h1>
<form class="recherche">
<input type="text" class="inpRecherche" placeholder="Rechercher une ville">
<button class="searchBtn">Chercher</button>
</form>
<div class="affichage">
</div>
The first thing that comes to my attention is the argument you're passing to the dataApi function. When you pass it to the event listener, the argument it receives is an event object (you're just naming it "cities"), and then you're trying to overwrite it with data from the API call instead of updating the global cities array.
Hi Lizeth and welcome to StackOverflow.
I'm not completely sure of what you are trying to do, but right now, your function createCard is not looping over all the cities you receive from the API, but writing over and over the content of cardHTML. To display all the cities, you can add a +in front of the = and
function createCard(cities) {
for (let i = 0; i < cities.length; i++) {
const cardHTML = `
<div class="carte">
<img src="${[cities[i].flag]}" alt="flag" class="avatar">
<h2>${[cities[i].name]}</h2>
<ul class="cont-infos">
<li class="capital">Capital : ${[cities[i].capital]}</li>
<li class="population">Population: ${[cities[i].population]}</li>
<li class="subregion">Region : ${[cities[i].subregion]}</li>
</ul>
</div>
`;
affichage.innerHTML += cardHTML;
}
}
And change your css classes to
.affichage {
justify-content: center;
border: 2px solid whitesmoke;
border-radius: 5px;
width: 90vw;
height: auto;
margin: 20px auto 0 auto;
display: flex;
flex-flow: row wrap;
}
.avatar {
height: 150px;
width: 150px;
margin: 10px auto;
border-radius: 50%;
position: initial;
background-color: #000;
border: 1px solid black;
margin: 10px auto;
}
But, be warned, building html this way can be very dangerous, see XSS attacks.
And to search for a city using the input, Yes, you need to build a search function yourself, and display the result. Regex could be a way to do it

How to add inline CSS to dynamically created elements with Javascript?

I would like to add inline CSS to the left and right messages that are generated, for example the left text is red and the right text is blue. (I know it's best to style in the CSS, but I'm testing something else). So I will have this HTML:
<ul class="messages">
<li class="message left appeared">
<div class="text_wrapper">
<p class="text" style="color:red;">blabla</p>
</div>
</li>
<li class="message right appeared">
<div class="text_wrapper">
<p class="text" style="color:blue;">blabla</p>
</div>
</li>
</ul>
Please see the code as reference for the functionality. Many thanks for your help.
(function() {
var Message;
Message = function({
text: text1,
message_side: message_side1
}) {
this.text = text1;
this.message_side = message_side1;
this.draw = () => {
var $message;
$message = $($('.message_template').clone().html());
$message.addClass(this.message_side).find('.text').html(this.text);
$('.messages').append($message);
return setTimeout(function() {
return $message.addClass('appeared');
}, 0);
};
return this;
};
$(function() {
var getMessageText, message_side, sendMessage;
message_side = 'right';
getMessageText = function() {
var $message_input;
$message_input = $('.message_input');
return $message_input.val();
};
sendMessage = function(text) {
var $messages, message;
if (text.trim() === '') {
return;
}
$('.message_input').val('');
$messages = $('.messages');
message_side = message_side === 'left' ? 'right' : 'left';
message = new Message({text, message_side});
message.draw();
return $messages.animate({
scrollTop: $messages.prop('scrollHeight')
}, 300);
};
$('.send_message').click(function(e) {
return sendMessage(getMessageText());
});
$('.message_input').keyup(function(e) {
if (e.which === 13) { // enter key
return sendMessage(getMessageText());
}
});
});
}).call(this);
* {
box-sizing: border-box;
}
.chat_window {
position: absolute;
width: calc(100% - 20px);
max-width: 600px;
height: 440px;
background-color: #fff;
left: 50%;
top: 50%;
transform: translateX(-50%) translateY(-50%);
border: 1px solid #ddd;
overflow: hidden;
}
.messages {
position: relative;
list-style: none;
padding: 20px 10px 0 10px;
margin: 0;
height: 347px;
overflow: scroll;
}
.messages .message {
clear: both;
overflow: hidden;
margin-bottom: 20px;
transition: all 0.5s linear;
opacity: 0;
}
.messages .message.left .text_wrapper {
background-color: #ddd;
margin-left: 20px;
}
.messages .message.left .text_wrapper::after, .messages .message.left .text_wrapper::before {
right: 100%;
border-right-color: #ddd;
}
.messages .message.left .text,
.messages .message.right .text {
color: #000;
margin: 0;
}
.messages .message.right .text_wrapper {
background-color: #ddd;
margin-right: 20px;
float: right;
}
.messages .message.right .text_wrapper::after, .messages .message.right .text_wrapper::before {
left: 100%;
border-left-color: #ddd;
}
.messages .message.appeared {
opacity: 1;
}
.messages .message .text_wrapper {
display: inline-block;
padding: 20px;
width: calc(100% - 85px);
min-width: 100px;
position: relative;
}
.messages .message .text_wrapper::after, .messages .message .text_wrapper:before {
top: 18px;
border: solid transparent;
content: " ";
height: 0;
width: 0;
position: absolute;
pointer-events: none;
}
.messages .message .text_wrapper::after {
border-width: 13px;
margin-top: 0px;
}
.messages .message .text_wrapper::before {
border-width: 15px;
margin-top: -2px;
}
.messages .message .text_wrapper .text {
font-size: 18px;
font-weight: 300;
}
.bottom_wrapper {
position: relative;
width: 100%;
background-color: #fff;
padding: 20px 20px;
position: absolute;
bottom: 0;
}
.bottom_wrapper .message_input_wrapper {
display: inline-block;
height: 50px;
border: 1px solid #bcbdc0;
width: calc(100% - 160px);
position: relative;
padding: 0 20px;
}
.bottom_wrapper .message_input_wrapper .message_input {
border: none;
height: 100%;
box-sizing: border-box;
width: calc(100% - 40px);
position: absolute;
outline-width: 0;
color: gray;
}
.bottom_wrapper .send_message {
width: 140px;
height: 50px;
display: inline-block;
background-color: #ddd;
border: 2px solid #ddd;
color: #000;
cursor: pointer;
transition: all 0.2s linear;
text-align: center;
float: right;
}
.bottom_wrapper .send_message:hover {
color: #000;
background-color: #fff;
}
.bottom_wrapper .send_message .text {
font-size: 18px;
font-weight: 300;
display: inline-block;
line-height: 48px;
}
.message_template {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="chat_window">
<ul class="messages"></ul>
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type here..." />
</div>
<div class="send_message">
<div class="icon"></div>
<div class="text">
Send
</div>
</div>
</div>
</div>
<div class="message_template">
<li class="message">
<div class="text_wrapper">
<p class="text"></p>
</div>
</li>
</div>
You can also add:
$(".left").css("color", "yellow");
$(".right").css("color", "blue");
$("li.message.left > div.text_wrapper > p").css('color', 'red');
$("li.message.right > div.text_wrapper > p").css('color', 'blue');
Using jQuery you can add inline style to an element
$(".left").attr("style","whatever");
$(".right").attr("style","whatever");
You can use the classList of every HTML component. Simply, select the DOM element with class left (or right) and use the add method to assign whatever class:
var elementLeft = $('.left')
elementLeft.classList.add('yourClass')
You can also use the methods remove to remove any class, or toggle to toggle some class..
elementLeft.classList.remove('yourClass')
elementLeft.classList.toggle('yourClass')
The Element.classList contains more examples. This solution works without jQuery or others javascript library, but use the standard API.

Properly position two DIVs - One as a fixed sidebar, and other as expanding

I have the following code to create a simple website with two sections; a sidebar and the main content:
html, body {
height: 100%;
margin: 0;
}
.container {
display: flex;
flex-direction: row;
height: 100%;
}
.sidebar {
background-color: #FFF5BA;
width: 200px;
}
.main {
background-color: rgba(248, 248, 248, 1);
flex-grow: 1;
}
The HTML is as goes:
<div class="container">
<div class="sidebar">
<div class="main">
</div>
The problem I have happens when you dynamically add more content to the main section with JavaScript. If you add enough to require scrolling, then the sidebar will not grow as you scroll down.
Ideally I would like to leave the sidebar as fixed content that scrolls with you, but I have read that you cannot combine flexbox with position: fixed.
If you need to see the complete here it is:
https://codepen.io/wulfenn/pen/LYNRNEv (apologies in advance if the code is sloppy; I am still learning)
Thank you for your help!
I have updated html code by moving modal code outside of container class.
I have used position:sticky on sidebar class and assign height:100vh. so that it would not scroll if main content height is bigger than 100vh.
I have also added dummy book-add div to create more height of main content.
View results in full screen and only first add button will work.
// Declare the Object constructor.
function Book(title, author, pages, isbn, read, bookURL) {
this.title = title;
this.author = author;
this.pages = pages;
this.isbn = isbn;
this.read = read;
this.bookURL = bookURL;
}
Book.prototype.toggleStatus = function () {
if (this.read == 'Read') {
this.read = 'Not Read';
return 1;
} else if (this.read == 'Not Read') {
this.read = 'Reading';
return 2;
} else if (this.read == 'Reading') {
this.read = 'Read';
return 3;
}
}
// Initalize library variables.
let myLibrary = [];
const container = document.querySelector('.books-container');
// Display and Hide the "Add a Book" form.
const popup = document.querySelector('.form-popup');
const addBtn = document.querySelector('.add-btn');
const cancelBtn = document.getElementById('cancel-btn');
addBtn.addEventListener('click', function () {
popup.style.display = 'block'; // Show
})
cancelBtn.addEventListener('click', function () {
popup.style.display = 'none'; // Hide
})
// #### Book Form Start
// ##
// Get the form values
const form = document.getElementById('form1');
form.addEventListener('submit', function (event) {
const title = document.forms[0].elements[1].value;
const author = document.forms[0].elements[2].value;
const pages = document.forms[0].elements[3].value;
const isbn = document.forms[0].elements[4].value;
const bookURL = document.forms[0].elements[0].value;
// Check which radio button has been selected.
let read = '';
if (document.getElementById('read').checked) {
read = 'Read';
} else if (document.getElementById('unread').checked) {
read = 'Not Read';
} else {
read = 'Reading';
}
// Prevent page from refreshing and closing the form popup.
event.preventDefault();
popup.style.display = 'none';
// Add our book.
addBookToLibrary(title, author, pages, isbn, read, bookURL);
// Display the books and reset the form.
render();
form.reset();
})
// Display our cover preview.
const cover = document.querySelector('.cover-preview');
const isbnField = document.getElementById('isbn'); // In case ISBN has been typed
const coverURL = document.getElementById('url'); // In case URL has been used.
coverURL.addEventListener('change', function () {
cover.style.background = `url(${document.forms[0].elements[0].value})`;
cover.style.backgroundSize = 'cover';
})
isbnField.addEventListener('change', function () {
if (document.forms[0].elements[0].value == '') { // URL takes preference as it's chosen by user.
cover.style.background = `url(http://covers.openlibrary.org/b/isbn/${document.forms[0].elements[4].value}-M.jpg)`;
cover.style.backgroundSize = 'cover';
}
})
// Add a given book to myLibrary array
function addBookToLibrary(title, author, pages, isbn, read, bookURL) {
let book = new Book(title, author, pages, isbn, read, bookURL);
myLibrary.push(book);
}
// ##
// #### Book Form End
// Display the books in our HTML
function render() {
// Clear our space first.
const existingDivs = document.querySelectorAll('[data-book]');
existingDivs.forEach((div) => {
div.remove();
});
for (let i = 0; i < myLibrary.length; i++) {
let element = document.createElement('div');
element.classList.add('book');
// Determine our cover. URL overrides ISBN.
if (myLibrary[i]['bookURL']) {
element.style.background = `url(${myLibrary[i]['bookURL']})`;
} else {
element.style.background = `url(http://covers.openlibrary.org/b/isbn/${myLibrary[i]['isbn']}-M.jpg)`;
}
element.style.backgroundSize = 'cover';
element.setAttribute("data-book", i);
// Create our mouse enter divs to display book information.
let infoDiv = document.createElement('div');
infoDiv.classList.add('book-info');
infoDiv.style.display = 'none'; // Set to not display by deafult until mouse enter.
let titleDiv = document.createElement('div');
titleDiv.classList.add('info-title');
titleDiv.textContent = myLibrary[i]['title'];
let authorDiv = document.createElement('div');
authorDiv.classList.add('info-author');
authorDiv.textContent = `by ${myLibrary[i]['author']}`;
let pagesDiv = document.createElement('div');
pagesDiv.classList.add('info-pages');
pagesDiv.textContent = `Pages: ${myLibrary[i]['pages']}`;
// Create our status buttons and our delete button.
let buttonsDiv = document.createElement('div');
buttonsDiv.classList.add('info-buttons');
let readTag = document.createElement('button');
readTag.classList.add('button-status');
readTag.setAttribute('data-bookstatus', i);
if (myLibrary[i]['read'] == 'Read') {
readTag.style.background = '#EBFFE5';
readTag.textContent = '✔';
} else if (myLibrary[i]['read'] == 'Not Read') {
readTag.style.background = '#FFC1B1';
readTag.textContent = '❌';
} else {
readTag.style.background = '#FFFFEA';
readTag.textContent = '📖';
}
let removeTag = document.createElement('button');
removeTag.classList.add('button-status');
removeTag.textContent = '🗑';
removeTag.setAttribute("data-bookremove", i);
// Add everything together
buttonsDiv.appendChild(readTag);
buttonsDiv.appendChild(removeTag);
infoDiv.appendChild(titleDiv);
infoDiv.appendChild(authorDiv);
infoDiv.appendChild(pagesDiv);
infoDiv.appendChild(buttonsDiv);
element.appendChild(infoDiv);
// Insert the finished product
container.insertBefore(element, container.firstChild);
}
// Display book information on mouseover
const bookFrames = Array.from(document.querySelectorAll('.book'));
bookFrames.forEach((bookFrame) => {
bookFrame.addEventListener('mouseenter', function (e) {
bookFrame.firstChild.style.display = 'block';
});
});
bookFrames.forEach((bookFrame) => {
bookFrame.addEventListener('mouseleave', function (e) {
bookFrame.firstChild.style.display = 'none';
});
});
// Add functionality to our status and delete buttons
const statusButtons = Array.from(document.querySelectorAll('button[data-bookstatus'));
statusButtons.forEach((button) => {
button.addEventListener('click', function () {
let index = button.getAttribute('data-bookstatus');
let x = myLibrary[index].toggleStatus();
switch (x) {
case 1:
button.style.background = '#FFC1B1';
button.textContent = '❌';
break;
case 2:
button.style.background = '#FFFFEA';
button.textContent = '📖';
break;
case 3:
button.style.background = '#EBFFE5';
button.textContent = '✔';
break;
}
});
});
//Remove button
const removeButtons = Array.from(document.querySelectorAll('button[data-bookremove]'));
removeButtons.forEach((button) => {
button.addEventListener('click', function () {
let index = button.getAttribute('data-bookremove');
const bookToRemove = document.querySelector(`div[data-book='${index}']`);
bookToRemove.remove(); // Remove it from the DOM.
myLibrary.splice(index, 1); // Remove it from our array so it does not render again.
});
});
}
#import url("https://fonts.googleapis.com/css?family=Special Elite&display=swap");
html,
body {
height: 100%;
margin: 0;
font-family: "Special Elite";
}
.container {
width: 100%;
display: flex;
justify-content: space-evenly;
align-items: flex-start;
}
.sidebar {
position: sticky;
top: 0%;
left: 0%;
background-color: #fff5ba;
width: 200px;
height:100vh;
}
.main {
background-color: rgba(248, 248, 248, 1);
flex-grow: 1;
}
.books-container {
background-color: rgba(248, 248, 248, 1);
margin-left: auto;
margin-right: auto;
position: relative;
top: 10%;
left: 50%;
transform: translate(-50%);
display: flex;
flex-wrap: wrap;
}
.book {
width: 200px;
height: 300px;
margin: 50px 25px;
border: 1px solid rgba(0, 0, 0, 0.5);
border-radius: 5px;
box-shadow: 3px 3px 5px 0px black;
}
.book-info {
background-color: rgba(0, 0, 0, 0.6);
width: 200px;
height: 300px;
}
.info-title {
position: relative;
top: 15%;
color: white;
font-size: 20px;
text-align: center;
text-shadow: 3px 3px 1px black;
}
.info-author {
position: relative;
top: 20%;
color: white;
font-size: small;
font-style: italic;
text-align: center;
text-shadow: 1px 1px 1px black;
}
.info-pages {
position: relative;
top: 23%;
color: #fff5ba;
font-size: 11px;
font-weight: bold;
text-align: center;
text-shadow: 1px 1px 1px black;
}
.info-buttons {
position: relative;
top: 40%;
left: 20%;
}
.button-status {
width: 50px;
height: 50px;
outline: none;
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 50px;
margin-left: 5px;
box-shadow: 3px 3px 5px 0px rgba(0, 0, 0, 0.8);
background-color: rgba(255, 255, 255, 0.8);
font-size: 25px;
}
.button-status:hover {
transform: scale(1.1);
}
.book-add {
width: 200px;
height: 300px;
margin: 50px 25px;
border: 1px solid rgba(0, 0, 0, 0.5);
border-radius: 5px;
box-shadow: 3px 3px 5px 0px black;
}
.add-btn {
position: relative;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 100px;
height: 100px;
background: inherit;
outline: none;
border-radius: 100px;
font-size: 4em;
}
.add-btn:hover {
background-color: #fff5ba;
}
.cover {
width: 200px;
height: 300px;
}
.cover-preview-container {
position: absolute;
right: 10%;
text-align: center;
}
.cover-preview {
width: 100px;
height: 150px;
border: 1px solid black;
position: relative;
left: 30%;
margin-bottom: 10px;
margin-top: 5px;
}
.form-popup {
display: none;
position: fixed;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.7);
}
.book-form-container {
position: fixed;
z-index: 1;
padding-top: 100px;
left: 50%;
top: 50%;
width: 500px;
height: 500px;
transform: translate(-50%, -50%);
overflow: hidden;
background-color: #836953;
border: 1px solid black;
border-radius: 5px;
}
.form-header {
position: absolute;
top: 0px;
background: url(assets/books.jpeg);
background-size: cover;
width: 500px;
height: 150px;
border-bottom: 1px solid black;
font-size: 4em;
text-align: center;
color: white;
text-shadow: 3px 3px 1px black;
}
.form-footer {
position: absolute;
bottom: 0px;
background: url(assets/wood.jpeg);
background-size: cover;
width: 500px;
height: 150px;
border-bottom: 1px solid black;
font-size: 4em;
text-align: center;
color: white;
text-shadow: 3px 3px 1px black;
}
.book-form {
position: absolute;
top: 150px;
bottom: 150px;
width: 500px;
padding: 20px;
line-height: 20px;
background-color: #fff5ba;
}
.entry-box {
height: 20px;
border-radius: 5px;
outline: none;
background-color: rgba(240, 240, 240, 0.5);
margin-bottom: 15px;
}
.form-btn {
margin: 40px 40px;
width: 100px;
height: 50px;
border: 1px solid white;
border-radius: 10px;
background: inherit;
color: white;
font-family: inherit;
font-size: 20px;
box-shadow: 3px 3px 1px 1px black;
outline: none;
}
.form-btn:hover {
transform: scale(1.1);
}
<div class="container">
<div class="sidebar">
<div class="my-library">My Library</div>
<div class="menu">Home</div>
</div>
<div class="main">
<div class="books-container">
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
<div class="book-add">
<button class="add-btn">+</button>
</div>
</div>
</div>
</div>
<div class="form-popup">
<div class="book-form-container">
<div class="form-header"><br />Add a Book</div>
<div class="book-form">
<form id="form1">
<div class="cover-preview-container">Cover
<div class="cover-preview"></div>
<div><span style="font-size: small">Or enter the link to the cover image:</span> <br /><input class="entry-box" id="url" type="url" placeholder="https://"></div>
</div>
<div>
<label for="title"> Title </label><br />
<input class="entry-box" type="text" id="title" name="title" placeholder="Enter the book title." required>
</div>
<div>
<label for="author"> Author</label><br />
<input class="entry-box" type="text" id="author" name="author" placeholder="Enter the Author." required>
</div>
<div>
<label for="pages"> Pages</label><br />
<input class="entry-box" type="number" id="pages" name="pages" min="1" placeholder="0" required>
</div>
<div>
<label for="isbn"> ISBN <span style="font-size: small"><i><sup>what is this?</sup></i></span></label><br />
<input class="entry-box" type="text" id="isbn" name="isbn" placeholder="(optional)">
</div>
<div style="text-align: center">
<label for="read">Read</label>
<input id="read" type="radio" name="status" value="read" required>
<label for="unread">Not Read</label>
<input id="unread" type="radio" name="status" value="unread" required>
<label for="reading">Reading</label>
<input id="reading" type="radio" name="status" value="reading" required>
</div>
</form>
</div>
<div class="form-footer">
<button id="form-add-btn" type="submit" class="form-btn" form="form1">Add</button>
<button id="cancel-btn" class="form-btn">Cancel</button>
</div>
</div>
</div>

Add checkbox to price calculation

Currently my price output gets calculated based on the chosen quantity of an input field. I have been trying to add a checkbox to this calculation that, if checked, adds $5 to the total price. That being said, I haven't been very successful. In my understanding, there are two calculations going on:
I hit the increase/decrease button and it checks if the checkbox has been selected
I select the checkbox and it calculates the total price
This is the code I have so far:
function IncludePrice()
{
var IncludePrice=0;
var include = theForm.elements["include"];
if(include.checked==true)
{
IncludePrice=5;
}
return IncludePrice;
}
$(".incr-btn_mobile").on("click", function(e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
var cakePrice = newVal;
var includep = IncludePrice();
var divobj = document.getElementById($button.attr('data-target'));
divobj.style.display = 'block';
divobj.innerHTML = "= $" + (cakePrice) * 7.99 + (includep);
e.preventDefault();
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>
UPDATE:
I changed made some changes based on the feedback here, but this seems to break the increase/decrease field. Here is the code as is:
$(".incr-btn_mobile").on("click", function(e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
var cakePrice = newVal;
var includep = theForm.elements.include.checked * 5;
var divobj = document.getElementById($button.attr('data-target'));
divobj.style.display = 'block';
divobj.innerHTML = "= $" + (cakePrice) * 7.99 + (includep);
e.preventDefault();
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>
There you go my friend. I only change your js code. There is all the change I made:
Deleted your IncludePrice function since you could do it in only one row. And do never user function name for a variable. It could possibly break your code.
All switched for jQuery use instead of half jQuery and native JS.
Created a function for checkbox onclick to change the prince dynamicly.
I changed the names of your variables to make them more specific.
Added some comments to make the code clearer.
var _EXTRAVAL = 5;
$(".incr-btn_mobile").on("click", function(e) {
// Prevent default action
e.preventDefault();
// Set variable for the method
var button = $(this);
var labelNb = button.parent().find('.quantity');
var labelPrice = $("#" + button.attr('data-target'));
var currentNb = button.parent().find('.quantity').val();
var newNb = 0;
// Remove 'inactive' class
$('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
// Increase or decrease
if (button.attr('data-action') == "increase") {
newNb = parseFloat(currentNb) + 1;
} else {
// Don't allow decrementing below 1
if (currentNb > 1) {
newNb = parseFloat(currentNb) - 1;
} else {
newNb = 1;
button.addClass('inactive');
}
}
var isExtra = $("#include").prop('checked') ? _EXTRAVAL : 0;
$(labelNb).val(newNb);
$(labelPrice).css('display', 'block').html("= $" + String((((newNb) * 7.99) + (isExtra)).toFixed(2)));
});
$("#include").on('click', function(){
// Set variable for method
var checkbox = $(this);
var labelPrice = $("#" + $(".incr-btn_mobile").attr('data-target'));
var labelPriceFloat = parseFloat(labelPrice.html().substring(4));
// If checkbox is check, increse price
if (checkbox.prop('checked')) {
labelPrice.html("= $" + String((labelPriceFloat + _EXTRAVAL).toFixed(2)));
} else {
labelPrice.html("= $" + String((labelPriceFloat - _EXTRAVAL).toFixed(2)));
}
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>

Get values from dynamic inputs generated by javascript

I am writing a generator for improving my knowledge of PHP programming and handling as I am weak and I already know that I would like to ask how I can make this.
Generate input data in javascript and I want to dynamically capture their value in PHP. I do not know how many of them, because they are generated after clicking the button in, hence the problem.
At the same moment I succeeded in JS up using this name: name_0, name_1 and so on.
Is it feasible? Below I do not
var tytul = document.getElementById("k-title");
var opis = document.getElementById("k-description");
var popup = document.getElementById("info_box");
var overlay = document.getElementById("overlay");
var podsumowanie = document.getElementById("summary");
$("#add").on("click", function () {
var id = $(".wiersz").length;
$('#tabela').append('<tr class="wiersz"><td class="komorka-lewa"> <input class="cecha" name="cecha_'+ id + '" type="text" placeholder="Cecha produktu"> </td><td class="komorka-prawa"><input class="cecha-opis" name="cecha-opis_'+ id + '" type="text" placeholder="Opis cechy produktu"></td></tr>');
document.getElementById("default-table").style = "display: none";
});
$("#add_square").on("click", function() {
var szerokosc = prompt("Podaj szerokość obrazka");
var wysokosc = prompt("Podaj wysokość obrazka");
var sciezka = prompt("Podaj link do zdjęcia");
$("#other-photos").append('<div class="other-img" style="width: '+szerokosc+'px;"><img class="img-present" style="height: '+ wysokosc +'px;" src="'+sciezka+'" /></div>');
if (szerokosc < 1050) {
$(".other-img").css("float", "left");
}
});
$("#add_photo").on("click", function () {
var sciezka = prompt("Podaj link do zdjęcia");
var opis = prompt("Podaj opis zdjęcia dla wyszukiwarek");
$("#gallery").append('<div class="photo-container"><button class="del">Usuń zdjęcie</button><img src="' + sciezka + '" class="photo" alt="' + opis + '"/></div>');
if ($(".photo").length > 0) {
document.getElementById("default-gallery").style = "display: none";
}
$(".del").on("click", function () {
$(this).parent().css("display", "none");
document.getElementById("default-gallery").style = "display: block";
});
});
$("#gen").on("click", function () {
if (opis.value.length < 1 || tytul.value.length < 1) {
popup.style = "display: block";
overlay.style = "display: block";
document.getElementById("infobox-content").innerHTML = "Uzupełnij wszystkie potrzebne dane, zanim wygenerujesz kartę produktu.";
} else {
popup.style = "display: block";
overlay.style = "display: block";
document.getElementById("infobox-content").innerHTML = "Karta została wygenerowana, plik z kodem znajduje się w katalogu generate.";
podsumowanie.innerHTML = "Tytuł: " + tytul.value + "<br>" + "Opis produktu: " + opis.value + "<br>" + "Cecha produktu: " + cecha + "<br>" + "Opis cechy produktu: " + cechaopis;
}
});
$("#close").on("click", function() {
popup.style = "display: none";
overlay.style = "display: none";
});
$("#add_section").on("click", function() {
var szerokosc = prompt("Określ szerokość sekcji");
var wysokosc = prompt("Określ wysokosć sekcji");
var tlo = prompt("Określ kolor tła sekcji (paleta RGB - np. FFFFFF)");
var kolor = prompt("Określ kolor tekstu w sekcji (paleta RGB - np. FFFFFF)");
$("#new_section").append('<div class="sekcja" style="width: '+ szerokosc +'px; height: '+ wysokosc +'px; background: #'+ tlo +'; color: #'+ kolor +';"><button type="button" class="check_btn">Checklista</button><button type="button" class="txt_btn">Sekcja tekstowa</button></div>');
if ($(".sekcja").length > 0) {
$("#default-section").css("display","none");
}
if(szerokosc < 1050) {
$(".sekcja").css("float","left");
}
});
body {
margin: 0;
font-family: 'open sans',sans-serif;
font-size: 15px;
}
.wiersz {
background-color: #eee;
margin: 0;
}
.komorka-lewa {
padding: 3px 10px;
text-align: right;
border-right: 1px solid #dbdbdb;
}
.komorka-prawa {
padding: 3px 10px;
text-align: left;
}
#tabela {
font-size: 14px;
border: none;
border-top: 1px solid #dbdbdb;
border-bottom: 1px solid #dbdbdb;
width: 100%;
}
.cecha, .cecha-opis {
border: 0;
margin: 0;
background: 0;
}
#gen {
display: block;
width: 100%;
margin-top: 10px;
}
#add, #gen, #add_photo, #add_section {
border: 0;
padding: 10px;
background: #222;
color: #fff;
border-radius: 3px;
font-family: 'open sans',sans-serif;
font-size: 15px;
}
#add:hover, #gen:hover, #add_photo:hover, #add_section:hover, .check_btn:hover, .txt_btn:hover {
background: green;
cursor: pointer;
transition-duration: 1s;
}
#add_section {
margin-top: 25px;
margin-bottom: 25px;
}
#container {
max-width: 1050px;
margin-left: auto;
margin-right: auto;
}
#overlay {
width: 100%;
height: 100%;
background: rgba(0,0,0,0.6);
z-index: 2;
position: absolute;
}
#info_box {
background: #fff;
position: absolute;
z-index: 3;
width: 500px;
top: 50%;
transform: translateY(-50%);
padding: 10px;
padding-top: 0;
left: 50%;
margin-left: -250px;
}
#info_box p:first-child {
font-size: 20px;
border-bottom: 1px solid #eaeaea;
padding-bottom: 10px;
}
#info_box, #overlay {
display: none;
}
#info_box > p span {
cursor: pointer;
color: red;
}
.photo {
display: block;
width: 100%;
}
.photo:first-child {
margin-top: 25px;
}
.photo:last-child {
margin-bottom: 25px;
}
#default-gallery, #default-section {
font-size: 14px;
border-bottom: 1px solid #dbdbdb;
padding: 5px;
}
.photo-container {
position: relative;
overflow: hidden;
margin-bottom: 25px;
}
.photo-container:first-child {
margin-top: 25px;
}
.photo-container:last-child {
margin-bottom: 25px;
}
.del {
position: absolute;
bottom: 50px;
right: 25px;
background: transparent;
border: 3px solid #fff;
padding: 10px;
font-family: 'open sans',sans-serif;
font-size: 15px;
color: #fff;
border-radius: 3px;
}
.del:hover {
background: #fff;
cursor: pointer;
transition-duration: 0.5s;
color: #222;
}
#add_square {
width: 150px;
height: 150px;
background: #eaeaea;
margin-bottom: 25px;
padding: 20px;
border: 1px solid #c0c0c0;
}
#add_square:hover {
background: #222;
cursor: pointer;
transition-duration: 0.5s;
color: #fff;
}
.img-present {
max-width: 100%;
}
.other-img:last-child {
margin-bottom: 25px;
}
.sekcja {
position: relative;
}
.check_btn, .txt_btn {
position: absolute;
top: 50%;
transform: translateY(-50%);
padding-top: 10px;
padding-bottom: 10px;
border: 0;
background: #000;
font-size: 15px;
font-family: 'open sans',sans-serif;
color: #fff;
}
.check_btn {
left: 0;
border-top-right-radius: 3px;
border-bottom-right-radius: 3px;
}
.txt_btn {
right: 0;
b
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="info_box">
<p>Informacja <span id="close" style="float: right;">x</span></p>
<p id="infobox-content"></p>
</div>
<div id="overlay"></div>
<div id="container">
<form method="post" action="">
<div style="padding-top: 50px; padding-bottom: 50px;">
<input type="text" value="" id="k-title" name="k-title" placeholder="Tytuł karty" style="display: block; width: 100%; font-size: 30px; border: 0; background: 0; margin-bottom: 25px; text-align: center;">
<input type="text" value="" id="k-description" name="k-desc" placeholder="Krótki opis" style="display: block; width: 100%; border: 0; background: 0; text-align: justify; padding: 10px;">
</div>
<div style="width: 100%; text-align: center; background-color: #eee; font-weight: 200; line-height: 0.92em; padding: 23px 0; font-size: 30px;">Specyfikacja techniczna</div>
<table id="tabela" border="0" cellspacing="0" cellpadding="5px">
<tbody>
<tr>
<td colspan="2" id="default-table">Brak dodanej specyfikacji</td>
<tr>
</tbody>
</table>
<button style="margin-top: 25px; margin-bottom: 25px;" id="add" type="button">Dodaj wiersz</button>
<div id="other-photos">
<div id="add_square" style="position: relative;">
<p style="text-align: center; position: absolute; width: 150px; top: 40px; font-size: 60px; margin: 0;">+</p>
<p style="text-align: center; position: absolute; width: 150px; bottom: 40px; margin: 0;">Dodaj obrazek prezentacji</p>
</div>
</div>
<div style="clear: both;"></div>
<div style="width: 100%; text-align: center; background-color: #eee; font-weight: 200; line-height: 0.92em; padding: 23px 0; font-size: 30px;">Dodaj nową sekcję</div>
<div id="new_section">
<div id="default-section">Brak dodanych sekcji</div>
</div>
<div style="clear: both;"></div>
<button type="button" id="add_section">Dodaj sekcję</button>
<div style="width: 100%; text-align: center; background-color: #eee; font-weight: 200; line-height: 0.92em; padding: 23px 0; font-size: 30px;">Galeria zdjęć</div>
<div id="default-gallery">Brak dodanych zdjęć</div>
<div id="gallery">
</div>
<button style="margin-top: 25px; margin-bottom: 25px;" id="add_photo" type="button">Dodaj zdjęcia</button>
<input id="gen" type="submit" value="Generuj kartę" />
</div>
<div id="summary">
</div>
</form>
Simplest Solution:
Name your generated Inputfields like:
<input ... name="field[]"> // see the []-Brackets
<input ... name="field[]">
<input ... name="field[]">
The Brackets will cause, that there will be sent an Array named "field" when submitting the Form. Of course you can also give them a Key like field[0], field[1] or what ever.
After you submitted the Form you can handle it like any other PHP-Array.
For Example:
foreach($_POST['field'] as $fieldno => $fieldvar){
echo 'field '.$fieldno.': '.$fieldvar.'<br>';
}
Tip: Using the same Keys for the same Section is quite helpful for processing trough the Data:
<input name="givenname[0]"><input name="lastname[0]"><input name="age[0]">
<input name="givenname[1]"><input name="lastname[1]"><input name="age[1]">
<input name="givenname[2]"><input name="lastname[2]"><input name="age[2]">
You can catch these Data after submitting this way:
foreach($_POST['givenname'] as $id => $givenname){
echo 'person #'.$id.': '.$_POST['lastname'][$id].', '.$givenname.', '.$_POST['age'][$id].'<br>';
}

Categories

Resources