I have a input text field with datalist. The Datalist data comes from a database. The input field is generated dynamically with javascript and if i transfer the value of the input field into the textarea field with the button, the page is reloading and I don't know why.
If someone could help me, that would pretty nice :)
This is the snippet of the button in line 10:
<button class="button3" style="width:185px;" onclick="artikeleinfuegen()">Artikel übernehmen</button>
And this is the function:
function artikeleinfuegen() {
var x = document.getElementById("artikelsuche").value;
document.getElementById("artikelbeschreibung[]").innerHTML = x;
}
This is the whole script.
var steuer = '19,00';
function O(id) {
return document.getElementById(id)
}
function insertPos() {
pos = '<table><tr>';
pos += '<td valign=top style="width:100px;"><input type=text name="anz[]" value="1" size=4 onKeyUp="calculate()" /></td>';
pos += '<td valign=top style="width:100px;"><select name="einheit[]"><option value="Lfm.">Lfm.</option><option value="Pal.">Pal.</option><option value="pschl.">pschl.</option><option value="Pkg.">Pkg.</option><option value="Std.">Std.</option><option value="Stk.">Stk.</option> size=4 onKeyUp="calculate()" /></td>';
pos += '<td valign=top><input type="text" list="artikelliste" name="artikelsuche" id="artikelsuche" autocomplete="off" placeholder="Artikelsuche" style="width:700px;"><button class="button3" style="width:185px;" onclick="artikeleinfuegen()">Artikel übernehmen</button><br><textarea style="width:900px;" rows=7 name=dsc[] id=artikelbeschreibung[] onKeyUp="typeAhead(event, this)"></textarea></td>';
pos += '<td valign=top style="width:100px;"><input type=text name="ep[]" value="" size=4 onKeyUp="calculate()" /></td>';
pos += '<td valign=top style="width:100px;"><input type=text name="poserab[]" value="0" size=4 onKeyUp="calculate()" /></td>';
pos += '<td valign=top style="width:100px;"><input type=text name="posprab[]" value="1" size=4 onKeyUp="calculate()" /></td>';
pos += '<td valign=top><input style="color:red;" type=button name="del[]" value=" X " onclick="deletePos(this);"/></td>';
pos += '</tr></table>';
obj = document.createElement("DIV");
obj.innerHTML = pos;
O("docpos").appendChild(obj);
a_anz = document.getElementsByName("anz[]");
a_anz[a_anz.length - 1].focus()
}
function Rabatt() {
return '<div class="column1">Gesamtrabatt €<input type=text name="geserab" value="0" size=4 onKeyUp="calculate()"></div><div class="column1">Gesamtrabatt %<input type=text name="gesprab" value="1" size=4 onKeyUp="calculate()"></div>';
}
function deletePos(obj) {
O("docpos").removeChild(obj.parentNode.parentNode.parentNode.parentNode.parentNode);
calculate()
}
function calculate() {
a_anz = document.getElementsByName("anz[]");
a_ep = document.getElementsByName("ep[]");
a_poserab = document.getElementsByName("poserab[]");
a_posprab = document.getElementsByName("posprab[]");
b_geserab = document.getElementsByName("geserab");
b_gesprab = document.getElementsByName("gesprab");
sum = 0;
for (f = 0; f < a_anz.length; f++) {
menge = parseFloat(a_anz[f].value.replace(/,/, "."));
preis = parseFloat(a_ep[f].value.replace(/,/, "."));
postenrabatteuro = parseFloat(a_poserab[f].value.replace(/,/, "."));
postenrabattprozent = parseFloat(a_posprab[f].value.replace(/,/, "."));
if (!(isNaN(menge) || isNaN(preis))) sum = sum + (((menge * preis) - (menge * postenrabatteuro)) * postenrabattprozent)
}
gesamtrabatteuro = parseFloat(b_geserab[0].value.replace(/,/, "."));
gesamtrabattprozent = parseFloat(b_gesprab[0].value.replace(/,/, "."));
mwst = parseFloat(steuer.replace(/,/, "."));
st = sum * mwst / 100;
gr = (sum * gesamtrabattprozent - gesamtrabatteuro) - sum;
nettoabzug = sum + gr;
total = sum + st;
O("netto").value = sum.toFixed(2).toString().replace(/\./, ",") + " €";
O("gr").value = gr.toFixed(2).toString().replace(/\./, ",") + " €";
O("nettoabzug").value = nettoabzug.toFixed(2).toString().replace(/\./, ",") + " €";
O("steuer").value = st.toFixed(2).toString().replace(/\./, ",") + " €";
O("brutto").value = total.toFixed(2).toString().replace(/\./, ",") + " €"
}
function artikeleinfuegen() {
var x = document.getElementById("artikelsuche").value;
document.getElementById("artikelbeschreibung[]").innerHTML = x;
}
Edit:
I know that's not the best script you've seen. I'm learning JS & PHP for the last 4 weeks and i doing my best.
This is the whole html / php code
<?php
include '../../inc/header.php';
include '../../inc/nav.php';
?>
<link rel="stylesheet" href="../../css/angebot.css" type="text/css">
<style>
textarea {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
</style>
<script src="../../js/angebot_erstellen.js"></script>
<section>
<h1>Angebot erstellen</h1>
<?php
if(isset($_POST["angebot-erstellen"])){
//Datenbank-Verbindung herstellen
include '../../inc/connect.php';
//Nutzereingabe aus Angebotposition in Variablen speichern
$kunde = $_POST["kunde"];
$anrede = $_POST["anrede"];
$datum = $_POST["datum"];
$referenz = $_POST["referenz"];
$zahlungsbedingungen = $_POST["zahlungsbedingungen"];
$netto = $_POST["netto"];
$mwst = $_POST["mwst"];
$brutto = $_POST["brutto"];
$pos1anz = $_POST['anz'][0];
$pos1einheit = $_POST['einheit'][0];
$pos1dsc = $_POST['dsc'][0];
$pos1ep = $_POST['ep'][0];
$pos1rab = $_POST['posrab'][0];
$pos2anz = $_POST['anz'][1];
$pos2einheit = $_POST['einheit'][1];
$pos2dsc = $_POST['dsc'][1];
$pos2ep = $_POST['ep'][1];
$pos2rab = $_POST['posrab'][1];
// 3. String für SQL-Anweisung erstellen
$insertString = "INSERT INTO angebote (kunde, anrede, datum, referenz, zahlungsbedingungen, netto, mwst, brutto, pos1anz, pos1einheit, pos1dsc, pos1ep, pos1rab, pos2anz, pos2einheit, pos2dsc, pos2ep, pos2rab)
VALUES ('$kunde', '$anrede', '$datum', '$referenz', '$zahlungsbedingungen', '$netto', '$mwst', '$brutto', '$pos1anz', '$pos1einheit', '$pos1dsc', '$pos1ep', '$pos1rab', '$pos2anz', '$pos2einheit', '$pos2dsc', '$pos2ep', '$pos2rab');";
// SQL-Anweisung durchfuehren
$check = mysqli_query($connect, $insertString);
if($check) {
echo '<span style="color: green;" /><strong>Angebot erfolgreich erstellt</strong></span>';
}}
// Hier wird der Kunde ausgegeben, welcher zuvor ausgewählt wurde.
// Kundenauswahl Verarbeitung
// 1. Verbindung zur Datenbank herstellen
include '../../inc/connect.php';
// 2. Prüfe Radio-Button-Auswahl
if(isset($_GET["auswahl"])){
// 3. Datenbankabfrage starten
$id = $_GET["auswahl"];
$abfrage = "SELECT * FROM kunden WHERE id = $id";
$result = mysqli_query($connect, $abfrage);
// 4. Datensatz in Variablen speichern
$kdata = mysqli_fetch_assoc($result);
$firma = $kdata["firma"];
$anrede = $kdata["anrede"];
$vorname = $kdata["vorname"];
$nachname = $kdata["nachname"];
$strasse = $kdata["strasse"];
$plz = $kdata["plz"];
$ort = $kdata["ort"];
}
// 5. Das Bearbeiten-Formular anzeigen
echo "<form action='angebot_erstellen.php' method='post'>";
echo "<div class='column3'>";
echo "<input name='id' type='hidden' value='$id'>";
echo "<textarea name='kunde' rows='10' cols='30'>$firma\n$vorname $nachname\n$strasse\n$plz $ort</textarea>";
echo "</div>";
// Hier wird die Artikelsuche ausgegeben
// 1. Artikeldaten Abfrage
$abfrageartikelsuche = "select artikelname from artikel";
$resultartikelsuche = mysqli_query($connect, $abfrageartikelsuche) or die("Error " . mysqli_error($connect));
?>
<!-- Artikelsuche -->
<datalist id="artikelliste">
<?php while($row = mysqli_fetch_array($resultartikelsuche)) { ?>
<option value="<?php echo $row['artikelname']; ?>"><?php echo $row['artikelname']; ?></option>
<?php } ?>
</datalist>
<?php mysqli_close($connect); ?>
<!-- Obere Eingabemaske -->
<div class="column3">
<textarea name="anrede" id="anrede" rows="10" cols="30" placeholder="Anrede"/></textarea>
</div>
<div class="column3">
<input type="date" name="datum" value="<?php echo date('Y-m-d'); ?>"/>
<input type="text" disabled name="angebotid" placeholder="Angebotsnummer (wird automatisch vergeben)"/>
<input type="text" name="referenz" placeholder="Referenz"/>
</div>
<!-- Hier beginnt die Angebotsbearbeitung fŸr Positionen -->
<!-- Positionen -->
<div id="docpos">
<table class="plist" style="font-size:10px;">
<tbody><tr>
<th style="width:100px;">Menge</th>
<th style="width:100px;border-left:1px solid grey;">Einheit</th>
<th style="width:900px;border-left:1px solid grey;">Beschreibung</th>
<th style="width:100px;border-left:1px solid grey;">EP Netto</th>
<th style="width:100px;border-left:1px solid grey;">Pos. Rabatt €</th>
<th style="width:100px;border-left:1px solid grey;">Pos. Rabatt %</th>
<th> </th>
</tr>
</tbody></table></div>
<input type="button" class="button2" name="newpos" style="float:right; clear:both;margin-right:25px;" value="Position erstellen" onclick="insertPos()">
<div class="column70">
<div class="column50">
<textarea name="zahlungsbedingungen" id="zahlungsbedingungen" rows="10" cols="30" placeholder="Zahlungsbedingungen"></textarea>
</div>
<div class="column50">
<select name="gesamtrabatt" id="gesamtrabatt">
<option value="Rabatt">Rabatt</option>
<option value="Nachlass">Nachlass</option>
</select>
<div id="rabatt"></div>
<script> document.getElementById("rabatt").innerHTML = Rabatt(); </script>
</div>
<input class="button" type="submit" name="angebot-erstellen" value="Angebot erstellen">
</div>
<div class="column30">
<div style="width:100%;border: #4B9F93 1px solid;border-bottom:2px solid #F39200;"><br>
<label> Summe Netto:</label><input type="text" name="netto" id="netto" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label> Rabatt / Nachlass:</label><input type="text" name="gr" id="gr" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label> Summe Netto nach Abzug:</label><input type="text" name="nettoabzug" id="nettoabzug" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label> MwSt 19,00%:</label><input type="text" name="mwst" id="steuer" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label style="font-weight:bold;"> Gesamt Brutto:</label><input type="text" name="brutto" id="brutto" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;font-weight:bold;" tabindex="32000">
</div>
</div>
</form>
</section>
<?php
include '../../inc/footer.php';
?>
</body>
</html>
added code to toggle amounts to JS amouts
using the first row of the tbody as template
looping over rows when calculating
removed all inline event handlers
Note I remove the date PHP - you can insert that again
I also could not find your typeAhead function. Please replace mine with yours
function typeAhead(e,tgt) { console.log(tgt.value) }; // missing function
const toNum = str => {
let num = str.replace(/,/, ".");
return isNaN(num) || num.trim() === "" ? 0 : +num;
}
const toAmount = num => num.toLocaleString('de-DE', {
style: 'currency',
currency: 'EUR'
})
const steuer = '19,00';
const mwst = toNum(steuer);
let container, nettoField, grField, nettoabzugField, steuerField, bruttoField, geserabField, gesprabField;
window.addEventListener("load", function() {
container = document.getElementById("docpos");
nettoField = document.getElementById("netto");
grField = document.getElementById("gr");
nettoabzugField = document.getElementById("nettoabzug");
steuerField = document.getElementById("steuer");
bruttoField = document.getElementById("brutto");
geserabField = document.querySelector("[name=geserab]");
gesprabField = document.querySelector("[name=gesprab]");
container.addEventListener("click", function(e) {
const tgt = e.target;
const parent = tgt.closest("tr");
if (tgt.classList.contains("button3")) {
const x = parent.querySelector("[name=artikelsuche]").value;
parent.querySelector(".artikelbeschreibung").value = x;
} else if (tgt.classList.contains("del")) {
tgt.closest("tr").remove();
calculate()
}
})
container.addEventListener("input", calculate);
geserabField.addEventListener("input", calculate);
gesprabField.addEventListener("input", calculate);
container.addEventListener("keyup", function(e) {
const tgt = e.target;
if (tgt.classList.contains("artikelbeschreibung")) {
typeAhead(e, tgt);
}
})
document.querySelector(".button2").addEventListener("click", insertPos);
})
function insertPos() {
const newTr = container.querySelector("tr").cloneNode(true);
[...newTr.querySelectorAll("input, textarea")].forEach(inp => inp.value="");
newTr.querySelector(".anz").value=1;
container.appendChild(newTr);
newTr.querySelector(".anz").focus();
}
function calculate() {
const gesamtrabatteuro = toNum(document.querySelector("[name=geserab]").value);
const gesamtrabattprozent = toNum(document.querySelector("[name=gesprab]").value);
let sum = 0;
[...container.querySelectorAll("tr")].forEach(row => {
const postenrabatteuro = toNum(row.querySelector(".poserab").value);
const postenrabattprozent = toNum(row.querySelector(".posprab").value);
const preis = toNum(row.querySelector(".ep").value);
const menge = toNum(row.querySelector(".anz").value);
sum += (((menge * preis) - (menge * postenrabatteuro)) * postenrabattprozent)
});
let st = sum * mwst / 100;
let gr = (sum * gesamtrabattprozent - gesamtrabatteuro) - sum;
let nettoabzug = sum + gr;
total = sum + st;
nettoField.value = toAmount(sum);
grField.value = toAmount(gr);
nettoabzugField.value = toAmount(nettoabzug);
steuerField.value = toAmount(st);
bruttoField.value = toAmount(total);
}
#docpos>tr:first-child .del {
display: none;
}
textarea {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
<datalist id="artikelliste">
<option value="Name1">Name1</option>
</datalist>
<!-- Obere Eingabemaske -->
<div class="column3">
<textarea name="anrede" id="anrede" rows="10" cols="30" placeholder="Anrede" /></textarea>
</div>
<div class="column3">
<input type="date" name="datum" value="" />
<input type="text" disabled name="angebotid" placeholder="Angebotsnummer (wird automatisch vergeben)" />
<input type="text" name="referenz" placeholder="Referenz" />
</div>
<!-- Hier beginnt die Angebotsbearbeitung für Positionen -->
<!-- Positionen -->
<div>
<table class="plist" style="font-size:10px;">
<thead>
<tr>
<th style="width:100px;">Menge</th>
<th style="width:100px;border-left:1px solid grey;">Einheit</th>
<th style="width:900px;border-left:1px solid grey;">Beschreibung</th>
<th style="width:100px;border-left:1px solid grey;">EP Netto</th>
<th style="width:100px;border-left:1px solid grey;">Pos. Rabatt €</th>
<th style="width:100px;border-left:1px solid grey;">Pos. Rabatt %</th>
<th> </th>
</tr>
</thead>
<tbody id="docpos">
<tr>
<td valign=top style="width:100px;"><input type=text class="anz" name="anz[]" value="1" size="4" /></td>
<td valign=top style="width:100px;">
<select name="einheit[]">
<option value="Lfm.">Lfm.</option>
<option value="Pal.">Pal.</option>
<option value="pschl.">pschl.</option>
<option value="Pkg.">Pkg.</option>
<option value="Std.">Std.</option>
<option value="Stk.">Stk.</option>
</select>
</td>
<td valign=top><input type="text" list="artikelliste" name="artikelsuche" autocomplete="off" placeholder="Artikelsuche" style="width:700px;">
<button type="button" class="button3" style="width:185px;">Artikel übernehmen</button><br>
<textarea style="width:900px;" rows=7 name=dsc[] class="artikelbeschreibung"></textarea>
</td>
<td valign=top style="width:100px;"><input type=text class="ep" name="ep[]" value="" size="4" /></td>
<td valign=top style="width:100px;"><input type=text class="poserab" name="poserab[]" value="0" size="4" /></td>
<td valign=top style="width:100px;"><input type=text class="posprab" name="posprab[]" value="1" size="4" /></td>
<td valign=top><input style="color:red;" type=button class="del" name="del[]" value=" X " /></td>
</tr>
</tbody>
</table>
</div>
<input type="button" class="button2" name="newpos" style="float:right; clear:both;margin-right:25px;" value="Position erstellen">
<div class="column70">
<div class="column50">
<textarea name="zahlungsbedingungen" id="zahlungsbedingungen" rows="10" cols="30" placeholder="Zahlungsbedingungen"></textarea>
</div>
<div class="column50">
<select name="gesamtrabatt" id="gesamtrabatt">
<option value="Rabatt">Rabatt</option>
<option value="Nachlass">Nachlass</option>
</select>
<div id="rabatt">
<div class="column1">Gesamtrabatt €<input type=text name="geserab" value="0" size="4"></div>
<div class="column1">Gesamtrabatt %<input type=text name="gesprab" value="1" size="4"></div>
</div>
</div>
<input class="button" type="submit" name="angebot-erstellen" value="Angebot erstellen">
</div>
<div class="column30">
<div style="width:100%;border: #4B9F93 1px solid;border-bottom:2px solid #F39200;"><br>
<label> Summe Netto:</label><input type="text" name="netto" id="netto" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label> Rabatt / Nachlass:</label><input type="text" name="gr" id="gr" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label> Summe Netto nach Abzug:</label><input type="text" name="nettoabzug" id="nettoabzug" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label> MwSt 19,00%:</label><input type="text" name="mwst" id="steuer" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;" tabindex="32000"><br>
<label style="font-weight:bold;"> Gesamt Brutto:</label><input type="text" name="brutto" id="brutto" value="" readonly="" style="border:none;background-color:transparent;width:60%;text-align:left;font-weight:bold;" tabindex="32000">
</div>
</div>
</form>
</section>
Related
please help me resolved this problem, I have an input value (weight) that generated by jQuery, I know it won't change it's value because of looping in my code, but is there another way to do this ?
The goal is I want to autogenerate the weight input value, but I can change it too.
if the snippet don't work, here's the link :
https://jsfiddle.net/s3grkqxm/
Thank you for your help.
var numRows = 2, ti = 5;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recalc() {
var berat = 0;
var qty = 0;
var grandtotal = 0;
var grandtotalbtg = 0;
$('#kas_table').find('tr').each(function() {
var berat = $(this).find('input.berat').val();
var qty = $(this).find('input.qty').val();
var subtotal = (berat * qty);
let berat_max = $(this).find('option:selected').data('berat');
$(this).find('input.subtotal').val(Math.round(subtotal * 100) / 100);
$(this).find('input.berat').val(berat_max).text();
});
}
$(function() {
$('div.table-responsive').on("keyup change blur", recalc);
});
var i=0;
$('#add_new').click(function(){
i++;
$('#mainbody').append('<tr><td>' +
'<select class="form-control nama" name="addmore['+i+'][nama]" id="nama'+i+'" required >' +
'<option disabled="disabled" selected="selected" value="" >Select Produk</option>' +
'<option value="1" data-berat="100">Item 1</option>' +
'<option value="1" data-berat="170">Item 2</option>' +
'</select></td>' +
'<td><input class="form-control qty" type="number" name="addmore['+i+'][qty]" id="qty'+i+'" required ></td>' +
'<td><input step=".001" class="form-control berat" type="number" name="addmore['+i+'][berat]" id="berat'+i+'" required ></td>' +
'<td><input class="form-control subtotal" type="number" name="addmore['+i+'][subtotal]" id="subtotal'+i+'" required readonly></td>'
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive">
<table class="table-bordered" width="100%" id="kas_table">
<thead>
<tr>
<th width="40%">Name</th>
<th width="10%">Qty</th>
<th width="10%">Weight</th>
<th>Subtotal KG</th>
<th>
<button id="add_new" type="button" name="add_new" class="btn btn-sm btn-success"> +</button>
</th>
</tr>
</thead>
<tbody id="mainbody">
<tr>
<td><select class="form-control nama" name="addmore[0][nama]" id="nama0" required >
<option disabled="disabled" selected="selected" value="" >Select Produk</option>
<option value="1" data-berat="100">Item 1</option>
<option value="2" data-berat="170">Item 2</option>
</select></td>
<td><input class="form-control qty" type="number" name="addmore[0][qty]" id=qty0 required></td>
<td><input step=".001" class="form-control berat" type="number" name="addmore[0][berat]" id="berat0" required></td>
<td><input class="form-control subtotal" type="number" name="addmore[0][subtotal]" id="subtotal0" readonly></td>
</tr>
</tbody>
</table>
</div>
the reason when you change Weight it back to the original value is because you refresh the whole table including the drop-down that's why it set back the value which must be set after the dropdown change.$('div.table-responsive').on("keyup change blur", recalc); due this.
you just need to separate each element change event to get the proper results.
I set the value in Weight on the change dropdown by adding this
$(document).on('change', 'select', function() {
$('#kas_table').find('tr').each(function() {
let berat_max = $(this).find('option:selected').data('berat');
$(this).find('input.berat').val(berat_max).text();
});
});
and separately call qty and weight using this
$('.qty').on("keyup change blur", recalc);
$('.berat').on("keyup change blur", recalc);
finally here is your updated code working as expected hope it will helpful for you.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var numRows = 2, ti = 5;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recalc() {
var berat = 0;
var qty = 0;
var grandtotal = 0;
var grandtotalbtg = 0;
$('#kas_table').find('tr').each(function() {
var berat = $(this).find('input.berat').val();
var qty = $(this).find('input.qty').val();
var subtotal = (berat * qty);
$(this).find('input.subtotal').val(Math.round(subtotal * 100) / 100);
});
}
function selectProduct(e)
{
let berat_max = $(e).find('option:selected').data('berat');
$(e).parent().parent().find('input.berat').val(berat_max).text();
var berat = $(e).parent().parent().find('input.berat').val();
var qty = $(e).parent().parent().find('input.qty').val();
var subtotal = (berat * qty);
$(e).parent().parent().find('input.subtotal').val(Math.round(subtotal * 100) / 100);
}
$(function() {
$(document).on('change', 'select', function() {
$('.qty').on("keyup change blur", recalc);
$('.berat').on("keyup change blur", recalc);
});
var i=0;
$('#add_new').click(function(){
i++;
$('#mainbody').append('<tr><td>' +
'<select class="form-control nama" name="addmore['+i+'][nama]" id="nama'+i+'" onchange="selectProduct(this)" required >' +
'<option disabled="disabled" selected="selected" value="">Select Produk</option>' +
'<option value="1" data-berat="100">Item 1</option>' +
'<option value="1" data-berat="170">Item 2</option>' +
'</select></td>' +
'<td><input class="form-control qty" type="number" name="addmore['+i+'][qty]" id="qty'+i+'" required ></td>' +
'<td><input step=".001" class="form-control berat" type="number" name="addmore['+i+'][berat]" id="berat'+i+'" required ></td>' +
'<td><input class="form-control subtotal" type="number" name="addmore['+i+'][subtotal]" id="subtotal'+i+'" required readonly></td>'
)
});
});
</script>
</head>
<body>
<div class="table-responsive">
<table class="table-bordered" width="100%" id="kas_table">
<thead>
<tr>
<th width="40%">Name</th>
<th width="10%">Qty</th>
<th width="10%">Weight</th>
<th>Subtotal KG</th>
<th>
<button id="add_new" type="button" name="add_new" class="btn btn-sm btn-success"> +</button>
</th>
</tr>
</thead>
<tbody id="mainbody">
<tr>
<td><select class="form-control nama" name="addmore[0][nama]" id="nama0" onchange="selectProduct(this)" required >
<option disabled="disabled" selected="selected" value="">Select Produk</option>
<option value="1" data-berat="100">Item 1</option>
<option value="2" data-berat="170">Item 2</option>
</select></td>
<td><input class="form-control qty" type="number" name="addmore[0][qty]" id=qty0 required></td>
<td><input step=".001" class="form-control berat" type="number" name="addmore[0][berat]" id="berat0" required></td>
<td><input class="form-control subtotal" type="number" name="addmore[0][subtotal]" id="subtotal0" readonly></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
I have nine number fields to calculate. I need to check for duplicate entries in these 9 number fields and if found duplicate values, change the background color of the screen to 'red'. I'm not able to find solution for the mentioned.
I have created a table with 9 nine number fields to input the numbers and calculate the sum.
I searched for code to check for duplicate values in number fields, but found code to check for duplicate values in text fields.
<html>
<head>
<script>
function Sum() {
alert("hi");
var num1 = Number(document.getElementById("qty1").value);
var num2 = Number(document.getElementById("qty2").value);
var num3 = Number(document.getElementById("qty3").value);
var num4 = Number(document.getElementById("qty4").value);
var num5 = Number(document.getElementById("qty5").value);
var num6 = Number(document.getElementById("qty6").value);
var num7 = Number(document.getElementById("qty7").value);
var num8 = Number(document.getElementById("qty8").value);
var num9 = Number(document.getElementById("qty9").value);
var sum=num1+num2+num3+num4+num5+num6+num7+num8+num9
document.getElementById("answer").value = sum;
}
</script>
<style>
table>tbody>tr:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
background-color: green;
}
#sumtable th, #sumtable td{
padding:5px;
}
</style>
</head>
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number"placeholder="input3"value="input3"id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4" ></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5" ></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6" ></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7" ></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8" ></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9" ></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
</body>
</html>
The above code generates 9 input number fields in table format to enter numbers and calculate the sum
Add your numbers to an array and loop through. One possible example, see https://codepen.io/anon/pen/yZaBrb:
var a = new Array(1,2,3,4,5,6,7,9,2,4);
var duplicate = false;
for (i=0;i<a.length;i++){
duplicate = false;
for(j=0;j<a.length;j++){
if(i != j && a[i]==a[j])
duplicate = true;
}
if(duplicate)
document.write('<span style="background-color:red;">')
document.write(a[i]);
if(duplicate)
document.write('</span>')
}
Create two events blur & keyup. On blur get the value from the input and push it in an array, on keyup check if the array contains the same value. If the value is present in the array then add a class to the target element or remove it
function Sum() {
alert("hi");
var num1 = Number(document.getElementById("qty1").value);
var num2 = Number(document.getElementById("qty2").value);
var num3 = Number(document.getElementById("qty3").value);
var num4 = Number(document.getElementById("qty4").value);
var num5 = Number(document.getElementById("qty5").value);
var num6 = Number(document.getElementById("qty6").value);
var num7 = Number(document.getElementById("qty7").value);
var num8 = Number(document.getElementById("qty8").value);
var num9 = Number(document.getElementById("qty9").value);
var sum = num1 + num2 + num3 + num4 + num5 + num6 + num7 + num8 + num9
document.getElementById("answer").value = sum;
}
let sumArray = []
document.querySelectorAll('input[type="number"]').forEach((item) => {
item.addEventListener('blur', (e) => {
sumArray.push(e.target.value)
})
item.addEventListener('keyup', (e) => {
if (sumArray.indexOf(e.target.value) !== -1) {
e.target.parentNode.classList.add('error')
} else if (e.target.parentNode.classList.contains('error')) {
e.target.parentNode.classList.remove('error')
}
})
})
table>tbody>tr:nth-child(odd) {
background-color: blue;
}
table>tbody>tr:nth-child(even) {
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd) {
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even) {
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd) {
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even) {
background-color: green;
}
#sumtable th,
#sumtable td {
padding: 5px;
}
.error {
border: 2px solid red;
}
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1" id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number" placeholder="input3" value="input3" id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4"></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5"></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6"></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7"></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8"></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9"></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
its pretty simple just put same class in input field and loop through it like
In Html ,
<td>
<input type="number" class="checkSame" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" class="checkSame" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number" class="checkSame" placeholder="input3"value="input3"id="qty3"></td>
then in javascript ,
var inputs = document.getElementsByClassName("checkSame");
var temp;
var count = 1;
for(var i = 0; i < inputs .length; i++)
{
temp = document.getElementsByClassName("checkSame")[i].value;
if(temp == document.getElementsByClassName("checkSame")[count++].value)
{
//change your background color here
break;
}
}
i think it works.
I hope this will help you to find duplicate fields
function Sum() {
alert("hi");
let arr = [];
let sum;
let duplicate = false;
for (let i = 1; i <= 9; i++) {
let num = Number(document.getElementById(`qty${i}`).value);
let indexOfDuplicateNum = arr.indexOf(num);
if (indexOfDuplicateNum > -1){
duplicate = true;
alert('Duplicate value found!');
document.getElementsByTagName('body')[0].style.background = 'red';
document.getElementById(`qty${i}`).classList.add('duplicate-error');
document.getElementById(`qty${indexOfDuplicateNum+1}`).classList.add('duplicate-error');
break;
} else{
//remove error class if value is not duplicate
document.getElementById(`qty${i}`).classList.remove('duplicate-error');
arr.push(num);
sum = arr.reduce((a, b) => a+b, 0);
}
}
if (!duplicate) {
document.getElementById('answer').value = sum;
document.getElementsByTagName('body')[0].style.background = 'white';
}
}
.duplicate-error {
border: 2px solid red;
}
table>tbody>tr:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(odd){
background-color: green;
}
table>tbody>tr:nth-child(odd)>td:nth-child(even){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(odd){
background-color: blue;
}
table>tbody>tr:nth-child(even)>td:nth-child(even){
background-color: green;
}
#sumtable th, #sumtable td{
padding:5px;
}
<html>
<head>
<title>Sum Calculator</title>
</head>
<title>Sum Box</title>
<body>
<table align="center" id="sumtable">
<tbody>
<tr>
<td>
<input type="number" placeholder="input1" value="input1"id="qty1"></td>
<td>
<input type="number" placeholder="input2" value="input2" id="qty2"></td>
<td>
<input type="number"placeholder="input3"value="input3"id="qty3"></td>
</tr>
<tr>
<td><input type="number" placeholder="input4" value="input4" id="qty4" ></td>
<td><input type="number" placeholder="input5" value="input5" id="qty5" ></td>
<td><input type="number" placeholder="input6" value="input6" id="qty6" ></td>
</tr>
<tr>
<td><input type="number" placeholder="input7" value="input7" id="qty7" ></td>
<td><input type="number" placeholder="input8" value="input8" id="qty8" ></td>
<td><input type="number" placeholder="input9" value="input9" id="qty9" ></td>
</tr>
</tbody>
</table>
<!-- Sum : <input type="text" name="total" id="total"/>
Sum-->
<div align="center">
<input type="button" onclick="Sum()" name="Sum" value="Sum" id="sum">
<input id="answer">
</div>
</body>
</html>
I'm nearing the end of this script and I've noticed an error.
It's possible to add rows to the table, however when I try to remove them it doesn't seem to work. I'm guessing the error is somewhere in my JS. It was working before and then stopped working all of a sudden! Can someone please shed some light on it?
Thanks,
Snelly
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LinePriceAfterDiscount = (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceAfterDiscount').value = LinePriceAfterDiscount.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY * (LINEPRICENET) - (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LinePriceAfterDiscount * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LinePriceAfterDiscount + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
/******Calculate totals*******/
//net
var arr = document.getElementsByName('LinePriceAfterDiscount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalNetAmount').value = tot;
//VAT
var arr = document.getElementsByName('TaxAmount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalTaxAmount').value = tot;
//Gross
var NetTotal = document.getElementById('TotalNetAmount').value;
var TaxTotal = document.getElementById('TotalTaxAmount').value;
GrossTotal = (+NetTotal + +TaxTotal);
document.getElementById('TotalGrossAmount').value = GrossTotal;
}
/******Adding and removing rows******/
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting">
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty 1|||</th>
<th>Line Price Net 2|||</th>
<th>Line Price Discount% 3|||</th>
<th>Line Price Discount Amount 4|||</th>
<th>Line Price With Discount 5|||</th>
<th>VAT Rate Amount 6|||</th>
<th>VAT Amount 7|||</th>
<th>Line Price Gross-OUTPUT 8|||</th>
</tr>
</thead>
<!-- start -->
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty[]" id="Qty" step="1" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<input type="number" name="LinePriceNet[]" step="0.01" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);" />
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount[]" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceAfterDiscount[]" id="LinePriceAfterDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);" />
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount[]" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput[]" id="GrossOutput">
</td>
</tr>
</table>
<table>
<tr>
<td><label>Net Amount</label>
<input readonly="readonly" type="number" name="TotalNetAmount[]" id="TotalNetAmount">
</td>
</tr>
<tr>
<td><label>VAT Amount</label>
<input readonly="readonly" type="number" name="TotalTaxAmount[]" id="TotalTaxAmount">
</td>
</tr>
<tr>
<td><label>Gross Amount</label>
<input readonly="readonly" type="number" name="TotalGrossAmount[]" id="TotalGrossAmount">
</td>
</tr>
</table>
</form>
</body>
</html>
Here are the code to work:
function deleteRow(tableID) {
debugger;
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0].nextElementSibling;
if (chkbox != null && chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
For some reason childNodes[0] is text and childNodes[1] is the input you're looking for.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript">
function calculate(object) {
var QTY = object.parentNode.parentNode.querySelector('#Qty').value;
var LINEPRICENET = object.parentNode.parentNode.querySelector("#LinePriceNet").value;
var LINEPRICEDISCOUNT = object.parentNode.parentNode.querySelector("#LinePriceDiscountInput").value;
var TAXRATE = object.parentNode.parentNode.querySelector("#TaxRate").value;
// Lineprice with discount
LinePriceAfterDiscount = (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT))));
object.parentNode.parentNode.querySelector('#LinePriceAfterDiscount').value = LinePriceAfterDiscount.toFixed(2);
//Line Price discount Amount
LINEPRICEDISCOUNTAMOUNT = (QTY * (LINEPRICENET) - (QTY * (LINEPRICENET - (LINEPRICENET * (LINEPRICEDISCOUNT)))));
object.parentNode.parentNode.querySelector("#LinePriceDiscountAmount").value = LINEPRICEDISCOUNTAMOUNT.toFixed(2);
//Tax calculation
TAXAMOUNT = (LinePriceAfterDiscount * TAXRATE);
object.parentNode.parentNode.querySelector("#TaxAmount").value = TAXAMOUNT.toFixed(2);
//Calc Gross
LINEPRICEGROSSAMOUNT = (LinePriceAfterDiscount + TAXAMOUNT);
object.parentNode.parentNode.querySelector("#GrossOutput").value = LINEPRICEGROSSAMOUNT.toFixed(2);
/******Calculate totals*******/
//net
var arr = document.getElementsByName('LinePriceAfterDiscount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalNetAmount').value = tot;
//VAT
var arr = document.getElementsByName('TaxAmount[]');
var tot = 0;
for (var i = 0; i < arr.length; i++) {
if (parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('TotalTaxAmount').value = tot;
//Gross
var NetTotal = document.getElementById('TotalNetAmount').value;
var TaxTotal = document.getElementById('TotalTaxAmount').value;
GrossTotal = (+NetTotal + +TaxTotal);
document.getElementById('TotalGrossAmount').value = GrossTotal;
}
/******Adding and removing rows******/
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[1];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all of the items!.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
</head>
<body>
<form name="CalculationTesting">
<p>
<input type="button" value="Add Item" onClick="addRow('dataTable')" />
<input type="button" value="Remove Selected Item" onClick="deleteRow('dataTable')" />
</p>
<thead>
<tr>
<th>Qty 1|||</th>
<th>Line Price Net 2|||</th>
<th>Line Price Discount% 3|||</th>
<th>Line Price Discount Amount 4|||</th>
<th>Line Price With Discount 5|||</th>
<th>VAT Rate Amount 6|||</th>
<th>VAT Amount 7|||</th>
<th>Line Price Gross-OUTPUT 8|||</th>
</tr>
</thead>
<!-- start -->
<table id="dataTable" border="1" width="600" height="50" cellpadding="10" cellspacing="3">
<tr>
<td>
<input type="checkbox" required="required" name="chk[]" checked="checked" /></td>
</td>
<td>
<input type="number" name="Qty[]" id="Qty" step="1" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<input type="number" name="LinePriceNet[]" step="0.01" id="LinePriceNet" onblur="this.value = parseFloat(Math.round(this.value * 100) / 100).toFixed(2);" onchange="calculate(this);" />
</td>
<td>
<select type="number" name="LinePriceDiscount" id="LinePriceDiscountInput" onchange="calculate(this);" />
<option value="0.00">None</option>
<option value="0.01">1%</option>
<option value="0.02">2%</option>
<option value="0.03">3%</option>
<option value="0.04">4%</option>
<option value="0.05">5%</option>
<option value="0.06">6%</option>
<option value="0.07">7%</option>
<option value="0.08">8%</option>
<option value="0.09">9%</option>
<option value="0.10">10%</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceDiscountAmount[]" id="LinePriceDiscountAmount">
</td>
<td>
<input readonly="readonly" type="number" name="LinePriceAfterDiscount[]" id="LinePriceAfterDiscount">
</td>
<td>
<select type="number" name="TaxRate" id="TaxRate" onchange="calculate(this);" />
<option value="0.00">Zero Rate</option>
<option value="0.20">Standard(20%)</option>
<option value="0.00">Exempt</option>
<option value="0.05">Reduced Rate</option>
<option value="0.00">Outside The Scope</option>
</select>
</td>
<td>
<input readonly="readonly" type="number" name="TaxAmount[]" id="TaxAmount">
</td>
<td>
<input readonly="readonly" type="number" name="GrossOutput[]" id="GrossOutput">
</td>
</tr>
</table>
<table>
<tr>
<td><label>Net Amount</label>
<input readonly="readonly" type="number" name="TotalNetAmount[]" id="TotalNetAmount">
</td>
</tr>
<tr>
<td><label>VAT Amount</label>
<input readonly="readonly" type="number" name="TotalTaxAmount[]" id="TotalTaxAmount">
</td>
</tr>
<tr>
<td><label>Gross Amount</label>
<input readonly="readonly" type="number" name="TotalGrossAmount[]" id="TotalGrossAmount">
</td>
</tr>
</table>
</form>
</body>
</html>
I don't know how to get Grand total value
grand total is sum of all total
here is the code
<?php
$con = mysqli_connect('localhost', 'root', '', 'a.karat');
if(isset($_POST['product_id']))
{
$prno=$_POST['prno'];
$i=1;
$sql = mysqli_query($con,"select * from detail_pr where prNo='$prno'");
while ($r = mysqli_fetch_array($sql)) {
echo
'<tr>
<td><input type="checkbox" name="check[]" id="check'.$i.'" value="'.$i.'"></td>
<td><label for="productCode"></label>
<input type="text" name="productCode'.$i.'" id="productCode'.$i.'" readonly value="'.$r["productCode"].'" size="12" ></td>
<td><label for="productName"></label>
<input type="text" name="productName'.$i.'" id="productName'.$i.'" readonly value="'.$r["productName"].'"size="35" ></td>
<td><label for="qty"></label>
<input type="number" onkeyup="calc(this);" name="qty'.$i.'" id="qty'.$i.'" readonly value="'.$r["qty"].'" size="8" ></td>
<td><input type="number" onkeyup="calc(this);" name="price'.$i.'" id="price'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
<td><input type="number" onkeyup="calc(this);" name="discount'.$i.'" id="discount'.$i.'" size="10" min="0" max="99" onchange="calc(this);"></td>
<td><input type="number" name="total'.$i.'" id="total'.$i.'" size="10" min="1" max="99" onchange="calc(this);" ></td>
</tr>';
$i++;
}
}
?>
<table width="400" border="0" align="right">
<tr>
<th scope="row">Grand Total</th>
<td>:</td>
<td><input name="grandtotal" id="grandtotal" type="text"></td>
</tr>
</table>
<script>
function calc(id) {
var row = id.parentNode.parentNode;
var quant = row.cells[3].getElementsByTagName('input')[0].value;
var price = row.cells[4].getElementsByTagName('input')[0].value;
var disc = row.cells[5].getElementsByTagName('input')[0].value;
if (disc == null || disc == '') {
res = parseFloat(quant) * parseFloat(price);
} else {
var res = (parseFloat(quant) * parseFloat(price)) - (parseFloat(quant) * parseFloat(price) * (parseFloat(disc) / 100));
}
row.cells[6].getElementsByTagName('input')[0].value = res;
}
</script>
I have manage to calculate total per row
now I need your help to sum all total and put the value in the grandtotal textbox
I guess on every change of a value of one of your input elements in your form the grand total should be updated, right? I 'd place an event listener on the form tag to keep it simple.
<form id="your-form" method="post" action="">
<!-- All your other inputs here -->
<input type="text" name="grandtotal" id="grandtotal">
</form>
<script>
document.querySelector('#your-form').addEventListener('change', function( event ) {
if (event.target.id && event.target.id !== 'grandtotal') {
var allTotals = document.querySelectorAll('input[name^="total"]'),
allTotalSum = 0;
Array.prototype.forEach.call(allTotals, function( element ) {
if (element.value) {
allTotalSum += parseFloat(element.value);
}
});
document.querySelector('#grandtotal').value = allTotalSum;
}
});
</script>
So on every change of one of your input fields the sum is updated. This code is untested.
i have problem to find total_penjualan value.
i use dynamic form here. i want add all total's value in dynamic form with biayalainlain's value. i think the problem is in var ttl2 = document.getElementById(totalid).value; how to get id in additem() to put in prosestotal()?
this is my html and javascript code:
function sum() {
var hrg = document.getElementById('harga').value;
var jml = document.getElementById('jumlah').value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById('total').value = result;
}
}
function additem() {
//menentukan target append
var itemlist = document.getElementById('itemlist');
// membuat element
var row = document.createElement('tr');
var nama = document.createElement('td');
var kode = document.createElement('td');
var harga = document.createElement('td');
var jumlah = document.createElement('td');
var total = document.createElement('td');
var aksi = document.createElement('td');
// meng append element
itemlist.appendChild(row);
row.appendChild(nama);
row.appendChild(kode);
row.appendChild(harga);
row.appendChild(jumlah);
row.appendChild(total);
row.appendChild(aksi);
// membuat element input1
var nama_input = document.createElement('input');
/*nama_input.setAttribute('id', 'nama');*/
nama_input.setAttribute('name', 'nama_input[]');
nama_input.setAttribute('class', 'form-control');
var kode_input = document.createElement('input');
/* kode_input.setAttribute('id', 'kode1');*/
kode_input.setAttribute('name', 'kode_input[]');
kode_input.setAttribute('readonly', '');
kode_input.setAttribute('class', 'form-control');
var harga_input = document.createElement('input');
harga_input.setAttribute('type', 'number');
harga_input.setAttribute('name', 'harga_input[]');
harga_input.setAttribute('class', 'harga form-control');
/*harga_input.setAttribute('onkeyup', 'sum();');*/
var jumlah_input = document.createElement('input');
jumlah_input.setAttribute('type', 'number');
jumlah_input.setAttribute('name', 'jumlah_input[]');
jumlah_input.setAttribute('class', 'jumlah form-control');
jumlah_input.setAttribute('autocomplete', 'off');
/*jumlah_input.setAttribute('onkeyup', 'sum();');*/
var total_input = document.createElement('input');
total_input.setAttribute('name', 'total_input[]');
total_input.setAttribute('class', 'total form-control');
total_input.setAttribute('readonly', '');
var hapus = document.createElement('span');
// meng append element input
nama.appendChild(nama_input);
kode.appendChild(kode_input);
harga.appendChild(harga_input);
jumlah.appendChild(jumlah_input);
total.appendChild(total_input);
aksi.appendChild(hapus);
hapus.innerHTML = '<button class="btn btn-small btn-default"><b>Hapus</b></button>';
// membuat aksi delete element
hapus.onclick = function () {
row.parentNode.removeChild(row);
};
var namaid = 'nama' + (Math.floor((1 + Math.random()) * 0x10000));
var kodeid = 'kode' + (Math.floor((1 + Math.random()) * 0x10000));
var hargaid = 'harga' + (Math.floor((1 + Math.random()) * 0x10000));
var jumlahid = 'jumlah' + (Math.floor((1 + Math.random()) * 0x10000));
var totalid = 'total' + (Math.floor((1 + Math.random()) * 0x10000));
nama_input.setAttribute('id', namaid);
kode_input.setAttribute('id', kodeid);
harga_input.setAttribute('id', hargaid);
jumlah_input.setAttribute('id', jumlahid);
total_input.setAttribute('id', totalid);
$(jumlah_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(harga_input).on('keyup',function(){
sum(hargaid,jumlahid,totalid)
})
$(total_input).on('keyup',function(){
prosestotal(totalid,total,biayalain)
})
function sum(hargaid,jumlahid,totalid) {
var hrg = document.getElementById(hargaid).value;
var jml = document.getElementById(jumlahid).value;
var result = parseInt(hrg) * parseInt(jml);
if (!isNaN(result)) {
document.getElementById(totalid).value = result;
}
}
$("#" + namaid).autocomplete({
source: "get_barang.php",
minLength: 2,
select: function(event, ui) {
$("#" + kodeid).val(ui.item.kode);
$("#" + hargaid).val(ui.item.harga);
}
});
}
function prosestotal(){
var ttl = document.getElementById('total').value;
var ttl2 = document.getElementById(totalid).value;
var biayalain = document.getElementById('biayalain').value;
var hsl = parseInt(ttl) + parseInt(ttl2) + parseInt(biayalain);
if (!isNaN(hsl)) {
document.getElementById('total_penjualan').value = hsl;
}
}
<table class="table table-condensed" style="margin-left: 10px;">
<thead>
<tr>
<th width="100px">Nama</th>
<th width="100px">Kode</th>
<th width="100px">Harga</th>
<th width="100px">Jumlah</th>
<th width="100px">Total</th>
<th width="80px"></th>
</tr>
</thead>
<tbody id='itemlist' >
<tr>
<td><input id='nama' name='nama_input[]' class='form-control' /></td>
<td><input id='kode' readonly name='kode_input[]' class='form-control' /></td>
<td><input type="number" id='harga' name='harga_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input type="number" id='jumlah' autocomplete="off" name='jumlah_input[]' class='form-control' onkeyup="sum();" /></td>
<td><input id='total' name='total_input[]' class='form-control' value="" onkeyup="prosestotal();" /></td>
<td></td>
</tr>
</tbody>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td>
<button type="button" id="tambah" class="btn btn-default">
<b>Tambah</b>
</button>
</td>
</tr>
</table>
<!-- Baris biaya lain-lain -->
<div style="padding-top: 10px; padding-bottom: 15px;" class="col-lg-10">
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<label class="col-sm-6 control-label"><b>Biaya Lain-lain :</b></label>
</div>
</div>
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<input id="biayalain" type="number" autocomplete="off" class="form-control" name="biaya_lainlain" value="" onkeyup="prosestotal();">
</div>
</div>
</div>
<!-- baris biaya dan lain-lain end -->
<div style="padding-top: 10px; padding-bottom: 15px;" class="col-lg-10">
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<label class="col-sm-6 control-label"><b>Total Penjualan :</b></label>
</div>
</div>
<div class="row">
<div class="col-lg-4"></div>
<div class="col-lg-4"></div>
<div class="col-lg-4">
<input id="total_penjualan" type="number" readonly autocomplete="off" class="form-control" name="total_penjualan" value="" onkeyup="prosestotal();">
</div>
</div>
</div>
any help is appreciated