How to change value inside input box that generated by jQuery? - javascript

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>

Related

Why does the page reload when the button is pressed

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>

calculate grand total with javascript

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.

Jquery .on(change) event on <select> input only changes first row.

I have a table whereby people can add rows.
There is a select input in the table that when changed, changes the values in a second select field via ajax.
The problem I have is that if a person adds an additional row to the table, the .on(change) event alters the second field in the first row, not the subsequent row.
I've been racking my brain, trying to figure out if I need to (and if so how to) dynamically change the div id that the event binds to and the div that it affects. Is this the solution? If so, could someone please demonstrate how I'd achieve this?
The HTML form is
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<!--<td><input type="text" placeholder="First Name" name="contact[0][contact_first]"></td>
<td><input type="text" placeholder="Surname" name="contact[0][contact_surname]"></td>-->
<td><select name="asset[0][type]">
<option><?php echo $typeoption ?></option>
</select></td>
<td><select class="manuf_name" name="asset[0][manuf]">
<option><?php echo $manufoption ?></option>
</select></td>
<td><input type="text" placeholder="Serial #" name="asset[0][serial_num]"></td>
<td><input type="text" placeholder="Mac Address" name="asset[0][mac_address]"></td>
<td><input type="text" placeholder="Name or Description" name="asset[0][description]"></td>
<td><select id="site" name="asset[0][site]">
<option><?php echo $siteoption ?></option>
</select></td>
<td><input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]"></td>
<td><select id="new_select" name="asset[0][contact]"></select></td>
<!--<td><input type="email" placeholder="Email" name="contact[0][email]"></td>
<td><input type="phone" placeholder="Phone No." name="contact[0][phone]"></td>
<td><input type="text" placeholder="Extension" name="contact[0][extension]"></td>
<td><input type="phone" placeholder="Mobile" name="contact[0][mobile]"></td>-->
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
The script I have is
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function(){
this.name = this.name.replace(/\[(\d+)\]/,
function(str,p1) {
return '[' + (parseInt(p1,10)+1)+ ']'
})
})
return false;
});
});
$(document).ready(function() {
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last')
if ($last.is(':nth-child(2)')) {
alert('This is the only one')
} else {
$last.remove()
}
});
});
$(document).ready(function() {
$("#myassettable").on("change","#site",function(event) {
$.ajax ({
type : 'post',
url : 'assetprocess.php',
data: {
get_option : $(this).val()
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
})
});
});
</script>
and the assetprocess.php page is
<?php
if(isset($_POST['get_option'])) {
//Get the Site Contacts
$site = $_POST['get_option'];
$contact = "SELECT site_id, contact_id, AES_DECRYPT(contact_first,'" .$kresult."'),AES_DECRYPT(contact_surname,'" .$kresult."') FROM contact WHERE site_id = '$site' ORDER BY contact_surname ASC";
$contactq = mysqli_query($dbc,$contact) or trigger_error("Query: $contact\n<br />MySQL Error: " .mysqli_errno($dbc));
if ($contactq){
//$contactoption = '';
echo '<option>Select a Contact (Optional)</option>';
while ($contactrow = mysqli_fetch_assoc($contactq)) {
$contactid = $contactrow['contact_id'];
$contactfirst = $contactrow["AES_DECRYPT(contact_first,'" .$kresult."')"];
$contactsurname = $contactrow["AES_DECRYPT(contact_surname,'" .$kresult."')"];
$contactoption .= '<option value="'.$contactid.'">'.$contactsurname.', '.$contactfirst.'</option>';
echo $contactoption;
}
}
exit;
}
?>
The code is ugly as sin, but this is only a self-interest project at this stage.
Any assistance would be greatly appreciated.
Cheers,
J.
Working Example: https://jsfiddle.net/Twisty/1c98Ladh/3/
A few minor HTML changes:
<form action="assets.php" method="post">
<button type="button" id="add">Add Row</button>
<button type="button" id="delete">Remove Row</button>
<table id="myassettable">
<tbody>
<tr>
<th>Asset Type</th>
<th>Manufacturer</th>
<th>Serial #</th>
<th>MAC Address</th>
<th>Description</th>
<th>Site</th>
<th>Location</th>
</tr>
<tr class="removable">
<td>
<select name="asset[0][type]">
<option>---</option>
<option>Type Option</option>
</select>
</td>
<td>
<select class="manuf_name" name="asset[0][manuf]">
<option>---</option>
<option>
Manuf Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="Serial #" name="asset[0][serial_num]">
</td>
<td>
<input type="text" placeholder="Mac Address" name="asset[0][mac_address]">
</td>
<td>
<input type="text" placeholder="Name or Description" name="asset[0][description]">
</td>
<td>
<select id="site-0" class="chooseSite" name="asset[0][site]">
<option>---</option>
<option>
Site Option
</option>
</select>
</td>
<td>
<input type="text" placeholder="e.g Level 3 Utility Room" name="asset[0][location]">
</td>
<td>
<select id="new-site-0" name="asset[0][contact]">
</select>
</td>
</tr>
</tbody>
</table>
<input type="submit" value="Submit">
<input type="hidden" name="submitted" value="TRUE" />
</form>
This prepares the id to be incrementd as we add on new elements. Making use of the class, we can bind a .change() to each of them.
$(document).ready(function() {
$("#add").click(function() {
var newgroup = $('#myassettable tbody>tr:last');
newgroup
.clone(true)
.find("input").val("").end()
.insertAfter('#myassettable tbody>tr:last')
.find(':input')
.each(function() {
this.name = this.name.replace(/\[(\d+)\]/,
function(str, p1) {
return '[' + (parseInt(p1, 10) + 1) + ']';
});
});
var lastId = parseInt(newgroup.find(".chooseSite").attr("id").substring(5), 10);
newId = lastId + 1;
$("#myassettable tbody>tr:last .chooseSite").attr("id", "site-" + newId);
$("#myassettable tbody>tr:last select[id='new-site-" + lastId + "']").attr("id", "new-site-" + newId);
return false;
});
$("#delete").click(function() {
var $last = $('#myassettable tbody').find('tr:last');
if ($last.is(':nth-child(2)')) {
alert('This is the only one');
} else {
$last.remove();
}
});
$(".chooseSite").change(function(event) {
console.log($(this).attr("id") + " changed to " + $(this).val());
var target = "new-" + $(this).attr('id');
/*$.ajax({
type: 'post',
url: 'assetprocess.php',
data: {
get_option: $(this).val()
},
success: function(response) {
$("#" + target).html(response);
}
});*/
var response = "<option>New</option>";
$("#" + target).html(response);
});
});
Can save some time by setting a counter in global space for the number of Rows, something like var trCount = 1; and use that to set array indexes and IDs. Cloning is fast and easy, but it also means we have to go back and append various attributes. Could also make a function to draw up the HTML for you. Like: https://jsfiddle.net/Twisty/1c98Ladh/10/
function cloneRow(n) {
if (n - 1 < 0) return false;
var html = "";
html += "<tr class='removable' data-row=" + n + ">";
html += "<td><select name='asset[" + n + "][type]' id='type-" + n + "'>";
html += $("#type-" + (n - 1)).html();
html += "<select></td>";
html += "<td><select name='asset[" + n + "][manuf]' id='manuf-" + n + "'>";
html += $("#manuf-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='Serial #' name='asset[" + n + "][serial_num]' id='serial-" + n + "' /></td>";
html += "<td><input type='text' placeholder='MAC Address' name='asset[" + n + "][mac_address]' id='mac-" + n + "' /></td>";
html += "<td><input type='text' placeholder='Name or Desc.' name='asset[" + n + "][description]' id='desc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][site]' class='chooseSite' id='site-" + n + "'>";
html += $("#site-" + (n - 1)).html();
html += "<select></td>";
html += "<td><input type='text' placeholder='E.G. Level 3 Utility Room' name='asset[" + n + "][location]' id='loc-" + n + "' /></td>";
html += "<td><select name='asset[" + n + "][contact]' id='contact-" + n + "'><select></td>";
html += "</tr>";
return html;
}
It's more work up front, yet offers a lot more control of each part. And much easier to use later.

Adding to a value declared in another function

It is hard to explain, you can see a DEMO HERE
I have a products table that dynamically creates/deletes new lines of products. I also have a totals table that totals up the totals of each line together.
In that totals box, I have a travel box I want to add to the grand total, but the issue I am having is the travel input is outside the table that is totaling all the values. I can replace the total with a new total, but I can not seem to call the sub total, add the travel and output a grand total.
HTML
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
<td> </td>
</tr>
</tbody>
</table>
<div class="wei-add-service">Add Item</div>
<table class="wei-add-totals">
<tr>
<td width="50%">Sub Total</td>
<td width="50%" class="wie-add-subtotal"> </td>
</tr>
<tr class="alternate travel">
<td>Travel</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field travel" /></td>
</tr>
<tr>
<td>Taxes</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-total-taxes" id="wei-disabled" disabled/> </td>
</tr>
<tr class="alternate total">
<td>Total</td>
<td><input type="text" value="" placeholder="0.00" class="wei-add-field wie-grand-total" id="wei-disabled" disabled/></td>
</tr>
</table>
Javascript
var counter = 1;
var testArray = [ 2,3,4,5];
jQuery('a.wei-add-service-button').click(function(event){
event.preventDefault();
counter++;
var newRow = jQuery('<tr><td><input type="text" class="wei-add-field description ' + counter + '"/></td><td><input type="text" class="wei-add-field quantity ' + counter + '" /></td><td><input type="text" class="wei-add-field unit-price ' + counter + '"/></td><td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total ' + counter + '" id=""/></td><td>X</td></tr>');
jQuery('table.order-details').append(newRow);
});
jQuery('table.order-details').on('click','tr a',function(e){
e.preventDefault();
var table = $(this).closest('table');
jQuery(this).parents('tr').remove();
reCalculate.call( table );
});
jQuery('table.order-details').on("keyup", "tr", reCalculate);
function reCalculate() {
var grandTotal = 0;
jQuery(this).closest('table').find('tr').each(function() {
var row = jQuery(this);
var value = +jQuery( ".unit-price", row ).val();
var value2 = +jQuery( ".quantity", row ).val();
var total = value * value2;
grandTotal += total;
jQuery( ".wei-add-field.price-total", row ).val( '$' + total.toFixed(2) );
});
jQuery(".wie-add-subtotal").text( '$' + grandTotal.toFixed(2));
}
I don't think, given the task of creating this, I would have chosen to do it in the way you did.
However, using your existing code you can bind the Travel value on change, paste, or keyup and run a function on any of those actions. Within that function I have removed the special character ($) from ".wie-grand-total" using a regex and converted the value of ".wie-grand-total" to a float using parseFloat. I also converted the Travel value to a float using parseFloat. I then added them together and made the sum your new value for "wie-grand-total".
/* NEW SINCE COMMENTS */
//Add to your HTML New table
<table class="order-details">
<tbody>
<tr>
<td><input type="text" value="" name="" placeholder="Work Description" class="wei-add-field description 1"/></td>
<td><input type="text" value="" name="" placeholder="QTY" class="wei-add-field quantity 1" /></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field unit-price 1"/></td>
<td><input type="text" value="" name="" placeholder="$0.00" class="wei-add-field price-total 1" id=""/></td>
/* NEW SINCE COMMENTS*/
<td><input type="text" id="travelHid" value=""></td>
<td> </td>
</tr>
</tbody>
</table>
/* NEW SINCE COMMENTS */
$('#travelHid').hide();
var travelVal = 0;
function updateTravelVal(travelVal){
var travelVal = travelVal;
$('#travelHid').val(travelVal);
};
updateTravelVal();
$("#travelVis").bind("change paste keyup", function() {
var noChars = jQuery(".wie-grand-total").val().replace(/[^0-9.]/g, "");
var newTot = parseFloat(noChars) + parseFloat($(this).val());
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//added error checking
var checkError = jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2));
//if the value that would go in input is NaN then use travelVal
//since there is no value in .wie-grand-total yet
if (typeof checkError !== "string") {
jQuery(".wie-grand-total").val( '$' + travelVal.toFixed(2))
} else if (typeof checkError === "string") {
jQuery(".wie-grand-total").val( '$' + newTot.toFixed(2))
}
/* NEW SINCE COMMENTS */
updateTravelVal(travelVal);
});
A fiddle for demonstration (now with hiddenVal per comment)
http://jsfiddle.net/chrislewispac/wed6eog0/3/
Only potential problems here are it only runs when you change, paste, or key up the value in #TravelVis.
/EXPLAINED SINCE COMMENTS/
It the html I added a td with input. Input id="travelHid". I then make that invisible by applying jQuery method .hide(). I then exposed travelVal to global scope an initiated it with a value of zero then created a function to update that value.
Within that function I set the value to the argument travelVal or to 0 if there are no args. I then immediately call it.
Then, I added a call to that function with the arg travelVal from our bind function to update it if a value is present.
And finally:
Just add a row to the table with preset value of Travel and Quant 1.
http://jsfiddle.net/chrislewispac/xntn7p5p/5/

using selector to enable/disable input text with jquery

Thank "Abhishek Jain", "rps", "adeneo" for your code.
this help me to resolved it.
I have problem with below code:
HTML
<table cellpadding="0" cellspacing="0" width="100%" class="table" id="addtable" border="1">
<thead>
<tr>
<th width="4%"><b>Date</b></th>
<th width="4%"><b>Cut Number</b></th>
<th width="4%"><b>Content</b></th>
<th width="4%"><b>Others</b></th>
<th width="5%"><b>Customer name</b></th>
<th width="4%"><b>Customer code</b></th>
<th width="5%"><b>Address</b></th>
<th width="5%"><b>Owe amount</b></th>
<th width="4%"><b>Executive</b></th>
<th width="6%"><b>Obtain Amount</b></th>
<th width="9%"><b>Obtain Room</b></th>
</tr>
</thead>
<tbody>
<tr id="addrow">
<td><input name="date[]" id="mask_dm1" type="text" size="1" value=""></td>
<td><input name="cutno[]" type="text" size="6" ></td>
<td>
<select name="cutcontent[]" id="selector">
<option value="0">Please select</option>
<option value="1">Value 1</option>
<option value="2">Value 2</option>
<option value="3">Value 3</option>
<option value="other">Other</option>
</select>
</td>
<td><input name="cutother[]" type="text" size="4" id="cutother" disabled /></td>
<td><input name="cusname[]" type="text" size="4" ></td>
<td><input name="cuscode[]" type="text" size="2" ></td>
<td><input name="cusaddress[]" type="text" size="4" ></td>
<td><input name="owe[]" type="text" size="2" id="cutowe" disabled /></td>
<td><input name="executive[]" type="text" size="1" /></td>
<td><input name="obtainamount[]" type="text" size="2" id="obtainamount" disabled /></td>
<td><input name="obtainroom[]" type="text" size="2" id="obtainroom" disabled /></td>
</tr>
</tbody>
Javascript:
$(document).ready(function () {
var clonedRow = ' <td><input name="date[]" id="mask_dm1" type="text" size="1" value=""></td>';
clonedRow += ' <td><input name="cutno[]" type="text" size="6" ></td>';
clonedRow += ' <td>';
clonedRow += ' <select name="cutcontent[]" id="selector">';
clonedRow += ' <option value="0">Please select</option>';
clonedRow += ' <option value="1">Value 1</option>';
clonedRow += ' <option value="2">Value 2</option>';
clonedRow += ' <option value="3">Value 3</option>';
clonedRow += ' <option value="other">Other</option>';
clonedRow += ' </select>';
clonedRow += ' </td>';
clonedRow += ' <td><input name="cutother[]" type="text" size="4" id="cutother" disabled /></td>';
clonedRow += ' <td><input name="cusname[]" type="text" size="4" ></td>';
clonedRow += ' <td><input name="cuscode[]" type="text" size="2" ></td>';
clonedRow += ' <td><input name="cusaddress[]" type="text" size="4" ></td>';
clonedRow += ' <td><input name="owe[]" type="text" size="2" id="cutowe" disabled /></td>';
clonedRow += ' <td><input name="executive[]" type="text" size="1" /></td>';
clonedRow += ' <td><input name="obtainamount[]" type="text" size="2" id="obtainamount" disabled /></td>';
clonedRow += ' <td><input name="obtainroom[]" type="text" size="2" id="obtainroom" disabled /></td>';
var appendRow = '<tr id="addrow">' + clonedRow + '</tr>';
$('#btnAddMore').click(function () {
$('#addtable tr:last').after(appendRow);
$('select#selector').change(function () {
var theVal = $(this).val();
switch (theVal) {
case '1':
$('input#cutowe').removeAttr('disabled');
$('input#obtainamount').removeAttr('disabled');
$('input#obtainroom').removeAttr('disabled');
break;
case '2':
$('input#cutother').removeAttr('disabled');
break;
default:
$('input#cutowe').attr('disabled', 'disabled');
$('input#obtainamount').attr('disabled', 'disabled');
$('input#obtainroom').attr('disabled', 'disabled');
$('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
$('select#selector').change(function () {
var theVal = $(this).val();
switch (theVal) {
case '1':
$('input#cutowe').removeAttr('disabled');
$('input#obtainamount').removeAttr('disabled');
$('input#obtainroom').removeAttr('disabled');
break;
case '2':
$('input#cutother').removeAttr('disabled');
break;
default:
$('input#cutowe').attr('disabled', 'disabled');
$('input#obtainamount').attr('disabled', 'disabled');
$('input#obtainroom').attr('disabled', 'disabled');
$('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
When I press "Add more row" button, the selector named "Content" at row#2 has effect on the all input.
how to resolve it?
see example http://jsfiddle.net/N2jyy/6/
Check this;
$(document).ready(function(){
$('#btnAddMore').click(function(){
$('#addtable tr:last').after($('#addtable tr:last').clone());
$('#addtable tr').each(function(){
var currentTR = $(this);
$(this).find('select#selector').change(function(){
var theVal = $(this).val();
switch(theVal){
case '1':
$(currentTR).find('input#cutowe').removeAttr('disabled');
$(currentTR).find('input#obtainamount').removeAttr('disabled');
$(currentTR).find('input#obtainroom').removeAttr('disabled');
break;
case '2':
$(currentTR).find('input#cutother').removeAttr('disabled');
break;
default:
$(currentTR).find('input#cutowe').attr('disabled', 'disabled');
$(currentTR).find('input#obtainamount').attr('disabled', 'disabled');
$(currentTR).find('input#obtainroom').attr('disabled', 'disabled');
$(currentTR).find('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
});
$('#addtable tr').each(function(){
var currentTR = $(this);
$(this).find('select#selector').change(function(){
var theVal = $(this).val();
switch(theVal){
case '1':
$(currentTR).find('input#cutowe').removeAttr('disabled');
$(currentTR).find('input#obtainamount').removeAttr('disabled');
$(currentTR).find('input#obtainroom').removeAttr('disabled');
break;
case '2':
$(currentTR).find('input#cutother').removeAttr('disabled');
break;
default:
$(currentTR).find('input#cutowe').attr('disabled', 'disabled');
$(currentTR).find('input#obtainamount').attr('disabled', 'disabled');
$(currentTR).find('input#obtainroom').attr('disabled', 'disabled');
$(currentTR).find('input#cutother').attr('disabled', 'disabled');
break;
}
});
});
});
Fiddle
After changing the id to class
$(document).ready(function () {
$('#btnAddMore').click(function () {
$('#addtable tr:last').after($('#addtable tr:last').clone(true));
$('select.selector').change(function () {
var theVal = $(this).val();
switch (theVal) {
case '1':
$(this).parents('tr').find('input.cutowe,input.obtainamount,nput.obtainroom').removeAttr('disabled');
break;
case '2':
$(this).parents('tr').find('input.cutowe,input.obtainamount,input.obtainroom,input.cutother').attr('disabled', 'disabled');
break;
}
});
});
});
The above code can be reduced to even more, but this should give you a start on knowing few things, like it is a bad idea to have the same ids and how you can access the other columns from current
http://jsfiddle.net/N2jyy/9/
Change all the duplicate ID's to classes, and use a delegated event handler to handle the change event on the select elements.
What you need to make each select only change the elements withing the same row is context, you'd do that like so:
$('#btnAddMore').on('click', function () {
$('#addtable tr:last').after(appendRow);
});
$('#addtable').on('change', '.selector', function () {
var theVal = $(this).val(),
tr = $(this).closest('tr');
switch (theVal) {
case '1':
$('.cutowe, .obtainamount, .obtainroom', tr).prop('disabled', false);
break;
case '2':
$('.cutother', tr).prop('disabled', false);
break;
default:
$('.cutowe, .obtainamount, .obtainroom, .cutother', tr).prop('disabled', true);
break;
}
});
FIDDLE
I upgraded the jQuery version, and if you're seriously using jQuery 1.3, so should you.

Categories

Resources