Not refreshing second select dropdown list - javascript

I am new in web development, I appreciate your help with this problem. I am trying to build and HTML form using Apps Script, materialize CSS and JavaScript. I have two dependent selects, the first one with id "tipo" and the second with id "nov". These two are dependent, if i choose in the first select an option, only for the second select must appears only the options that belongs to that category. for example, when i select in the first dropdown the option calls "servicios publicos" the second select only must show the options: agua, luz, energia, gas and telef/internet. The problem is in the second select with id "nov" its not refreshing, only appears the option calls "agua", but the select its not working, when you clicked it.
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
google.script.run.withSuccessHandler(populateWords).getWords();
document.getElementById("frmRegister").addEventListener("submit", empres);
document.getElementById('nov').addEventListener("click", 'select');
});
function populateWords(words) {
var autocomplete = document.getElementById('pto');
var instances2 = M.Autocomplete.init(autocomplete, {
data: words
});
}
function empres(e) {
// prevenir un evento por defecto
e.preventDefault();
var userInfo = {};
userInfo.punto = document.getElementById("pto").value;
userInfo.tiponov = document.getElementById("tipo").value;
userInfo.novedad = document.getElementById("nov").value;
userInfo.check = document.getElementById("ch").value;
userInfo.detalle = document.getElementById("textarea1").value;
google.script.run.registroEmp(userInfo);
document.getElementById("pto").value = "";
document.getElementById("tipo").value = "";
document.getElementById("nov").value = "";
document.getElementById("ch").value = "";
document.getElementById("textarea1").value = "";
var selectList = document.getElementById("tipo");
selectList.selectedIndex = 0;
M.FormSelect.init(selectList);
var selectList2 = document.getElementById("nov");
selectList2.selectedIndex = 0;
M.FormSelect.init(selectList2);
var selectList3 = document.getElementById("ch");
selectList3.selectedIndex = 0;
M.FormSelect.init(selectList3);
//var datePicker =document.getElementById("fecha");
//datePicker.value ="";
//M.Datepicker.init(datePicker);
}
* {
top: 0;
left: 0;
margin: 0;
padding: 0;
}
.form-row {
margin-bottom: 0px;
}
.row1 {
display: inline-block;
margin-right: auto;
margin-left: auto;
padding: 2px;
}
.warning-bar {
visibility: hidden;
}
img {
width: 250px;
height: auto;
margin: 10px;
margin-top: 8px;
padding-top: 15px;
}
.page-footer {
background: black;
border-top: 1px solid #e4e4e4;
}
.container-footer {
color: black;
background-color: #FFFFFF;
margin-left:
}
.page-footer.footer-copyright {
background-color: #FFFFFF;
}
.div.footer-copyright {
color: black;
background-color: #FFFFFF;
}
.footer.page-footer {
background-color: black;
}
.page-footer .footer-copyright {
background-color: #FFFFFF;
border-top: 1px solid #e4e4e4;
}
p.black-text-copyright {
padding-left: 15px;
text-align: left;
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted #FFFFFF;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #17202A;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
h3 {
text-align: center;
}
btn {
float: none;
text-align: center;
margin-bottom: 20px;
padding-left: 30px;
padding-top: 10px;
}
h5 {
text-align: center;
}
.title {
color: red;
text-align: center;
}
h4 {
text-align: center;
}
}
body {
background-image: url("https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg");
width: 100%;
margin: 0;
padding: 0;
font-family: 'Josefin Sans', sans-serif;
}
button {
margin-bottom: 20px;
}
html {
top: 0;
left: 0;
margin: 0;
padding: 0;
width: 100%;
}
.login {
width: 400px;
margin: 16px auto;
font-size: 16px;
position: relative;
}
}
.frmHome {
margin-left: auto;
margin-right: auto;
}
.select-wrapper .caret {
position: absolute;
right: 0;
top: 0;
bottom: 0;
margin: auto 0;
z-index: 0;
fill: rgba(0, 0, 0, 0.0);
}
.login-triangle {
width: 0;
margin-right: auto;
margin-left: auto;
border: 12px solid transparent;
border-bottom-color: #1ABC9C;
margin-top: 60px;
}
.login-header {
background: #1ABC9C;
padding: 20px;
font-size: 1.4em;
font-weight: normal;
text-align: center;
border-radius: 4px;
color: #fff;
margin-bottom: 0;
margin-top: 0px;
}
.login-container {
background: #FDFEFE;
padding: 30px;
margin-left: auto;
margin-right: auto;
border: 1px solid #D5D8DC;
border-radius: 6px;
margin-top: 0px;
}
.textarea.materialize-textarea {
margin-left: auto;
margin-right: auto;
}
<!DOCTYPE html>
<html>
<head>
<base target="_Self">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">
<?!= include("page-css"); ?>
</head>
<body>
<img style="position:absolute; width:100%; height:auto; margin:0; padding:0; background:https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg"
src="https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg">
<div class="login">
<div class="login-triangle"></div>
<h2 class="login-header">Registro Novedades</h2>
<form id="frmRegister" class="login-container">
<div class="row">
<div class="input-field col s12">
<i style="color:#1ABC9C" class="material-icons prefix">search</i>
<input type="text" id="pto" class="autocomplete">
<label for="pto">Consulta el punto de servicio</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="tipo" onchange="ChangeCarList()">
<option value=""></option>
<option value="SP">Servicios Públicos</option>
<option value="SG">Seguridad</option>
<option value="AD">Administración</option>
<option value="CV">Convivencia</option>
</select>
<label for="tipo">Selecciona el tipo de novedad</label>
</div>
<div class="input-field col s12">
<select id="nov"></select>
<label>Novedad</label>
</div>
</div>
<script>
var carsAndModels = {};
carsAndModels['SP'] = ['Agua', 'Aseo', 'Energia', 'Gas', 'Telef/Internet'];
carsAndModels['SG'] = ['Hurto a residencias', 'Intervención Policia Nal', 'Orden Público',
'Lesiones Personales', 'Alarma', 'Daños Infraestruc/Bienes'
];
carsAndModels['AD'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("tipo");
var modelList = document.getElementById("nov");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
<div class="row">
<div class="input-field col s12">
<select id="ch">
<option value="" disabled selected>Generar Alerta</option>
<option>Si</option>
<option>No</option>
</select>
<label>¿Desea generar alerta de pánico?</label>
</div>
</div>
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Ingrese el detalle del evento</label>
</div>
<button style="width:100%; margin-top:20px;" class="waves-effect waves-light btn-small" type="submit"
name="action">Enviar
<i class="material-icons right">send</i>
</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<?!= include("page-js"); ?>
</body>
</html>

The problem is: the select input is rendered with Materialize on page load, it adds HTML elements to you're initial code to make the UI looks the way it looks,
All you have to do is to trigger this after you add the select options, so I moved this code from Javascript file ( which triggers only once at the beginning ) into the ChangeCarList() so that the Materialize can create the proper dropdown with new options.
var selectList2 = document.getElementById("nov");
selectList2.selectedIndex = 0;
M.FormSelect.init(selectList2);
Since you already have the variable modelList contains the nov, I just used it instead of re-selecting it.
I hope this is the result you were looking for, Good Luck.
document.addEventListener('DOMContentLoaded', function () {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems);
//google.script.run.withSuccessHandler(populateWords).getWords();
document.getElementById("frmRegister").addEventListener("submit", empres);
// document.getElementById('nov').addEventListener("click", 'select');
});
function populateWords(words) {
var autocomplete = document.getElementById('pto');
var instances2 = M.Autocomplete.init(autocomplete, {
data: words
});
}
function empres(e) {
e.preventDefault();
var userInfo = {};
userInfo.punto = document.getElementById("pto").value;
userInfo.tiponov = document.getElementById("tipo").value;
userInfo.novedad = document.getElementById("nov").value;
userInfo.check = document.getElementById("ch").value;
userInfo.detalle = document.getElementById("textarea1").value;
google.script.run.registroEmp(userInfo);
document.getElementById("pto").value = "";
document.getElementById("tipo").value = "";
document.getElementById("nov").value = "";
document.getElementById("ch").value = "";
document.getElementById("textarea1").value = "";
var selectList = document.getElementById("tipo");
selectList.selectedIndex = 0;
M.FormSelect.init(selectList);
var selectList3 = document.getElementById("ch");
selectList3.selectedIndex = 0;
M.FormSelect.init(selectList3);
//var datePicker =document.getElementById("fecha");
//datePicker.value ="";
//M.Datepicker.init(datePicker);
}
* {
top: 0;
left: 0;
margin: 0;
padding: 0;
}
.form-row {
margin-bottom: 0px;
}
.row1 {
display: inline-block;
margin-right: auto;
margin-left: auto;
padding: 2px;
}
.warning-bar {
visibility: hidden;
}
img {
width: 250px;
height: auto;
margin: 10px;
margin-top: 8px;
padding-top: 15px;
}
.page-footer {
background: black;
border-top: 1px solid #e4e4e4;
}
.container-footer {
color: black;
background-color: #FFFFFF;
margin-left:
}
.page-footer.footer-copyright {
background-color: #FFFFFF;
}
.div.footer-copyright {
color: black;
background-color: #FFFFFF;
}
.footer.page-footer {
background-color: black;
}
.page-footer .footer-copyright {
background-color: #FFFFFF;
border-top: 1px solid #e4e4e4;
}
p.black-text-copyright {
padding-left: 15px;
text-align: left;
}
.tooltip {
position: relative;
display: inline-block;
border-bottom: 1px dotted #FFFFFF;
}
.tooltip .tooltiptext {
visibility: hidden;
width: 120px;
background-color: #17202A;
color: #fff;
text-align: center;
border-radius: 6px;
padding: 5px 0;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
margin-left: -60px;
opacity: 0;
transition: opacity 0.3s;
}
.tooltip .tooltiptext::after {
content: "";
position: absolute;
top: 100%;
left: 50%;
margin-left: -5px;
border-width: 5px;
border-style: solid;
border-color: #555 transparent transparent transparent;
}
.tooltip:hover .tooltiptext {
visibility: visible;
opacity: 1;
}
h3 {
text-align: center;
}
btn {
float: none;
text-align: center;
margin-bottom: 20px;
padding-left: 30px;
padding-top: 10px;
}
h5 {
text-align: center;
}
.title {
color: red;
text-align: center;
}
h4 {
text-align: center;
}
}
body {
background-image: url("https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg");
width: 100%;
margin: 0;
padding: 0;
font-family: 'Josefin Sans', sans-serif;
}
button {
margin-bottom: 20px;
}
html {
top: 0;
left: 0;
margin: 0;
padding: 0;
width: 100%;
}
.login {
width: 400px;
margin: 16px auto;
font-size: 16px;
position: relative;
}
}
.frmHome {
margin-left: auto;
margin-right: auto;
}
.select-wrapper .caret {
position: absolute;
right: 0;
top: 0;
bottom: 0;
margin: auto 0;
z-index: 0;
fill: rgba(0, 0, 0, 0.0);
}
.login-triangle {
width: 0;
margin-right: auto;
margin-left: auto;
border: 12px solid transparent;
border-bottom-color: #1ABC9C;
margin-top: 60px;
}
.login-header {
background: #1ABC9C;
padding: 20px;
font-size: 1.4em;
font-weight: normal;
text-align: center;
border-radius: 4px;
color: #fff;
margin-bottom: 0;
margin-top: 0px;
}
.login-container {
background: #FDFEFE;
padding: 30px;
margin-left: auto;
margin-right: auto;
border: 1px solid #D5D8DC;
border-radius: 6px;
margin-top: 0px;
}
.textarea.materialize-textarea {
margin-left: auto;
margin-right: auto;
}
.input-field input {
padding-left: 10px
}
.select-wrapper input.select-dropdown {
text-indent: 25px
}
<!DOCTYPE html>
<html>
<head>
<base target="_Self">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/css2?family=Josefin+Sans&display=swap" rel="stylesheet">
<link rel="stylesheet" href="style.css">
</head>
<body>
<img style="position:absolute; width:100%; height:auto; margin:0; padding:0; background:https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg"
src="https://images.pexels.com/photos/3717291/pexels-photo-3717291.jpeg">
<div class="login">
<div class="login-triangle"></div>
<h2 class="login-header">Registro Novedades</h2>
<form id="frmRegister" class="login-container">
<div class="row">
<div class="input-field col s12">
<i style="color:#1ABC9C" class="material-icons prefix">search</i>
<input type="text" id="pto" class="autocomplete">
<label for="pto">Consulta el punto de servicio</label>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select id="tipo" onchange="ChangeCarList()">
<option value=""></option>
<option value="SP">Servicios Públicos</option>
<option value="SG">Seguridad</option>
<option value="AD">Administración</option>
<option value="CV">Convivencia</option>
</select>
<label for="tipo">Selecciona el tipo de novedad</label>
</div>
<div class="input-field col s12 nov-select">
<select id="nov">
</select>
<label>Novedad</label>
</div>
</div>
<script>
var carsAndModels = {};
carsAndModels['SP'] = ['Agua', 'Aseo', 'Energia', 'Gas', 'Telef/Internet'];
carsAndModels['SG'] = ['Hurto a residencias', 'Intervención Policia Nal', 'Orden Público',
'Lesiones Personales', 'Alarma', 'Daños Infraestruc/Bienes'
];
carsAndModels['AD'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("tipo");
var modelList = document.getElementById("nov");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
for (var i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car)
}
}
modelList.selectedIndex = 0;
M.FormSelect.init(modelList);
}
</script>
<div class="row">
<div class="input-field col s12">
<select id="ch">
<option value="" disabled selected>Generar Alerta</option>
<option>Si</option>
<option>No</option>
</select>
<label>¿Desea generar alerta de pánico?</label>
</div>
</div>
<div class="input-field col s12">
<textarea id="textarea1" class="materialize-textarea"></textarea>
<label for="textarea1">Ingrese el detalle del evento</label>
</div>
<button style="width:100%; margin-top:20px;" class="waves-effect waves-light btn-small" type="submit"
name="action">Enviar
<i class="material-icons right">send</i>
</button>
</form>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<script src="index.js"></script>
</body>
</html>
<div class="input-field col s12">
<div class="select-wrapper">
<select id="tipo" onchange="ChangeCarList()" tabindex="-1">
<option value=""></option>
<option value="SP">Servicios Públicos</option>
<option value="SG">Seguridad</option>
<option value="AD">Administración</option>
<option value="CV">Convivencia</option>
</select>
</div>
<label for="tipo">Selecciona el tipo de novedad</label>
</div>

Related

This last step on my Note app... When I click on view more modal window is created, but the wrong one

'use strict';
// Select all elements needed for this task (querySelector)
const form = document.querySelector('.form');
const input = document.querySelector('.input__text');
let container = document.querySelector('.notes-container');
const button = document.querySelector('.btn');
const noteDiv = document.querySelector('.note');
let modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnClose = document.querySelectorAll('.close-modal');
const btnView = document.querySelector('.btn-view');
let noteCount = 0;
// Create function that reads when the button is clicked on form
form.addEventListener('submit', function (e) {
e.preventDefault();
// if input filed is empty note will not be added!
if (!input.value == '') {
// Every time i click on button, notCount is incremented by one. Then that count i store and use to count number of note
if (button.click) noteCount++;
// Creating div element where notes will go
const divNotes = document.createElement('div');
// Adding class to that div element
divNotes.classList.add('note');
// Inserting HTML content into created div
const createdNote = (divNotes.innerHTML += `
<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="btn btn-view">View Detail</button>
`);
container.appendChild(divNotes);
//
container.addEventListener('click', function (e) {
if (!e.target.classList.contains('btn-view')) {
return;
}
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
modal.innerHTML = `<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="close-modal">X</button>
`;
});
modal.addEventListener('click', function (e) {
if (!e.target.classList.contains('close-modal')) {
return;
}
modal.classList.add('hidden');
overlay.classList.add('hidden');
});
}
});
html {
margin: 0;
padding: 0;
font-family: 'Courier New', Courier, monospace;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
}
.container__app {
text-align: center;
}
h1 {
font-size: 4rem;
font-weight: 100;
}
h3 {
font-size: 2rem;
color: green;
margin-top: -40px;
}
.input__text {
width: 1310px;
height: 50px;
margin-bottom: 15px;
padding: 10px;
font-size: 16px;
resize: none;
}
label {
bottom: 36px;
padding: 3px;
vertical-align: top;
font-size: 25px;
font-weight: 600;
}
.btn-green {
color: white;
background-color: green;
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-span {
margin-top: 15px;
}
.btn-green:active {
transform: translateY(4px);
}
.notes-container {
margin: auto;
padding: 25px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
grid-gap: 1.5rem;
}
.note {
border: 1px solid gray;
padding-bottom: 18px;
margin-top: 15px;
}
.note__text {
overflow: hidden;
max-height: 7rem;
-webkit-box-orient: vertical;
display: -webkit-box;
text-overflow: ellipsis;
-webkit-line-clamp: 4;
word-wrap: break-word;
padding: 0 20px 4px 20px;
}
h4 {
font-size: 25px;
}
p {
font-size: 20px;
}
.btn-view {
color: white;
background-color: rgb(24, 113, 197);
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-view:active {
transform: translateY(4px);
}
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
border-radius: 5px;
background-color: white;
padding: 6rem;
box-shadow: 0 3rem 5rem rgba(0 0 0 0.3);
z-index: 10;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(3px);
z-index: 5;
}
.hidden {
display: none;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 2rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
<!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>Note Taker App</title>
<link rel="stylesheet" href="style.css" />
<script src="script.js" defer></script>
</head>
<body>
<div class="container__app">
<h1>Note Taker</h1>
<h3>Add a new note:</h3>
<div class="input__field">
<form class="form">
<label class="input__text-name">Note: </label>
<textarea
rows="5"
cols=""
class="input__text"
placeholder="Write your note here"
></textarea>
<label for="submit"></label><br />
<button class="btn btn-green" type="submit">Add Note</button>
</form>
</div>
<div class="modal hidden">
<button class="close-modal">X</button>
</div>
<div class="overlay hidden"></div>
<div class="notes-container">
<!-- <div class="note">
<h4 class="note__heading">Note1</h4>
<p class="note__text">
MY note text
</p>
<div class="note__btn">
<button class="btn btn-view">View Detail</button>
</div>
</div> -->
</div>
</div>
</body>
</html>
Im new to programming, please help. I finished almost everything except last step. This is the problem: when I press button view more (it should create modal window related to that note and button). Thing is that everything is working fine when you press buttons in order (like note1, note2, note3), but if you press 6th button and then the first one, only last element will be created. If someone can explain me how this works. https://codepen.io/Niksani/pen/GROXGyN
const form = document.querySelector('.form');
const input = document.querySelector('.input__text');
let container = document.querySelector('.notes-container');
const button = document.querySelector('.btn');
const noteDiv = document.querySelector('.note');
let modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnClose = document.querySelectorAll('.close-modal');
const btnView = document.querySelector('.btn-view');
let noteCount = 0;
form.addEventListener('submit', function (e) {
e.preventDefault();
if (!input.value == '') {
and use to count number of note
if (button.click) noteCount++;
const divNotes = document.createElement('div');
divNotes.classList.add('note');
const createdNote = (divNotes.innerHTML += `
<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="btn btn-view">View Detail</button>
`);
container.appendChild(divNotes);
//
container.addEventListener('click', function (e) {
if (!e.target.classList.contains('btn-view')) {
return;
}
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
modal.innerHTML = `<h4 class="note__heading">Note ${noteCount}</h4>
<p class="note__text">${input.value}</p>
<button class="close-modal">X</button>
`;
});
modal.addEventListener('click', function (e) {
if (!e.target.classList.contains('close-modal')) {
return;
}
modal.classList.add('hidden');
overlay.classList.add('hidden');
});
}
});
'use strict';
// Select all elements needed for this task (querySelector)
const form = document.querySelector('.form');
const input = document.querySelector('.input__text');
let container = document.querySelector('.notes-container');
const button = document.querySelector('.btn');
const noteDiv = document.querySelector('.note');
let modal = document.querySelector('.modal');
const overlay = document.querySelector('.overlay');
const btnClose = document.querySelectorAll('.close-modal');
const btnView = document.querySelector('.btn-view');
let noteCount = 0;
// Create function that reads when the button is clicked on form
form.addEventListener('submit', function (e) {
e.preventDefault();
// if input filed is empty note will not be added!
if (!input.value == '') {
// Every time i click on button, notCount is incremented by one. Then that count i store and use to count number of note
if (button.click) noteCount++;
// Creating div element where notes will go
const divNotes = document.createElement('div');
// Adding class to that div element
divNotes.classList.add('note');
// Inserting HTML content into created div
const createdNote = (divNotes.innerHTML += `
<h4 class="note__heading">Note ${noteCount}</h4>
<p id='note${noteCount}' class="note__text">${input.value}</p>
<button class="btn btn-view" value='${noteCount}'>View Detail</button>
`);
container.appendChild(divNotes);
//
container.addEventListener('click', function (e) {
if (!e.target.classList.contains('btn-view')) {
return;
}
let showNote = '';
showNote = e.target.value;
let noteText = document.getElementById(`note${showNote}`).innerHTML;
modal.classList.remove('hidden');
overlay.classList.remove('hidden');
modal.innerHTML = `<h4 class="note__heading">Note ${showNote}</h4>
<p class="note__text">${noteText}</p>
<button class="close-modal">X</button>
`;
});
modal.addEventListener('click', function (e) {
if (!e.target.classList.contains('close-modal')) {
return;
}
modal.classList.add('hidden');
overlay.classList.add('hidden');
});
}
});
html {
margin: 0;
padding: 0;
font-family: 'Courier New', Courier, monospace;
box-sizing: border-box;
}
body {
display: grid;
place-items: center;
}
.container__app {
text-align: center;
}
h1 {
font-size: 4rem;
font-weight: 100;
}
h3 {
font-size: 2rem;
color: green;
margin-top: -40px;
}
.input__text {
width: 1310px;
height: 50px;
margin-bottom: 15px;
padding: 10px;
font-size: 16px;
resize: none;
}
label {
bottom: 36px;
padding: 3px;
vertical-align: top;
font-size: 25px;
font-weight: 600;
}
.btn-green {
color: white;
background-color: green;
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-span {
margin-top: 15px;
}
.btn-green:active {
transform: translateY(4px);
}
.notes-container {
margin: auto;
padding: 25px;
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
grid-gap: 1.5rem;
}
.note {
border: 1px solid gray;
padding-bottom: 18px;
margin-top: 15px;
}
.note__text {
overflow: hidden;
max-height: 7rem;
-webkit-box-orient: vertical;
display: -webkit-box;
text-overflow: ellipsis;
-webkit-line-clamp: 4;
word-wrap: break-word;
padding: 0 20px 4px 20px;
}
h4 {
font-size: 25px;
}
p {
font-size: 20px;
}
.btn-view {
color: white;
background-color: rgb(24, 113, 197);
width: 100px;
height: 35px;
border-radius: 5px;
border: none;
}
.btn-view:active {
transform: translateY(4px);
}
.modal {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 70%;
border-radius: 5px;
background-color: white;
padding: 6rem;
box-shadow: 0 3rem 5rem rgba(0 0 0 0.3);
z-index: 10;
}
.overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.6);
backdrop-filter: blur(3px);
z-index: 5;
}
.hidden {
display: none;
}
.close-modal {
position: absolute;
top: 1.2rem;
right: 2rem;
font-size: 2rem;
color: #333;
cursor: pointer;
border: none;
background: none;
}
<div class="container__app">
<h1>Note Taker</h1>
<h3>Add a new note:</h3>
<div class="input__field">
<form class="form">
<label class="input__text-name">Note: </label>
<textarea
rows="5"
cols=""
class="input__text"
placeholder="Write your note here"
></textarea>
<label for="submit"></label><br />
<button class="btn btn-green" type="submit">Add Note</button>
</form>
</div>
<div class="modal hidden">
<button class="close-modal">X</button>
</div>
<div class="overlay hidden"></div>
<div class="notes-container">
<!-- <div class="note">
<h4 class="note__heading">Note1</h4>
<p class="note__text">
MY note text
</p>
<div class="note__btn">
<button class="btn btn-view">View Detail</button>
</div>
</div> -->
</div>
</div>
check out the new event listener for your btn.click event...I am determining which note to show by getting the button value attribute that was added to the string literal....I am using that value to get the text of the note by giving the p an id and referencing that....I believe this gives you what you are looking for

Position a button next to a text in a created div

When I create an div I want to position my button to the right of the text. It works fine when i just put in some text like "PHP" but when write in a longer word like "Javascript" the button moves down so it is under the text. I have tried using float and display but it does not seem to work. Any ideas on how I can do this?
$(document).ready(() => {
//You can use IDs here because these elements are unique
const $addBtn = $("#läggatill");
const $inputBox = $("#myText");
const $flexBox = $("#flexbox");
$addBtn.click(() => {
//Creating a new box that contains everything we need and saving it to a variable
//I'm using ES6 template strings to embed the value of $inputBox
const $box = $(`
<div class="box">
<div class="newrect">
${$inputBox.val()}
<button class="hej">X</button></div>
<div class="dropdown">
<p class="text" id="text">Add description</p>
<textarea maxlength="255" class="autoExpand"></textarea>
</div>
</div>
`);
//Adding event listeneres for the box elements
$box.find(".hej").click(function () {
//Removing the parent .box wrapper DIV
$(this).closest(".box").remove();
});
$box.find(".newrect").click(() => {
const $dropdown = $box.find(".dropdown");
//If the dropdown is invisible, show it. Otherwise, hide it
if ($dropdown.css("display") === "none") {
$box.find(".dropdown").show();
} else {
$box.find(".dropdown").hide();
}
});
//Appending the box to the flexBox
$box.appendTo($flexBox);
});
});
// Expands all textareas with the class autoExpand
$(document)
.one('focus.autoExpand', 'textarea.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
/* Start of lägga till kompetens */
.newrect {
min-width: 105px;
max-width: 220px;
margin-top: 1%;
margin-right: 1%;
margin-left: 1%;
margin-bottom: 0%;
padding: 5px 10px 5px 10px;
border: 1px solid green;
border-radius: 40px;
text-align: center;
background-color: white;
z-index: 2;
cursor: pointer;
}
.flexbox{
display: flex;
flex-direction: row;
}
.box {
z-index: 1;
}
.skriv {
border-radius: 40px 40px 40px 40px;
outline: none;
padding: 0 2%;
width: 51%;
margin: 2%;
}
.läggatill {
border: 1px solid black;
background-color: white;
border-radius: 5px 5px 5px 5px;
outline: none;
margin: 2% 5%;
width: 23%;
max-width: 200px;
float: right;
}
.dropdown {
display: none;
background-color: darkgrey;
height: 400px;
margin-top: -20%;
margin-right: 0%;
margin-left: 1.5%;
margin-bottom: 0%;
z-index: -1;
padding-top: 10%;
width: 97%;
}
.dropdown textarea{
width: 90%;
}
.show {
display: block;
}
.hej {
position: relative;
border: none;
background-color: transparent;
color: darkblue;
}
.autoExpand {
margin-top: 0%;
margin-right: 0%;
margin-left: 5%;
margin-bottom: 0%;
z-index: 2;
display: block;
overflow: hidden;
padding: 10px;
font-size: 14px;
border-radius: 6px;
border: 0;
resize: none;
}
.text {
text-align: center;
margin-top: 30%;
cursor: default;
}
/* End of lägga till kompetens */
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/test.css"> <!-- Länk till CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <!-- Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Start of lägga till kompetenser function -->
<div class="col-md-12">
<div class="reform">
<input id="myText" maxlength="25" type="text" class="skriv" name="Kompetenser" autocomplete="off" autofocus> <!-- Textfield for kompetenser -->
<input id="läggatill" class="läggatill" type="button" value="Add box"> <!-- Button lägga till -->
</div>
</div>
<div class="flexbox" id="flexbox"></div> <!-- Container for the boxes -->
The issue is due to the max-width you set in CSS on .newrect causing the content to overflow. Similarly, the margin-left and margin-right encroached in to the content so .hej occasionally overflowed due to that too.
To fix this, remove max-width from .newrect (or make it much bigger) and use padding to set the horizontal gutters for the content within the .newrect instead:
.newrect {
min-width: 105px;
padding; 0 5px 0 15px;
/* other rules ... */
}
$(document).ready(() => {
//You can use IDs here because these elements are unique
const $addBtn = $("#läggatill");
const $inputBox = $("#myText");
const $flexBox = $("#flexbox");
$addBtn.click(() => {
//Creating a new box that contains everything we need and saving it to a variable
//I'm using ES6 template strings to embed the value of $inputBox
const $box = $(`
<div class="box">
<div class="newrect">
${$inputBox.val()}
<button class="hej">X</button></div>
<div class="dropdown">
<p class="text" id="text">Add description</p>
<textarea maxlength="255" class="autoExpand"></textarea>
</div>
</div>
`);
//Adding event listeneres for the box elements
$box.find(".hej").click(function() {
//Removing the parent .box wrapper DIV
$(this).closest(".box").remove();
});
$box.find(".newrect").click(() => {
const $dropdown = $box.find(".dropdown");
//If the dropdown is invisible, show it. Otherwise, hide it
if ($dropdown.css("display") === "none") {
$box.find(".dropdown").show();
} else {
$box.find(".dropdown").hide();
}
});
//Appending the box to the flexBox
$box.appendTo($flexBox);
});
});
// Expands all textareas with the class autoExpand
$(document)
.one('focus.autoExpand', 'textarea.autoExpand', function() {
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function() {
var minRows = this.getAttribute('data-min-rows') | 0,
rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
/* Start of lägga till kompetens */
.newrect {
min-width: 105px;
margin-top: 1%;
padding; 0 5px 0 15px;
margin-bottom: 0%;
padding: 5px 10px 5px 10px;
border: 1px solid green;
border-radius: 40px;
text-align: center;
background-color: white;
z-index: 2;
cursor: pointer;
}
.flexbox {
display: flex;
flex-direction: row;
}
.box {
z-index: 1;
}
.skriv {
border-radius: 40px 40px 40px 40px;
outline: none;
padding: 0 2%;
width: 51%;
margin: 2%;
}
.läggatill {
border: 1px solid black;
background-color: white;
border-radius: 5px 5px 5px 5px;
outline: none;
margin: 2% 5%;
width: 23%;
max-width: 200px;
float: right;
}
.dropdown {
display: none;
background-color: darkgrey;
height: 400px;
margin-top: -20%;
margin-right: 0%;
margin-left: 1.5%;
margin-bottom: 0%;
z-index: -1;
padding-top: 10%;
width: 97%;
}
.dropdown textarea {
width: 90%;
}
.show {
display: block;
}
.hej {
position: relative;
border: none;
background-color: transparent;
color: darkblue;
}
.autoExpand {
margin-top: 0%;
margin-right: 0%;
margin-left: 5%;
margin-bottom: 0%;
z-index: 2;
display: block;
overflow: hidden;
padding: 10px;
font-size: 14px;
border-radius: 6px;
border: 0;
resize: none;
}
.text {
text-align: center;
margin-top: 30%;
cursor: default;
}
/* End of lägga till kompetens */
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/test.css">
<!-- Länk till CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<!-- Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Start of lägga till kompetenser function -->
<div class="col-md-12">
<div class="reform">
<input id="myText" maxlength="25" type="text" class="skriv" name="Kompetenser" autocomplete="off" autofocus>
<!-- Textfield for kompetenser -->
<input id="läggatill" class="läggatill" type="button" value="Add box">
<!-- Button lägga till -->
</div>
</div>
<div class="flexbox" id="flexbox"></div>
<!-- Container for the boxes -->
I think it's gonna work for you
$(document).ready(() => {
//You can use IDs here because these elements are unique
const $addBtn = $("#läggatill");
const $inputBox = $("#myText");
const $flexBox = $("#flexbox");
$addBtn.click(() => {
//Creating a new box that contains everything we need and saving it to a variable
//I'm using ES6 template strings to embed the value of $inputBox
const $box = $(`
<div class="box">
<div class="newrect">
<span class="inputText">${$inputBox.val()}</span>
<button class="hej">X</button></div>
<div class="dropdown">
<p class="text" id="text">Add description</p>
<textarea maxlength="255" class="autoExpand"></textarea>
</div>
</div>
`);
//Adding event listeneres for the box elements
$box.find(".hej").click(function () {
//Removing the parent .box wrapper DIV
$(this).closest(".box").remove();
});
$box.find(".newrect").click(() => {
const $dropdown = $box.find(".dropdown");
//If the dropdown is invisible, show it. Otherwise, hide it
if ($dropdown.css("display") === "none") {
$box.find(".dropdown").show();
} else {
$box.find(".dropdown").hide();
}
});
//Appending the box to the flexBox
$box.appendTo($flexBox);
$inputBox.val('');
});
});
// Expands all textareas with the class autoExpand
$(document)
.one('focus.autoExpand', 'textarea.autoExpand', function(){
var savedValue = this.value;
this.value = '';
this.baseScrollHeight = this.scrollHeight;
this.value = savedValue;
})
.on('input.autoExpand', 'textarea.autoExpand', function(){
var minRows = this.getAttribute('data-min-rows')|0, rows;
this.rows = minRows;
rows = Math.ceil((this.scrollHeight - this.baseScrollHeight) / 16);
this.rows = minRows + rows;
});
.newrect {
/* min-width: 105px; */
/* max-width: 220px; */
margin-top: 1%;
margin-right: 1%;
margin-left: 1%;
margin-bottom: 0%;
padding: 5px 10px 5px 10px;
border: 1px solid green;
border-radius: 40px;
text-align: center;
background-color: white;
z-index: 2;
cursor: pointer;
display: inline-block;
text-overflow:ellipsis;
white-space:nowrap;
line-height: 100%;
}
.flexbox{
display: flex;
flex-direction: row;
}
.box {
z-index: 1;
}
.skriv {
border-radius: 40px 40px 40px 40px;
outline: none;
padding: 0 2%;
width: 51%;
margin: 2%;
}
.läggatill {
border: 1px solid black;
background-color: white;
border-radius: 5px 5px 5px 5px;
outline: none;
margin: 2% 5%;
width: 23%;
max-width: 200px;
float: right;
}
.dropdown {
display: none;
background-color: darkgrey;
height: 400px;
margin-top: -20%;
margin-right: 0%;
margin-left: 1.5%;
margin-bottom: 0%;
z-index: -1;
padding-top: 10%;
width: 97%;
}
.dropdown textarea{
width: 90%;
}
.show {
display: block;
}
.hej {
position: relative;
border: none;
background-color: transparent;
color: darkblue;
}
.autoExpand {
margin-top: 0%;
margin-right: 0%;
margin-left: 5%;
margin-bottom: 0%;
z-index: 2;
display: block;
overflow: hidden;
padding: 10px;
font-size: 14px;
border-radius: 6px;
border: 0;
resize: none;
}
.text {
text-align: center;
margin-top: 30%;
cursor: default;
}
/* End of lägga till kompetens */
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="css/test.css"> <!-- Länk till CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <!-- Bootstrap -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
</head>
<body>
<!-- Start of lägga till kompetenser function -->
<div class="col-md-12">
<div class="reform">
<input id="myText" maxlength="25" type="text" class="skriv" name="Kompetenser" autocomplete="off" autofocus> <!-- Textfield for kompetenser -->
<input id="läggatill" class="läggatill" type="button" value="Add box"> <!-- Button lägga till -->
</div>
</div>
<div class="flexbox" id="flexbox"></div> <!-- Container for the boxes -->
</body>
</html>

How to fit elements at slider container

I work with statick creation elements, and for this i need to have slider.
I just create slider, but elements are not fit in to slider container.
Example:
var htmlElements;
var userName = "Jonny Programmer"
var id = "6656"
function createUserCard() {
htmlElements = `<div class="user-card">
<img src="https://source.unsplash.com/user/erondu" class="userImage" />
<div class="info">
<div class="name">${userName}</div>
<div class="handle">
<div class="idPersone">${id}</div>
</div>
</div>
</div>`
$('.cardsCreation').append(htmlElements);
}
$('#plus-button').on('click', function () {
createUserCard();
});
(function () {
var sliderImages = document.querySelectorAll('.image'),
arrowLeft = document.querySelector('#left-arrow'),
arrowRight = document.querySelector('#right-arrow'),
currentImg = 0;
function initSlider() {
resetSlider();
sliderImages[0].style.display = 'block';
}
function resetSlider() {
for (var i = 0; i < sliderImages.length; i++) {
sliderImages[i].style.display = 'none';
}
}
function toLeft() {
resetSlider();
sliderImages[currentImg - 1].style.display = 'block';
currentImg--;
}
function toRight() {
resetSlider();
sliderImages[currentImg + 1].style.display = 'block';
currentImg++;
}
arrowLeft.addEventListener('click', function () {
if (currentImg === 0) {
currentImg = sliderImages.length;
}
toLeft();
});
arrowRight.addEventListener('click', function () {
if (currentImg === sliderImages.length - 1) {
currentImg = -1;
}
toRight();
});
initSlider();
})();
.user-card, userImage {
box-shadow: 0px 2px 5px 0 rgba(0,0,0,0.25);
}
.user-card {
margin: 12px;
padding: 10px 10px 10px 10px;
border-radius: 12px;
width: 160px;
text-align: center;
float: left;
background-color: #fff;
}
.userImage {
border-radius: 50%;
height: 140px;
width: 140px;
border: 5px solid #eee;
}
.name {
font-size: 20px;
margin: 5px;
font-weight: bold;
}
.progress {
color: #25af53;
font-size: 48px;
}
#plus-button {
width: 55px;
height: 55px;
border-radius: 50%;
background: #428bca;
position: absolute;
top: 33%;
margin-left: 20px;
cursor: pointer;
box-shadow: 0px 2px 5px #666;
border: none;
outline: none;
}
.plus {
color: white;
position: absolute;
top: 0;
display: block;
bottom: 0;
left: 0;
right: 0;
text-align: center;
padding: 0;
margin: 0;
line-height: 55px;
font-size: 38px;
font-family: 'Roboto';
font-weight: 300;
}
#plus-button:hover {
box-shadow: 0 6px 14px 0 #666;
transform: scale(1.05);
}
.wrapper {
position: relative;
}
.arrow {
cursor: pointer;
position: absolute;
width: 0;
height: 0;
border-style: solid;
top: 50%;
margin-top: 160px;
}
#left-arrow {
border-width: 50px 40px 50px 0;
border-color: transparent #000 transparent transparent;
left: 0;
margin-left: 25px;
}
#right-arrow {
border-width: 50px 0 50px 40px;
border-color: transparent transparent transparent #000;
right: 0;
margin-right: 25px;
}
.image {
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.vertical-align-wrapper {
display: table;
overflow: hidden;
text-align: center;
}
.vertical-align-wrapper span {
display: table-cell;
vertical-align: middle;
font-size: 5rem;
color: #ffffff;
}
#media only screen and (max-width : 992px) {
.vertical-align-wrapper span {
font-size: 2.5rem;
}
#left-arrow {
border-width: 30px 20px 30px 0;
margin-left: 15px;
}
#right-arrow {
border-width: 30px 0 30px 20px;
margin-right: 15px;
}
.arrow {
margin-top: -30px;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<div id="left-arrow" class="arrow"></div>
<div id="slider">
<div class="image image-one">
<div class="vertical-align-wrapper">
<div class="cardsCreation"></div>
<button id="plus-button">
<p class="plus">+</p>
</button>
</div>
</div>
<div class="image image-two">
<div class="vertical-align-wrapper">
<span>Slide 2</span>
</div>
</div>
<div class="image image-three">
<div class="vertical-align-wrapper">
<span>Slide 3</span>
</div>
</div>
</div>
<div id="right-arrow" class="arrow"></div>
</div>
So as u can see affter tapping "+" i add new ellement in to html.
And from two sides i have arrows which are changing slider.
After tapping arrows go down, and this is not good.
And after i will reach limit of adding element in one slider it's add new element to new slider page.
What i want ex:
If you are using toggle of display CSS property that happened because it remove whole element from the DOM so, I suggest you to use visibility or opacity properties to done your task.

Javascript - I can not sum the inputs in the cloned divs

I'm a level 0 newbie, and I'm cloning some divs (here the script works very well), to which I added some inputs with different values, and what I'm looking for is to be able to sum the values ​​(only of the cloned inputs), but the script does not he reads. Only sum ALL the html inputs.
// Script for clone the div´s
$(document).ready(function() {
$("#comp-p1").click(function() {
$("#cont-p1").clone().appendTo(".derecha");
});
// =============
$("#comp-p2").click(function() {
$("#cont-p2").clone().appendTo(".derecha");
});
// =============
$("#comp-p3").click(function() {
$("#cont-p3").clone().appendTo(".derecha");
});
});
// =============================================================
// New Script for sum inputs
const suma = function() {
var x = document.getElementsByClassName("add-prod");
let sum = 0;
for (var i = 0; i < x.length; i++) {
console.log(x[i].value)
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
}
//console.log(suma());
document.getElementById("total").value = suma();
// =============================================================
// Old Script for sum inputs
/*$(document).ready(function() {
function sumInputs(e) {
e.preventDefault();
var valores = $('.derecha').children('input');
var suma = 0;
$.each(valores, function() {
valor = $(this).val();
suma += Number(valor);
});
valores = document.getElementById('total');
$(valores).val(suma);
}
$('#sumup').on('click', sumInputs);
});*/
body {
margin: 0 auto;
color: #323232;
width: 100%;
height: 100%;
line-height: 1.5;
font-family: 'Roboto', serif
}
#container {
width: 500px;
margin: 0 auto
}
#container p {
display: inline-block;
margin-top: 20px
}
span {
font-weight: bold;
text-decoration: underline
}
#productos {
display: none
}
.img-prod {
display: inline-block;
float: left;
background: #000;
margin-right: 10px
}
.img-prod img {
width: 100%;
height: auto;
max-width: 70px;
display: block;
border: 0
}
#comp-p1,
#comp-p2,
#comp-p3 {
width: 120px;
height: 30px;
margin-top: 15px;
background: green;
padding: 10px 0 5px;
text-align: center;
vertical-align: middle;
color: #fff;
cursor: pointer
}
.derecha {
border: solid 1px #999;
max-height: 400px;
width: 350px;
margin: 0 auto;
text-align: center;
padding: 10px 0;
overflow-y: auto;
float: right
}
#producto-1,
#producto-2,
#producto-3 {
display: inline-block;
width: 220px;
padding: 10px;
float: left;
text-align: left;
font-size: .9em;
margin-right: 5px
}
#producto-1 {
background: green;
color: #fff
}
#producto-2 {
background: #add8e6;
color: #000
}
#producto-3 {
background: #666;
color: #fff
}
.cont-p {
display: inline-block;
margin: 7px auto;
line-height: 1
}
.bbp {
display: inline-block;
float: right;
width: 24px;
height: 24px;
text-align: center;
background: red;
color: #fff;
margin-left: 5px;
line-height: 1.5;
cursor: pointer
}
.cont-num {
float: left;
width: 24px;
height: 24px;
margin: 20px 5px 0 18px;
padding: 4px 3px 3px;
background: red;
text-align: center;
font-size: 16px;
font-family: Arial, sans-serif;
color: #fff
}
#mostrar {
display: none
}
#mostrar {
width: 100px;
margin: 70px 0 0;
padding: 10px;
text-align: center;
background: grey;
color: #fff;
cursor: pointer
}
/* ==== Style of Sume ==== */
.derecha input {
width: 40px;
display: block;
margin: 0 auto 10px 0;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 110px;
margin-top: 70px;
background: grey;
padding: 5px 10px 10px;
color: #fff
}
#cont-resultado input {
display: inline-block;
margin: 10px auto;
background: #fff;
color: #000;
border: 1px solid #000;
padding: 8px 0
}
#cont-resultado p {
display: inline-block;
text-decoration: none;
color: #fff;
background: grey;
padding: 8px 10px;
cursor: pointer
}
#total {
display: block;
width: 80px;
text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="productos">
<!-- =============== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"> </div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp" onclick="restar();restardos();this.parentNode.parentNode.removeChild(this.parentNode);">X</div>
</div>
<!-- =============== -->
<div id="cont-p2" class="cont-p">
<div id="producto-2">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p2 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp" onclick="restar();restardos();this.parentNode.parentNode.removeChild(this.parentNode);">X</div>
</div>
<!-- =============== -->
<div id="cont-p3" class="cont-p">
<div id="producto-3">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p3 cloned!<br><br>Input Value = 198</div>
<input class="add-prod" type="num" value="198">
<div class="bbp" onclick="restar();restardos();this.parentNode.parentNode.removeChild(this.parentNode);">X</div>
</div>
<!-- =============== -->
</div>
<!-- // productos -->
<div class="derecha"></div>
<div id="comp-p1" onClick="clickME();clickME2();">Clone 1</div>
<div id="comp-p2" onClick="clickME();clickME2();">Clone 2</div>
<div id="comp-p3" onClick="clickME();clickME2();">Clone 3</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<span>RESULT:</span><br>
<input name="total" id="total">
<br>Is the sum of the cloned divs
<!--<p id='sumup'>Ver total</p>-->
</div>
<p><span>NOTE:</span><br>Here we are looking for only the cloned inputs can be sumed (and see the result in the box color gray).<br><br>The problem is that the current script does not apply a sume of the cloned inputs only... it adds ALL the inputs presents
in the html...<br><br>So (1), how do you sum only the cloned inputs, ignoring those that are outside...?<br><br>And (2) also, how to subtract from the total result all the cloned divs that are deleted...?</p>
</div>
<!-- // container -->
<script>
// Script that adds and subtracts the clicks
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks
}
var clicksdos = 0;
function clickME2() {
clicksdos += 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 1) {
document.getElementById("cont-resultado").style.display = "block";
}
}
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
function restar() {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
function restardos() {
if (clicksdos > 0) clicksdos -= 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
}
</script>
Ok, you need a couple of changes.
First of you need to run a query selector and get only the elements inside the destination.
const suma = function () {
// NOTE: The query selector is very specific
let x = Array.from(document.querySelectorAll(".derecha div .add-prod"));
console.log(x);
let sum = 0;
for (var i = 0; i < x.length; i++) {
console.log(x[i].value)
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
}
Next you will need to call you SUM method each time you add an item:
$(document).ready(function () {
$("#comp-p1").click(function () {
$("#cont-p1").clone().appendTo(".derecha");
document.getElementById("total").value = suma();
});
// =============
$("#comp-p2").click(function () {
$("#cont-p2").clone().appendTo(".derecha");
document.getElementById("total").value = suma();
});
// =============
$("#comp-p3").click(function () {
$("#cont-p3").clone().appendTo(".derecha");
document.getElementById("total").value = suma();
});
});
Here it is working:
Added code to deal with the removal of elements also.
// Script for clone the div´s
$(document).ready(function() {
$("#comp-p1").click(function() {
$("#cont-p1").clone().appendTo(".derecha");
displaySuma();
});
// =============
$("#comp-p2").click(function() {
$("#cont-p2").clone().appendTo(".derecha");
displaySuma();
});
// =============
$("#comp-p3").click(function() {
$("#cont-p3").clone().appendTo(".derecha");
displaySuma();
});
});
const getParent = (match, node) => (node.matches(match)) ? node : getParent(match, node.parentNode);
// Deal with remove
document.addEventListener('click', (event) => {
let target = event.target;
if (target.matches('.bbp')) {
restar();
restardos();
getParent('.derecha', target).removeChild(target.parentNode);
displaySuma();
}
})
// New Script for sum inputs
const displaySuma = () => document.getElementById("total").value = suma();
const suma = function() {
let x = Array.from(document.querySelectorAll(".derecha div .add-prod"));
let sum = 0;
for (var i = 0; i < x.length; i++) {
sum += parseFloat(x[i].value);
}
console.log(sum);
return sum;
}
//console.log(suma());
document.getElementById("total").value = suma();
body {
margin: 0 auto;
color: #323232;
width: 100%;
height: 100%;
line-height: 1.5;
font-family: 'Roboto', serif
}
#container {
width: 500px;
margin: 0 auto
}
#container p {
display: inline-block;
margin-top: 20px
}
span {
font-weight: bold;
text-decoration: underline
}
#productos {
display: none
}
.img-prod {
display: inline-block;
float: left;
background: #000;
margin-right: 10px
}
.img-prod img {
width: 100%;
height: auto;
max-width: 70px;
display: block;
border: 0
}
#comp-p1,
#comp-p2,
#comp-p3 {
width: 120px;
height: 30px;
margin-top: 15px;
background: green;
padding: 10px 0 5px;
text-align: center;
vertical-align: middle;
color: #fff;
cursor: pointer
}
.derecha {
border: solid 1px #999;
max-height: 400px;
width: 350px;
margin: 0 auto;
text-align: center;
padding: 10px 0;
overflow-y: auto;
float: right
}
#producto-1,
#producto-2,
#producto-3 {
display: inline-block;
width: 220px;
padding: 10px;
float: left;
text-align: left;
font-size: .9em;
margin-right: 5px
}
#producto-1 {
background: green;
color: #fff
}
#producto-2 {
background: #add8e6;
color: #000
}
#producto-3 {
background: #666;
color: #fff
}
.cont-p {
display: inline-block;
margin: 7px auto;
line-height: 1
}
.bbp {
display: inline-block;
float: right;
width: 24px;
height: 24px;
text-align: center;
background: red;
color: #fff;
margin-left: 5px;
line-height: 1.5;
cursor: pointer
}
.cont-num {
float: left;
width: 24px;
height: 24px;
margin: 20px 5px 0 18px;
padding: 4px 3px 3px;
background: red;
text-align: center;
font-size: 16px;
font-family: Arial, sans-serif;
color: #fff
}
#mostrar {
display: none
}
#mostrar {
width: 100px;
margin: 70px 0 0;
padding: 10px;
text-align: center;
background: grey;
color: #fff;
cursor: pointer
}
/* ==== Style of Sume ==== */
.derecha input {
width: 40px;
display: block;
margin: 0 auto 10px 0;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 110px;
margin-top: 70px;
background: grey;
padding: 5px 10px 10px;
color: #fff
}
#cont-resultado input {
display: inline-block;
margin: 10px auto;
background: #fff;
color: #000;
border: 1px solid #000;
padding: 8px 0
}
#cont-resultado p {
display: inline-block;
text-decoration: none;
color: #fff;
background: grey;
padding: 8px 10px;
cursor: pointer
}
#total {
display: block;
width: 80px;
text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="productos">
<!-- =============== -->
<div id="cont-p1" class="cont-p">
<div id="producto-1">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"> </div>cont-p1 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- =============== -->
<div id="cont-p2" class="cont-p">
<div id="producto-2">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p2 cloned!<br><br>Input Value = 1</div>
<input class="add-prod" type="num" value="1">
<div class="bbp">X</div>
</div>
<!-- =============== -->
<div id="cont-p3" class="cont-p">
<div id="producto-3">
<div class="img-prod"><img src="https://upload.wikimedia.org/wikipedia/commons/3/39/Lichtenstein_img_processing_test.png"></div>
cont-p3 cloned!<br><br>Input Value = 198</div>
<input class="add-prod" type="num" value="198">
<div class="bbp">X</div>
</div>
<!-- =============== -->
</div>
<!-- // productos -->
<div class="derecha"></div>
<div id="comp-p1" onClick="clickME();clickME2();">Clone 1</div>
<div id="comp-p2" onClick="clickME();clickME2();">Clone 2</div>
<div id="comp-p3" onClick="clickME();clickME2();">Clone 3</div>
<div class="cont-num" id="clicks">0</div>
<div class="cont-num" id="clicksdos">0</div>
<div id="cont-resultado">
<span>RESULT:</span><br>
<input name="total" id="total">
<br>Is the sum of the cloned divs
<!--<p id='sumup'>Ver total</p>-->
</div>
<p><span>NOTE:</span><br>Here we are looking for only the cloned inputs can be sumed (and see the result in the box color gray).<br><br>The problem is that the current script does not apply a sume of the cloned inputs only... it adds ALL the inputs presents
in the html...<br><br>So (1), how do you sum only the cloned inputs, ignoring those that are outside...?<br><br>And (2) also, how to subtract from the total result all the cloned divs that are deleted...?</p>
</div>
<!-- // container -->
<script>
// Script that adds and subtracts the clicks
var clicks = 0;
function clickME() {
clicks += 1;
document.getElementById("clicks").innerHTML = clicks
}
var clicksdos = 0;
function clickME2() {
clicksdos += 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 1) {
document.getElementById("cont-resultado").style.display = "block";
}
}
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
function restar() {
if (clicks > 0) clicks -= 1;
document.getElementById("clicks").innerHTML = clicks;
}
function restardos() {
if (clicksdos > 0) clicksdos -= 1;
document.getElementById("clicksdos").innerHTML = clicksdos;
if (clicksdos === 0) {
document.getElementById("cont-resultado").style.display = "none";
}
}
</script>

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