My Js creates a div("log-entry") with a table(contents are input values) after each form submit.
My problem is that all the created tables have a identical ID, if I try to export these tables with SheetJs only the first created table gets exported but i want the whole "log"/all tables exported to the same sheet.
I tried to wrap the table around my log but couldn't manage to make it work that way.
HTML Site
The SheetJS snippet is all the way at the bottom
<!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" />
<base target="_top" />
<title>-</title>
<link rel="stylesheet" href="https://static.staticsave.com/lottie/stylesheet.css">
<!-- jQuery & Decimal Input Plugin -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.mask/1.14.16/jquery.mask.min.js" integrity="sha512-pHVGpX7F/27yZ0ISY+VVjyULApbDlD0/X0rgGbTqCE7WFW5MezNTWG/dnhtbBuICzsd0WQPgpE4REBLv+UqChw==" crossorigin="anonymous"></script>
<!-- SheetJS Library -->
<script type="text/javascript" src="https://unpkg.com/xlsx#0.15.1/dist/xlsx.full.min.js"></script>
</head>
<body>
<div class="logo-text-wrapper">
<p>
<img
src="https://scontent-muc2-1.xx.fbcdn.net/v/t39.30808-1/277464704_400510965219536_7135106775534792654_n.jpg?stp=dst-jpg_p148x148&_nc_cat=101&ccb=1-7&_nc_sid=1eb0c7&_nc_ohc=ACTsME9JaDsAX-R7bsd&_nc_ht=scontent-muc2-1.xx&oh=00_AT-Rz2SmBYtbhy06EjZdzLe7w9duM8mIp8W0mRYX7fvwzQ&oe=6344B0CB"
alt="logo"
width="40px"
height="auto"
/>
<span id="title">PCR-Rechner</span>
</p>
<div class="actionBtns">
<button class="actionBtn calcBtn">PCR-Rechner</button>
<button class="actionBtn egensBtn">EGENS-Tool</button>
<button class="moveBtn">PCR-Rechner</button>
</div>
</div>
<main>
<form class="calc-form-wrapper" id="calc-form">
<div class="inputblock-wrapper-ID">
<label class="inputlabel" for="ID">Probenummer</label>
<input
type="number"
name="ID"
id="ID"
class="inputfield"
step="0.01"
maxlength="8"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
placeholder="Probenummer eingeben..."
onkeydown="return event.keyCode !== 69"
disabled
required
/>
<div class="inputcheckboxwrapper">
<label class="toggler-wrapper formstyle" id="toggler-wrapper">
<input type="checkbox" id="checkbox" />
<div class="toggler-slider">
<div class="toggler-knob"></div>
</div>
</label>
<label class="inputcheckboxlabel" for="checkbox"
>Mit Probennummer verwenden.</label
>
</div>
</div>
<div class="calculator">
<div class="inputblock-wrapper">
<label class="inputlabel" for="ct1"
><span id="FAM-label">FAM</span> Wert</label
>
<input
type="number"
name="ct1"
id="ct1"
class="inputfield"
step="0.01"
maxlength="5"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
onkeydown="return event.keyCode !== 69"
required
/>
</div>
<div class="inputblock-wrapper">
<label class="inputlabel" for="ct2"
><span id="CY5-label">CY5</span> Wert</label
>
<input
type="number"
name="ct2"
id="ct2"
class="inputfield"
step="0.01"
maxlength="5"
oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
onkeydown="return event.keyCode !== 69"
required
/>
</div>
</div>
<div class="result-wrapper">
<label class="result-label">CT <span>=</span></label>
<div class="result-wrapper inner">
<input class="inputfield result" id="result" name="result" tabindex="-1" />
<div class="copy-button tooltip" id="copy-button">
<svg
version="1.1"
width="18"
height="18"
viewBox="0 0 64 64"
xml:space="preserve"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="m53.979 9.1429h-3.9683c-0.082699 0-0.1562 0.0284-0.2331 0.047v-4.1671c0-2.7698-2.3046-5.0228-5.1379-5.0228h-34.423c-2.8333 0-5.1379 2.253-5.1379 5.0228v46.843c0 2.7698 2.3046 5.0228 5.1379 5.0228h6.0367v2.2679c0 2.6706 2.2163 4.8432 4.9415 4.8432h32.784c2.7252 0 4.9415-2.1726 4.9415-4.8432v-45.171c-1.8e-6 -2.6706-2.2163-4.8432-4.9415-4.8432zm-46.868 42.723v-46.843c0-1.6488 1.3939-2.991 3.1062-2.991h34.423c1.7123 0 3.1062 1.3422 3.1062 2.991v46.843c0 1.6488-1.3939 2.9911-3.1062 2.9911h-34.423c-1.7123 4e-7 -3.1062-1.3423-3.1062-2.9911zm49.778 7.2907c0 1.5506-1.3055 2.8115-2.9097 2.8115h-32.784c-1.6042 0-2.9098-1.2609-2.9098-2.8115v-2.2679h26.354c2.8333 0 5.1379-2.253 5.1379-5.0228v-40.739c0.0769 0.0186 0.1504 0.047 0.2331 0.047h3.9683c1.6042 0 2.9097 1.2609 2.9097 2.8115v45.171z"
/>
<path
d="m38.603 13.206h-22.349c-0.5615 0-1.0159 0.4543-1.0159 1.0158 0 0.5616 0.4544 1.0159 1.0159 1.0159h22.349c0.5615 0 1.0159-0.4543 1.0159-1.0159 0-0.5615-0.4544-1.0158-1.0159-1.0158z"
/>
<path
d="m38.603 21.333h-22.349c-0.5615 0-1.0159 0.4543-1.0159 1.0158 0 0.5615 0.4544 1.0159 1.0159 1.0159h22.349c0.5615 0 1.0159-0.4544 1.0159-1.0159 0-0.5615-0.4544-1.0158-1.0159-1.0158z"
/>
<path
d="m38.603 29.46h-22.349c-0.5615 0-1.0159 0.4544-1.0159 1.0159s0.4544 1.0159 1.0159 1.0159h22.349c0.5615 0 1.0159-0.4544 1.0159-1.0159s-0.4544-1.0159-1.0159-1.0159z"
/>
<path
d="m28.444 37.587h-12.19c-0.5615 0-1.0159 0.4544-1.0159 1.0159s0.4544 1.0159 1.0159 1.0159h12.19c0.5615 0 1.0158-0.4544 1.0158-1.0159s-0.4543-1.0159-1.0158-1.0159z"
/>
</svg>
<div class="top">
<p id="tooltip-content">Ergebniss kopieren.</p>
<i></i>
</div>
</div>
</div>
</div>
<button
type="submit"
class="submit-button"
id="calcbutton"
onclick="this.blur();"
>
CT Berechnen
</button>
<button onclick="ExportToExcel()">Test export</button>
</form>
<div class="log-scroll-wrapper">
<div class="log-wrapper" id="log-wrapper">
<!-- Log entries are displayed here -->
<!-- <div class="log-entry">
<table class="log-entry-table">
<thead>
<tr class="log-entry-table-tr">
<td><span>99</span>.</td>
<td>ID<span>:</span> <span>30715407</span></td>
<td>CT<span>:</span> <span>34.3444</span></td>
<td>Zeit<span>:</span> <span>20:20:20</span></td>
</tr>
</thead>
</table>
</div> -->
</div>
</div>
</main>
<script>
const ct1 = document.getElementById("ct1");
const ct2 = document.getElementById("ct2");
const calcBtn = document.querySelector(".calcBtn");
const egensBtn = document.querySelector(".egensBtn");
const moveBtn = document.querySelector(".moveBtn");
const copyBtn = document.querySelector("#copy-button");
const result = document.querySelector("#result");
const calcForm = document.querySelector("#calc-form");
const idinput = document.getElementById("ID");
const logWrapper = document.getElementById("log-wrapper");
const title = document.getElementById("title");
const uploadForm = document.getElementById("upload-form");
let logcounter = 0;
setListeners();
function handleCalcForm(event) {
event.preventDefault();
const h =
(new Date().getHours() < 10 ? "0" : "") + new Date().getHours();
const m =
(new Date().getMinutes() < 10 ? "0" : "") + new Date().getMinutes();
const s =
(new Date().getSeconds() < 10 ? "0" : "") + new Date().getSeconds();
const timestamp = h + ":" + m + ":" + s;
const ct1val = ct1.value;
const ct2val = ct2.value;
const addition = +ct1val + +ct2val;
const division = addition / 2;
const idval = idinput.value;
logcounter += 1;
result.value = division;
ct1.value = ""
ct2.value = ""
const logEntry = document.createElement("div");
logEntry.classList.add("log-entry");
logEntry.innerHTML = `
<table class="log-entry-table" id="log-entry-table">
<thead>
<tr class="log-entry-table-tr">
<td><span>${logcounter}</span>.</td>
<td>ID<span>:</span> <span>${idval ? idval : "-"}</span></td>
<td>CT<span>:</span> <span>${division}</span></td>
<td>Zeit<span>:</span> <span>${timestamp}</span></td>
</tr>
</thead>
</table>
`;
logWrapper.appendChild(logEntry);
}
function setListeners() {
$("#upload-button").on("click", function ( ){
alert("Entschuldige, dieses Tool befindet sich noch in der Entwicklung :/")
});
$(document).ready(function () {
$(ct1).mask('00.00', { reverse: true });
$(ct2).mask('00.00', { reverse: true });
});
$(function () {
$("#checkbox").on("click", function () {
$("#ID").attr("disabled", !$(this).is(":checked"));
$("#ID").val([], !$(this).is(":checked"));
});
});
calcForm.addEventListener("submit", (event) => {
handleCalcForm(event);
});
copyBtn.addEventListener("click", (event) => {
event.preventDefault();
result.select();
result.setSelectionRange(0, 99999);
navigator.clipboard.writeText(result.value);
document.getElementById("tooltip-content").innerText = "Kopiert!";
});
result.addEventListener("focusout", (event) => {
document.getElementById("tooltip-content").innerText =
"Ergebniss kopieren.";
});
egensBtn.addEventListener("click", () => {
moveBtn.classList.add("rightBtn");
title.innerText = "EGENS-Tool";
calcForm.style.display = "none";
logWrapper.style.display = "none";
uploadForm.style.display = "flex";
moveBtn.innerText = "EGENS-Tool";
});
calcBtn.addEventListener("click", () => {
moveBtn.classList.remove("rightBtn");
title.innerText = "PCR-Rechner";
calcForm.style.display = "flex";
logWrapper.style.display = "flex";
uploadForm.style.display = "none";
moveBtn.innerText = "PCR-Rechner";
});
}
//File input
var inputs = document.querySelectorAll('.file-input')
for (var i = 0, len = inputs.length; i < len; i++) {
customInput(inputs[i])
}
function customInput (el) {
const fileInput = el.querySelector('[type="file"]')
const label = el.querySelector('[data-js-label]')
fileInput.onchange =
fileInput.onmouseout = function () {
if (!fileInput.value) return
var value = fileInput.value.replace(/^.*[\\\/]/, '')
el.className += ' -chosen'
label.innerText = value
}
}
//Start Dropdown
// function getSelectedValue(id) {
// return $("#" + id).find("dt a span.value").html();
// }
// $("button").click(function(e){
// var val = getSelectedValue('locations');
// alert(val);
// });
$(".dropdown dt a").click(function(e) {
$(".dropdown dd ul").toggle();
e.preventDefault();
});
$(".dropdown dd ul li a").click(function() {
var text = $(this).html();
$(".dropdown dt a span").html(text);
$(".dropdown dd ul").hide();
});
$(document).bind('click', function(e) {
var $clicked = $(e.target);
if (! $clicked.parents().hasClass("dropdown"))
$(".dropdown dd ul").hide();
});
//End Dropdown
// $(function() {
// tmpval = $('#result').val();
// if(tmpval == '') {
// $('#copy-button').addClass('button-disabled');
// } else if(tmpval != "") {
// $('#copy-button').removeClass('button-disabled');
// }
// });
///SheetJS export
function ExportToExcel(type, fn, dl) {
var elt = document.getElementById('log-entry-table');
var wb = XLSX.utils.table_to_book(elt, { sheet: "Logs" });
return dl ?
XLSX.write(wb, { bookType: type, bookSST: true, type: 'base64' }):
XLSX.writeFile(wb, fn || ('Log Test.' + (type || 'xlsx')));
}
</script>
</body>
</html>
Related
I have an html form with item and amount entries and I want the values in them to be stored in local storage and xampp, I have succeeded in submiting to localstorage however the form submits nothing in xampp in a column for item and 0 in the column of amount
here is my html file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title>ICT specialists</title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="app.css" />
<link rel="shortcut icon" href="ICT_Logo-01.png">
</head>
<body>
<h2>Daily transactions at ICT specialists</h2>
<div class="container">
<h4>Your balance</h4>
<h1 id="balance"></h1>
<div class="inc-exp-container">
<div>
<h4>income</h4>
<p id="money-plus" class="money plus"></p>
</div>
<div>
<h4>expense</h4>
<p id="money-minus" class="money minus"></p>
</div>
</div>
<h3>History</h3>
<div class="shows">
<ion-icon name="menu-outline" id="showLi"></ion-icon>
<ion-icon name="close-outline" id="hideLi"></ion-icon>
</div>
<ul id="list" class="list"></ul>
<h3>add new transation</h3>
<form action="sales.php" method="post" id="form">
<div class="form-control">
<label for="">date</label>
<input type="text" id="date" name="date">
</div>
<div class="form-control">
<label for="text">item</label>
<input type="text" id="text" name="item" placeholder="please enter the item..." autocomplete="off" />
</div>
<div class="form-control">
<label for="amount">amount <br />(negative=expense, positive=income)</label>
<input type="number" id="amount" name="amount" placeholder="please enter the amount..." autocomplete="off" />
</div>
<button class="btn" type="submit">Add transation</button>
</form>
</div>
<div class="footer">
<div class="footerTxt">copyright © <span id="dated">2022</span</div>
<div class="footerRyt">
ict specialists | sydotech
</div>
</div>
<style>
.footer{
display: flex;
justify-content: space-evenly;
width: 100%;
bottom: 0;
background: deepskyblue !important;
padding: 10px;
position: fixed;
}
.footer .footerTxt{
font-size: 1.2rem;
text-transform: capitalize;
font-weight: 500;
}
.footer .footerRyt a{
text-decoration: none;
font-size: 1.4rem;
color: #fff !important;
}
</style>
<ion-icon name="arrow-up-outline" id="icons"></ion-icon>
<script src="sales.js"></script>
<script type="module" src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.esm.js">
</script>
<script nomodule src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.js"></script>
</body>
</html>
here is my php
<?php
$pdo = new PDO('mysql:host=localhost;port=3306;dbname=sales','root','');
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
if($_SERVER['REQUEST_METHOD']==='POST'){
$item = $_POST['item'];
$amount = $_POST['amount'];
$statement = $pdo->prepare("insert into transaction
(item,amount)
values (:item,:amount)");
$statement->bindValue(':item', $item );
$statement->bindValue(':amount', $amount );
$statement->execute();
header('Location: sales.html');
}
here is my javascript file
const balance = document.getElementById("balance");
const money_plus = document.getElementById("money-plus");
const list = document.getElementById("list");
const form = document.getElementById("form");
const text = document.getElementById("text");
const amount = document.getElementById("amount");
const money_minus = document.getElementById("money-minus");
let showLi = document.getElementById("showLi");
let hideLi = document.getElementById('hideLi');
const localStorageTransations = JSON.parse(localStorage.getItem("transations"));
let transations =
localStorage.getItem("transations") !== null ? localStorageTransations : [];
//add transation
function addTransation() {
// e.preventDefault();
if (text.value.trim() === "" || amount.value.trim() === "") {
text.placeholder = "PLEASE SOME TEXT";
text.style.backgroundColor = "#ccc";
text.style.fontWeight = 'bold';
amount.placeholder = "ENTER AMOUNT";
amount.style.backgroundColor = "#ccc";
amount.style.fontWeight = 'bold';
} else {
const transation = {
id: genenrateID(),
text: text.value,
amount: +amount.value,
};
transations.push(transation);
addTransationDOM(transation);
updateValues();
updateLocalStorage();
text.value = "";
amount.value = "";
}
}
//generate id
function genenrateID() {
return Math.floor(Math.random() * 100000000);
}
//add transations to dom list
function addTransationDOM(transation) {
//get sign
const sign = transation.amount < 0 ? "-" : "+";
const item = document.createElement("li");
//add class based on value
item.classList.add(transation.amount < 0 ? "minus" : "plus");
item.innerHTML = `${transation.text} <span>${sign}${Math.abs(transation.amount)}</span>
<button class="delete-btn" onclick="removeTransation(${transation.id})">x</button>`;
list.appendChild(item);
item.style.display="none";
hideLi.addEventListener('click',()=>{
item.style.display = 'none';
hideLi.style.display = "none";
showLi.style.display = "block";
});
showLi.addEventListener('click',()=>{
item.style.display = 'block';
hideLi.style.display = "block";
showLi.style.display = "none";
})
}
// ********hide list******
// ********hide list end******
//update the balance
function updateValues() {
const amounts = transations.map((transation) => transation.amount);
const total = amounts.reduce((acc, item) => (acc += item), 0).toFixed(0);
const income = amounts
.filter((item) => item > 0)
.reduce((acc, item) => (acc += item), 0)
.toFixed(0);
const expense = (
amounts.filter((item) => item < 0).reduce((acc, item) => (acc += item), 0) * -1).toFixed(0);
balance.innerText = `UgShs: ${total}`;
money_plus.innerText = `UgShs: ${income}`;
money_minus.innerText = `UgShs: ${expense}`;
}
//remove
function removeTransation(id) {
transations = transations.filter((transation) => transation.id !== id);
updateLocalStorage();
init();
}
//updatelocal storage
function updateLocalStorage() {
localStorage.setItem("transations", JSON.stringify(transations));
}
function init() {
list.innerHTML = "";
transations.forEach(addTransationDOM);
updateValues();
}
init();
form.addEventListener("submit", addTransation);
// *********date calculation********
let date =document.getElementById('date');
date.value = new Date().toDateString();
// *********ionicons*******88
let icon = document.getElementById('icons');
window.onscroll = ()=>{
if(window.scrollY >=100){
icon.style.display = 'block';
icon.style.position = 'fixed';
}else{
icon.style.display = 'none';
}
}
icon.addEventListener('click',()=>{
window.scrollTo({top:0, behavior:"smooth"})
})
let span11 = document.getElementById('dated');
span11.innerHTML = new Date().getFullYear();
I am generating a default header for a given file and I want the sender ID to have 4 characters and the sender Name to have 45 characters. if they are less than 4 and 45 respectfully, I need to enter spaces to have the 4 or 45 characters. How can I do this?
In the figure below as you can see there are not filled in the necessary spaces for when I do blank file. And even if I write something on the sender ID or the sender Name nothing is added.
What am I doing wrong?
function download(fileName, text) {
let element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
document.getElementById("generate").addEventListener("click", function(){
// Generate .txt file header
//force 4 chars
let id = document.getElementById("senderID");
if (id.textContent.length < 4) {
id.textContent += ' ';
}
//force 45 chars
let name = document.getElementById("senderName");
if (name.textContent.length < 45) {
name.textContent += ' ';
}
let header = "HDRPB" + id.textContent + name + "01.10";
let body = document.getElementById("fileContents").textContent;
let text = header;
let fileName = document.getElementById("fileName").value + ".txt";
download(fileName, text);
}, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="css/site.css">
<title>Generator</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-2 p-0 mt-2">
<label for="senderID" class="font-weight-bold">Sender ID:</label>
<input id="senderID" type="text" maxlength="4" size="4"/>
</div>
<div class="col-6 p-0 mt-2">
<label for="senderName" class="font-weight-bold">Sender Name:</label>
<input id="senderName" type="text" maxlength="45" size="45"/>
</div>
</div>
<div class="row mt-5">
<div class="col-10">
<label for="fileName" class="font-weight-bold">File Name:</label>
<input id="fileName" type="text"/>
</div>
<div class="col-2">
<button id="generate" type="button" class="btn btn-light font-weight-bold mx-auto">Generate File</button>
</div>
</div>
<div id="fileContents" class=""></div>
</div>
<script src="js/app.js"></script>
</body>
</html>
Consider the following code:
function genId(seed) {
var result = new Array(4);
for (var i = 0; i < 4; i++) {
result[i] = seed[i] || " ";
}
return result.join("");
}
function genName(seed) {
var result = new Array(45);
for (var c = 0; c < 45; c++) {
result[c] = seed[c] || " ";
}
return result.join("");
}
document.getElementById("genHead").addEventListener("click", function() {
var i = document.getElementById("hid").value;
var n = document.getElementById("hname").value;
var header = genId(i) + genName(n);
document.getElementById("results").innerHTML = header;
});
#results {
font-family: monospace;
border: 1px solid #ccc;
display: inline-block;
}
<p>ID: <input type="text" id="hid" /></p>
<p>Name: <input type="" id="hname" /></p>
<button id="genHead">Generate Header</button>
<div id="results"></div>
In this example, I am creating an Array of the specific number of characters. String is considered an Array of Characters anyway. I am using $nbsp; to represent spaces in HTML but you can use ' ' or " ".
There will always be a result due to result[c] = seed[c] || " "; If seed has a character in that position, it will be entered into result at the same position. Otherwise it will enter the No Break Space or the character you want.
You can also do this:
function formatText(t, n, c) {
if(t == undefined){
return "";
}
if(n == undefined){
n = 45;
}
if(c == undefined){
c = " ";
}
var r = new Array(n);
for (var i = 0; i < n; i++) {
r[i] = t[i] || c;
}
return r.join("");
}
Then use like so:
var i = formatText("12", 4, " ");
var n = formatText("test", 45, " ");
Hope this helps.
I have a situation where user may insert the Total Quantity and also the Total Pass and Total Fail. I have created a function where when the number of Total Pass inserted, the loop (of entering the pass score) will run according to the iterations inputted.
However, I do not want to have the loop to display the line Enter The Score : in the JavaScript function. Therefore, I want the function to call a div from the HTML itself.
For example, I want the <div id="outputPass"><p>Enter the score : <input type="text" /></p></div> to be called in the loop function which I have created in the document.getElementById('btnPass').onclick = function().
I have inserted some comments in the code section.
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
item.innerHTML = "";
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass" onclick="return validate();"></p><br />
<!--This Div-->
<div id="outputPass">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p>Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
You can make the following changes to achieve what you are looking for:
Initially we're giving an id of pscore/fscore (for pass and fail respectively) to the <p></p> tags and hiding them.
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
We're accessing them in the javascript code in the form of variables pscore and fscore respectively. (Make sure they are declared globally outside)
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
Then in the iterations we can just make a clone of the pscore/fscore , give a class of pscore/fscore to the <p></p> tags and remove the id of pscore/score (to avoid duplicate IDs), changing the display to block and append it to the output container by using the following:
var cln = pscore.cloneNode(true);
cln.style.display="block";
cln.className ="pscore";
cln.removeAttribute("id");
item.appendChild(cln);
var cln = fscore.cloneNode(true);
cln.style.display="block";
cln.removeAttribute("id");
cln.className ="fscore";
item.appendChild(cln);
var pscore = document.getElementById('pscore');
var fscore = document.getElementById('fscore');
document.getElementById('btnPass').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputPass').value);
var output = document.getElementById('outputPass');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Pass Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = pscore.cloneNode(true);
cln.style.display = "block";
cln.className = "pscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
document.getElementById('btnFail').onclick = function() {
var totalIterations = parseInt(document.getElementById('inputFail').value);
var output = document.getElementById('outputFail');
var quantity = document.getElementById('quantity').value;
output.innerHTML = '';
if (quantity < totalIterations) {
alert("Invalid Input, Fail Value(" + totalIterations + ") Bigger than Quantity(" + quantity + ")");
} else {
for (var i = 1; i <= totalIterations; i++) {
var item = document.createElement('div');
//Call <div> from HTML
var cln = fscore.cloneNode(true);
cln.style.display = "block";
cln.className = "fscore";
cln.removeAttribute("id");
item.appendChild(cln);
output.appendChild(item);
}
}
};
function togglePass() {
var x = document.getElementById("passDiv");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function toggleFail() {
var y = document.getElementById("failDiv");
if (y.style.display === "block") {
y.style.display = "none";
} else {
y.style.display = "block";
}
}
.display {
display: none;
}
<form method="post" name="form">
<p>Enter the quantity : <input type="text" id="quantity" name="quantity" /></p><br />
<input type="button" value="Pass" onclick="togglePass()">
<input type="button" value="Fail" onclick="toggleFail()">
<div id="passDiv" class="display">
<p>Enter Total Pass : <input type="text" id="inputPass" name="inputPass" /> <input type="button" value="Key In Score" id="btnPass"></p><br />
<!--This Div-->
<div id="outputPass">
<p id="pscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
<br />
<div id="failDiv" class="display">
<p>Enter Total Fail : <input type="text" id="inputFail" /> <input type="button" value="Key In Score" id="btnFail"></p><br />
<!--This Div-->
<div id="outputFail">
<p id="fscore" style="display:none">Enter the score : <input type="text" /></p>
</div>
<br />
<input type="button" value="DONE">
</div>
</form>
Only the first element (the first button) will get the remove event from the class "remove-row"
My HTML:
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
My JavaScript/jQuery:
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$(this).parent().remove();
});
});
I hope it's not duplicated because I tried this and some other questions, but without success.
$(document).ready(function () {
$('.remove-row').each(function(index) {
$(this).on('click', function () {
$(this).parent().remove();
});
});
});
Would do it, see this Plunk. Note that you have to click exactly on the (line of the) X to make it work.
$(function () {
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$(this).parent().remove();
});
});
$('.draggable-button').mousedown(function (e) {
if (e.which === 1) {
var button = $(this);
var button_id = button.attr('id');
var parent_height = button.parent().innerHeight();
var top = parseInt(button.css('top'));
var original_ypos = button.position().top; //original ypos
var drag_min_ypos = 0 - original_ypos;
var drag_max_ypos = parent_height - original_ypos - button.outerHeight();
var drag_start_ypos = e.clientY;
var my_ypos = original_ypos;
//Set current order for all
$('.draggable-button').each(function (i) {
$(this).attr('data-order', (i + 1));
});
var prev_button = button.prev('.draggable-button');
var next_button = button.next('.draggable-button');
var prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
var next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
$(window).on('mousemove', function (e) {
//Move and constrain
button.addClass('drag');
var direction = my_ypos > button.position().top ? 'up' : 'down';
var new_top = top + (e.clientY - drag_start_ypos);
my_ypos = button.position().top;
button.css({top: new_top + 'px'});
if (new_top < drag_min_ypos) {
button.css({top: drag_min_ypos + 'px'});
}
if (new_top > drag_max_ypos) {
button.css({top: drag_max_ypos + 'px'});
}
//Check position over others
if (direction == 'down' && next_button_ypos != '') {
if (my_ypos > next_button_ypos) { //crossed next button
next_button.css({top: (parseInt(next_button.css('top')) - next_button.outerHeight(true)) + 'px'}); //up once
var tmp_order = next_button.attr('data-order');
next_button.attr('data-order', button.attr('data-order')); //switch order
button.attr('data-order', tmp_order);
prev_button = next_button;
next_button = next_button.nextAll('.draggable-button:not(.drag)').first();
prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
}
} else if (direction == 'up' && prev_button_ypos != '') {
if (my_ypos < prev_button_ypos) { //crossed prev button
prev_button.css({top: (parseInt(prev_button.css('top')) + prev_button.outerHeight(true)) + 'px'}); //down once
var tmp_order = prev_button.attr('data-order');
prev_button.attr('data-order', button.attr('data-order')); //switch order
button.attr('data-order', tmp_order);
next_button = prev_button;
prev_button = prev_button.prevAll('.draggable-button:not(.drag)').first();
prev_button_ypos = prev_button.length > 0 ? prev_button.position().top : '';
next_button_ypos = next_button.length > 0 ? next_button.position().top : '';
}
}
});
$(window).on('mouseup', function (e) {
if (e.which === 1) {
$('.draggable-button').removeClass('drag');
$(window).off('mouseup mousemove');
//Reorder and reposition all
$('.draggable-button').each(function () {
var this_order = parseInt($(this).attr('data-order'));
var prev_order = $(this).siblings('.draggable-button[data-order="' + (this_order - 1) + '"]');
if (prev_order.length > 0) {
$(this).insertAfter(prev_order);
}
});
$('.draggable-button').css('top', '0');
$('.draggable-button').removeAttr('data-order'); //reset
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
<button type="button" class="draggable-button">
<div>Some value<input type="hidden" name="row[][key1]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key2]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key3]"></div>
<div data-value="1">Some value<input type="hidden" name="row[][key4]"></div>
<div class="edit-row">Edit</div>
<div class="remove-row">X</div>
</button>
The problem wasn't in the code I posted. I forgot to mention that I made the buttons draggable. For that, I use a plugin, which prevented the click in some way.
Now debugging and trying to fix it, thanks for the help!
Please use it like this:
$(document).ready(function () {
// Remove row
$('.remove-row').on('click', function () {
$('.remove-row').parent().remove();
});
});
My markup is written as follows. Pay more attention to the click handler of the uploadBtn button.
<!DOCTYPE html>
<html>
<head>
<title>Cleansing Workbench</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Bootstrap -->
<link href="Content/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
</head>
<body>
<div class="container">
<h1>Cleansing Workbench</h1>
<h3>Upload File</h3>
<form class="form-inline well">
<label class="span3">Enter the file to upload</label><button id="uploadBtn" class="btn btn-default">...</button><label id="filename"></label>
<br />
<label class="span3">Enter Delimiter</label>
<select name="delimiter" id="delimiter">
<option value="comma">Comma</option>
<option value="tab">Tab</option>
<option value="pipe">Pipe</option>
<option value="other">Other</option>
</select>
<label>Specify Delimiter</label>
<input type="text" name="otherDelimiter" id="txtdelimiter" value="Comma (,)" />
<br />
<br />
<div class="text-right">
<input type="submit" class="btn btn-primary" value="Upload" />
</div>
</form>
<iframe name="upload" id="upload" src="about:blank" style="display:none"></iframe>
</div>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/bootstrap/js/bootstrap.min.js"></script>
<script type="text/javascript">
(function ($) {
$.fn.toggleDisabled = function () {
return this.each(function () {
var $this = $(this);
if ($this.attr('disabled')) $this.removeAttr('disabled');
else $this.attr('disabled', 'disabled');
});
};
})(jQuery);
$(function () {
var arrDelimiterEnums = ['Comma (,)',
'Tab Separated ( \\t )',
'Pipe ( | )'];
$txt = $('#txtdelimiter').toggleDisabled();
$('#delimiter').change(function () {
var obj = this;
var indx = obj.selectedIndex;
var val = obj.options[indx].value;
if (val == 'other') {
$txt.val('').toggleDisabled();
}
else {
if (!$txt.attr('disabled'))
$txt.toggleDisabled();
$txt.val(arrDelimiterEnums[indx]);
}
});
$('#upload').load(function () {
});
$('#uploadBtn').click(function () {
var ifr = document.getElementById('upload');
var doc = ifr.contentWindow.document;
if (doc.getElementById('uploader') == null) {
var frm = document.createElement('form');
frm.action = "fileupload.ashx";
frm.method = "post";
frm.id = 'uploader';
var inp = document.createElement('input');
inp.type = "file";
inp.name = 'uploadFile';
inp.id = 'uploadbtn';
var i = $(inp).click(function () {
console.log('hello');
console.log(this.value);
});
frm.appendChild(inp);
doc.body.appendChild(frm);
//i.trigger('click', null);
}
else {
var btn = doc.getElementById('uploadbtn');
$(btn).trigger('click', null);
}
});
});
</script>
</body>
</html>
As soon as the following line executes, the url in my browser gets appended with ?delimiter=comma.
doc.body.appendChild(frm);
I expected this would not reload. So what do I do to not make it reload?
Take your inputs out of the form <form class="form-inline well"> & just manipulate them with jQuery or vanilla javascript.
When buttons are in a form they automatically "submit"/refresh the page.