How to sum dynamically added column values? - javascript

I have dynamically added rows that I need to sum.
Added columns and total will be displayed in separate fields.
I want to sum user enter data one particular column that is "DEBIT*" columns. for example user enter 1st row on debit coloumn 100rs and user click add new row and enter 100rs that amount will be calculate and show the total field..
Here is my code.
Faild Fiddle here
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cashacc = 'cashacc' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' placeholder="NNNN" /></td><td><select class="form-control" id="cashacc" ><option value="">TDS A/C Name1</option><option value="1">Joe</option><option value="2">Joe</option><option value="3">Joe</option></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
/* second row */
var ctr = 1;
var FieldCount = 1;
$('#sndRow').on('click', '.button-add', function() {
ctr++;
var rowNum = 'rowNum' + ctr;
var cashacc_nme = 'cashacc_nme' + ctr;
var acc_narrat = 'acc_narrat' + ctr;
var accdeb = 'accdeb' + ctr;
var accCredit = 'accCredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + rowNum + ' placeholder="NNNN" /></td><td><select class="form-control" id="cashacc_nme" ><option value="">Account Name 1</option><option value="1">Plumz</option><option value="2">Plumz</option><option value="3">Plumz</option></select></td><td><input type="text" class=' + "joe" + ' id=' + acc_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe debClass" + ' id=' + accdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + accCredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<thead>
<tr>
<th>A/c Code</th>
<th>Account Name*</th>
<th>Narration*</th>
<th>Debit*</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td>
<input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" class="form-control" name="cashdeb" readonly />
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly />
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
<tr id="sndRow">
<td>
<input type="number" class="form-control" id="rowNum" name="cashaccCode" placeholder="NNNN" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc_nme" id="cashacc_nme">
<option value="#">Choose and items</option>
<option value="1">Joe</option>
<option value="2">Joe2</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" class="form-control debClass" id="accdeb" placeholder="NNNNNN" name="accdeb" />
</td>
<td>
<input type="number" id="accCredit" class="form-control" name="accCredit" readonly />
</td>
<td style="width: 4%">
<img src="./img/plus.svg" id="debsum" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon">
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="totaldbt" readonly>
</div>
</div>
I am just beginner, any help would be grateful.
Thank you.

EDIT: I'm sorry Joe, it looks like I attached your fiddle to the link other than my updated copy. Please check the link out again.
I've created a JSfiddle using yours for a working example.
I modified your code to make it easier by adding an attribute on your debit input of data-action="sumDebit" and added in this snippet.
$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
var total = 0;
$('[data-action="sumDebit"]').each(function(i,e) { //Get all tags with [data-action="sumDebit"]
var val = parseFloat(e.value); //Get int value from string
if(!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
total += val;
});
$('#totaldbt').val(total); //Update value to total
});

I have fixed your code. please check it.
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cashacc = 'cashacc' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' name="cashaccCode" onchange="calSum()" keyup="calSum()" placeholder="NNNN" /></td><td><select class="form-control" id="cashacc" ><option value="">TDS A/C Name1</option><option value="1">Joe</option><option value="2">Joe</option><option value="3">Joe</option></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
/* second row */
var ctr = 1;
var FieldCount = 1;
$('#sndRow').on('click', '.button-add', function() {
ctr++;
var rowNum = 'rowNum' + ctr;
var cashacc_nme = 'cashacc_nme' + ctr;
var acc_narrat = 'acc_narrat' + ctr;
var accdeb = 'accdeb' + ctr;
var accCredit = 'accCredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + rowNum + ' name="cashaccCode" onchange="calSum()" keyup="calSum()" placeholder="NNNN" /></td><td><select class="form-control" id="cashacc_nme" ><option value="">Account Name 1</option><option value="1">Plumz</option><option value="2">Plumz</option><option value="3">Plumz</option></select></td><td><input type="text" class=' + "joe" + ' id=' + acc_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe debClass" + ' id=' + accdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + accCredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<tbody>
<tr id="fst_row">
///First row
<td>
<input type="number" onchange="calSum()" keyup="calSum()" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashaccCode" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" class="form-control" name="cashdeb" readonly />
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly />
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
//// second row
<tr id="sndRow">
<td>
<input type="number" onchange="calSum()" keyup="calSum()" class="form-control" id="rowNum" name="cashaccCode" placeholder="NNNN" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc_nme" id="cashacc_nme">
<option value="#">Choose and items</option>
<option value="1">Joe</option>
<option value="2">Joe2</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" class="form-control debClass" id="accdeb" placeholder="NNNNNN" name="accdeb" />
</td>
<td>
<input type="number" id="accCredit" class="form-control" name="accCredit" readonly />
</td>
<td style="width: 4%">
<img src="./img/plus.svg" id="debsum" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon">
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="totaldbt" readonly>
</div>
</div>
<script>
function calSum(){
var calvalue = 0;
$("input[name*='cashaccCode']").each( function( key, item ) {
//alert( key + ": " + item.value );
calvalue = calvalue + parseFloat(item.value);
});
$("#totaldbt").val(calvalue);
$
}
</script>

Related

Change data format in CRUD output to dd/mm/yyy [duplicate]

This question already has answers here:
How do I format a date in JavaScript?
(68 answers)
Closed 4 months ago.
i know it's a question asked many times here, but i tried all the solutions and no one is working.
I want to change the output in my CRUD from the input form to dd/mm/yyyy and not in yyyy-mm-dd.
Here's my code:
var nextId = 1;
var activeId = 0;
function productDisplay(ctl) {
var row = $(ctl).parents("tr");
var cols = row.children("td");
activeId = $($(cols[0]).children("button")[0]).data("id");
$("#productname").val($(cols[1]).text());
$("#introdate").val($(cols[2]).text());
$("#finishdate").val($(cols[3]).text());
$("#url").val($(cols[4]).text());
$("#phone").val($(cols[5]).text());
$("#note").val($(cols[6]).text());
$("#client").val($(cols[7]).text());
$("#updateButton").text("Aggiorna");
}
function productUpdate() {
if ($("#updateButton").text() == "Add") {
productUpdateInTable(activeId);
}
else {
productAddToTable();
}
formClear();
$("#productname").focus();
}
function productAddToTable() {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(
productBuildTableRow(nextId));
nextId += 1;
}
function productUpdateInTable(id) {
var row = $("#productTable button[data-id='" + id + "']")
.parents("tr")[0];
$(row).after(productBuildTableRow(id));
$(row).remove();
formClear();
$("#updateButton").text("Add");
}
function productBuildTableRow(id) {
var ret =
"<tr>" +
"<td>" +
"<button type='button' " +
"onclick='productDisplay(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-pencil' />" +
"</button>" +
"</td>" +
"<td>" + $("#productname").val() + "</td>" +
"<td>" + $("#introdate").val() + "</td>" +
"<td>" + $("#finishdate").val() + "</td>" +
"<td>" + $("#url").val() + "</td>" +
"<td>" + $("#phone").val() + "</td>" +
"<td>" + $("#note").val() + "</td>" +
"<td>" + $("#client").val() + "</td>" +
"<td>" +
"<button type='button' " +
"onclick='productDelete(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-minus' />" +
"</button>" +
"</td>" +
"</tr>"
return ret;
}
function productDelete(ctl) {
var result = confirm("Want to delete record?");
if (result) {
var result2 = confirm("Really?");
}
if (result2) {
$(ctl).parents("tr").remove();
}
}
function formClear() {
$("#productname").val("");
$("#introdate").val("");
$("#finishdate").val("");
$("#url").val("");
$("#phone").val("");
$("#note").val("");
$("#client").val("");
}
function doSearch(text, color = "yellow") {
if (color != "transparent") {
doSearch(document.getElementById('hid_search').value, "transparent");
document.getElementById('hid_search').value = text;
}
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<h2><b>Availability</h2></b>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="col-sm-0">Modify</th>
<th class="col-sm-2">Name</th>
<th class="col-sm-1">From</th>
<th class="col-sm-1">To</th>
<th class="col-sm-2">Area</th>
<th class="col-sm-2">Phone</th>
<th class="col-sm-3">Note</th>
<th class="col-sm-2">Client</th>
<th class="col-sm-0">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
Add Availability
</div>
<div class="panel-body">
<div class="form-group">
<label for="productname">
Name
</label>
<input type="text" class="form-control" value="" id="productname" />
</div>
<div class="form-group">
<label for="introdate">
From
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="introdate">
</div>
<div class="form-group">
<label for="introdate">
To
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="finishdate" />
</div>
<div class="form-group">
<label for="area">
Area
</label>
<input type="search" class="form-control" value="" id="url" />
</div>
<div class="form-group">
<label for="phone">
Phone
</label>
<input type="" class="form-control" value="" id="phone" />
</div>
<div class="form-group">
<label for="note">
Note
</label>
<input type="" class="form-control" value="" id="note" />
</div>
<div class="form-group">
<label for="client">
Client
</label>
<select id="client" class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-xs-12">
<button type="button" id="updateButton" class="btn btn-primary" onclick="productUpdate();">
Add
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
When I insert a new record from form field date, the output in my CRUD is like YYYY-MM-DD.
This should help you. Pass a valid date in any format and the function will return a dd/mm/yyyy date format
// Helper function to format date from $(input).val()
function formatDate(date) {
if (date == '') {
return '';
}
let d = new Date(date),
ye = new Intl.DateTimeFormat('en', {
year: 'numeric'
}).format(d),
mo = new Intl.DateTimeFormat('en', {
month: '2-digit'
}).format(d),
da = new Intl.DateTimeFormat('en', {
day: '2-digit'
}).format(d);
return (`${da}-${mo}-${ye}`);
}
// ----
var nextId = 1;
var activeId = 0;
function productDisplay(ctl) {
var row = $(ctl).parents("tr");
var cols = row.children("td");
activeId = $($(cols[0]).children("button")[0]).data("id");
$("#productname").val($(cols[1]).text());
$("#introdate").val($(cols[2]).text());
$("#finishdate").val($(cols[3]).text());
$("#url").val($(cols[4]).text());
$("#phone").val($(cols[5]).text());
$("#note").val($(cols[6]).text());
$("#client").val($(cols[7]).text());
$("#updateButton").text("Aggiorna");
}
function productUpdate() {
if ($("#updateButton").text() == "Add") {
productUpdateInTable(activeId);
}
else {
productAddToTable();
}
formClear();
$("#productname").focus();
}
function productAddToTable() {
if ($("#productTable tbody").length == 0) {
$("#productTable").append("<tbody></tbody>");
}
$("#productTable tbody").append(
productBuildTableRow(nextId));
nextId += 1;
}
function productUpdateInTable(id) {
var row = $("#productTable button[data-id='" + id + "']")
.parents("tr")[0];
$(row).after(productBuildTableRow(id));
$(row).remove();
formClear();
$("#updateButton").text("Add");
}
function productBuildTableRow(id) {
var ret =
"<tr>" +
"<td>" +
"<button type='button' " +
"onclick='productDisplay(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-pencil' />" +
"</button>" +
"</td>" +
"<td>" + $("#productname").val() + "</td>" +
"<td>" + formatDate($("#introdate").val()) + "</td>" + // call helper function
"<td>" + formatDate($("#finishdate").val()) + "</td>" + // call helper function
"<td>" + $("#url").val() + "</td>" +
"<td>" + $("#phone").val() + "</td>" +
"<td>" + $("#note").val() + "</td>" +
"<td>" + $("#client").val() + "</td>" +
"<td>" +
"<button type='button' " +
"onclick='productDelete(this);' " +
"class='btn btn-default' " +
"data-id='" + id + "'>" +
"<span class='glyphicon glyphicon-minus' />" +
"</button>" +
"</td>" +
"</tr>"
return ret;
}
function productDelete(ctl) {
var result = confirm("Want to delete record?");
if (result) {
var result2 = confirm("Really?");
}
if (result2) {
$(ctl).parents("tr").remove();
}
}
function formClear() {
$("#productname").val("");
$("#introdate").val("");
$("#finishdate").val("");
$("#url").val("");
$("#phone").val("");
$("#note").val("");
$("#client").val("");
}
function doSearch(text, color = "yellow") {
if (color != "transparent") {
doSearch(document.getElementById('hid_search').value, "transparent");
document.getElementById('hid_search').value = text;
}
if (window.find && window.getSelection) {
document.designMode = "on";
var sel = window.getSelection();
sel.collapse(document.body, 0);
while (window.find(text)) {
document.execCommand("HiliteColor", false, color);
sel.collapseToEnd();
}
document.designMode = "off";
} else if (document.body.createTextRange) {
var textRange = document.body.createTextRange();
while (textRange.findText(text)) {
textRange.execCommand("BackColor", false, color);
textRange.collapse(false);
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<div class="row">
<div class="col-sm-6">
<h2><b>Availability</h2></b>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<table id="productTable" class="table table-bordered table-condensed table-striped">
<thead>
<tr>
<th class="col-sm-0">Modify</th>
<th class="col-sm-2">Name</th>
<th class="col-sm-1">From</th>
<th class="col-sm-1">To</th>
<th class="col-sm-2">Area</th>
<th class="col-sm-2">Phone</th>
<th class="col-sm-3">Note</th>
<th class="col-sm-2">Client</th>
<th class="col-sm-0">Delete</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="row">
<div class="col-sm-5">
<div class="panel panel-primary">
<div class="panel-heading">
Add Availability
</div>
<div class="panel-body">
<div class="form-group">
<label for="productname">
Name
</label>
<input type="text" class="form-control" value="" id="productname" />
</div>
<div class="form-group">
<label for="introdate">
From
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="introdate">
</div>
<div class="form-group">
<label for="introdate">
To
</label>
<input type="date" class="form-control" value="gg/mm/aaaa" id="finishdate" />
</div>
<div class="form-group">
<label for="area">
Area
</label>
<input type="search" class="form-control" value="" id="url" />
</div>
<div class="form-group">
<label for="phone">
Phone
</label>
<input type="" class="form-control" value="" id="phone" />
</div>
<div class="form-group">
<label for="note">
Note
</label>
<input type="" class="form-control" value="" id="note" />
</div>
<div class="form-group">
<label for="client">
Client
</label>
<select id="client" class="form-control">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
</select>
</div>
<div class="panel-footer">
<div class="row">
<div class="col-xs-12">
<button type="button" id="updateButton" class="btn btn-primary" onclick="productUpdate();">
Add
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>

Accessing Element previously appended to the DOM?

I have the following HTML structure in two modals on my website - one for adding new datasets and one for editing existing datasets:
HTML (add) is added to the DOM via TWIG Syntax
<div class="mb-3" id="bar_area-add">
<div class="card">
<div class="card-body">
<h3 class="float-start">Thekendienst</h3>
<div class="float-end">
<button class="btn btn-sm btn-primary" type="button" id="bar_plus-add">
<i class="bi-plus-lg"></i>
</button>
<button class="btn btn-sm btn-danger" type="button" id="bar_minus-add">
<i class="bi-dash-lg"></i>
</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Zeitfenster</th>
<th>MAs</th>
</tr>
</thead>
<tbody id="bar_multiple-add">
<tr id="bar_placeholder-add" style="display: none;">
<td colspan="2">aktuell keine Position(en) verfügbar</td>
</tr>
<tr id="bar_shift_1-add">
<td><input type="text" name="bar_timewindow_1" value="21:00-24:00" required=""></td>
<td><input type="number" min="0" name="bar_amountma_1" value="2" required=""></td>
<input type="hidden" name="bar_id_1" value="3" required="">
</tr>
</tbody>
</table>
</div>
</div>
</div>
HTML (edit) is appended to the DOM via JQuery.append() function
<div class="mb-3" id="bar_area-edit" style="">
<div class="card">
<div class="card-body">
<h3 class="float-start">Thekendienst</h3>
<div class="float-end">
<button class="btn btn-sm btn-primary" type="button" id="bar_plus-edit">
<i class="bi-plus-lg"></i>
</button>
<button class="btn btn-sm btn-danger" type="button" id="bar_minus-edit">
<i class="bi-dash-lg"></i>
</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Zeitfenster</th>
<th>MAs</th>
</tr>
</thead>
<tbody id="bar_multiple-edit">
<tr id="bar_placeholder-edit" style="display: none;">
<td colspan="2">aktuell keine Position(en) verfügbar</td>
</tr>
<tr id="bar_shift_1-edit">
<td><input type="text" name="bar_timewindow_1" value="21:00-24:00" required=""></td>
<td><input type="number" min="0" name="bar_amountma_1" value="2" required=""></td>
<input type="hidden" name="bar_id_1" value="3" required="">
</tr>
</tbody>
</table>
</div>
</div>
</div>
As you can see, I also have 2 Buttons in both structures to add oder remove lines - it´s a kind of dynamic formfield. For this purpose I have written the following JQuery-Function:
var tasks = ['add', 'edit'];
var services = {{ services | json_encode | raw }};
tasks.forEach(task => {
services.forEach(service => {
$("#" + service.shortname + "_plus-" + task).click(function () {
$("#" + service.shortname + "_multiple-" + task).each(function () {
var i = $(this).find("tr").length;
var n = (i - 1);
$(this).append('<tr id="' + service.shortname + '_shift_' + (n + 1) + '-' + task + '">\n' +
'<td><input type="text" name="' + service.shortname + '_timewindow_' + (n + 1) + '" value="00:00-00:00" required></td>\n' +
'<td><input type="number" min="0" name="' + service.shortname + '_amountma_' + (n + 1) + '" value="0" required></td>\n' +
'</tr><input type="hidden" name="' + service.shortname + '_id_' + (n + 1) + '" value="' + service.id + '" required>');
if (n === 0) {
$("#" + service.shortname + "_placeholder-" + task).hide();
}
});
});
$("#" + service.shortname + "_minus-" + task).click(function () {
$("#" + service.shortname + "_multiple-" + task).each(function () {
var i = $(this).find("tr").length;
var n = i;
if (n !== 0) {
$("#" + service.shortname + '_shift_' + (n - 1) + '-' + task).remove();
if (n === 2) {
$("#" + service.shortname + "_placeholder-" + task).show();
}
}
});
});
});
});
Unfortunately this only works for the add-task, when clicking on add/remove button in the edit modal nothing happens. There´s no error message. I think this could be a result of adding edit-structure with Jquery.append() to the DOM like this.
$.ajax({
url: '/getJobs/' + eventClickEvent.event.id,
type: 'get',
success: function (jobData) {
var jobs = JSON.parse(jobData);
var services = {{ services | json_encode | raw }};
services.forEach(service => {
$('#areas-edit').append(`<div class="mb-3" id="` + service.shortname + `_area-edit" style="display: none;">
<div class="card">
<div class="card-body">
<h3 class="float-start">` + service.name + `</h3>
<div class="float-end">
<button class="btn btn-sm btn-primary" type="button"
id="` + service.shortname + `_plus-edit">
<i class="bi-plus-lg"></i>
</button>
<button class="btn btn-sm btn-danger" type="button"
id="` + service.shortname + `_minus-edit">
<i class="bi-dash-lg"></i>
</button>
</div>
<table class="table table-striped">
<thead>
<tr>
<th>Zeitfenster</th>
<th>MAs</th>
</tr>
</thead>
<tbody id="` + service.shortname + `_multiple-edit">
<tr id="` + service.shortname + `_placeholder-edit">
<td colspan="2">aktuell keine Position(en) verfügbar</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>`);
var i = 1;
jobs.forEach(job => {
if (service.id === job.serviceId) {
$('#' + service.shortname + '-editPill').addClass('bg-primary');
$('#' + service.shortname + '-editPill').removeClass('bg-secondary');
$('#' + service.shortname + '_area-edit').show();
$('#' + service.shortname + '_placeholder-edit').hide();
$('#' + service.shortname + '_multiple-edit').append(`
<tr id="` + service.shortname + `_shift_` + i + `-edit">
<td><input type="text"
name="` + service.shortname + `_timewindow_` + i + `"
value="` + job.timewindow + `" required></td>
<td><input type="number" min="0"
name="` + service.shortname + `_amountma_` + i + `"
value="` + job.mas + `" required></td>
<input type="hidden" name="` + service.shortname + `_id_` + i + `"
value="` + service.id + `" required>
</tr>
`);
i++;
}
});
});
}
});
You have jQuery, use it. Delegate or something like this
$(".service").on("click", function() {
$(".task", this).each(function() {
if (this.id.includes("plus")) {
var len = $(this).find("tr").length;
...
}
if (n === 0) {
$(this).find("[id*='_placeholder-']).hide();
}
})
}
else if (this.id.includes("_multiple") {
...
}
});
});

How to access parent element and then get it's value and then append to other element when adding a row?

My goal is to get the previous value inside my input element labeled "SERIAL END" then automatically append it's value when adding a row to "SERIAL START" and not only append but will add +1 to it's value. The problem is I always get an undefine value, I don't know what is missing.
Here is the image
Here is the snippets
$(document).ready(function() {
$("#addrow").on("click", function() {
var startElement = $("#start");
var value = parseInt(startElement.val());
startElement.val(value);
var hidden = startElement.val();
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_" + hidden + "'>");
var cols = "";
cols +=
'<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name"id="model' +
hidden + '" class="form-control selectpicker show-menu-arrow " name="model[]" ><option selected disabled> Select your model name</option><?php $sql = mysqli_query($con,"call gettrial");
if(mysqli_num_rows($sql)>0){
while($row=mysqli_fetch_assoc($sql)){
echo "<option value=$row[id]>".$row['model_name']." </option>";
}
} ?></select></td>';
cols +=
'<td><input id="code' + hidden +
'" value="" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" id="serstart' + hidden +
'" name="serstart[]" readonly/></td>';
cols +=
'<td><input type="number" class="form-control" id="serend' + hidden +
'" name="serend[]" onkeyup="manage(this)" /></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
.find('.selectpicker')
.selectpicker({
liveSearch: true,
showSubtext: true
});
const hide = document.getElementById('start');
hide.value = (parseInt(hidden) + parseInt(1));
hidden++;
}
});
$('#remove').click(function() {
$("#myTable").each(function() {
if ($('tr', this).length > 2) {
$('tr:last', this).remove();
}
});
});
});
$('#addrow').click(function() {
var id = $(this).closest('tr').find('#tablerow_0').text();
var row = $(this).parent("tbody tr");
var rowin=$(this).parent('tr').find('input:number');
var rowprev=$(this).parent('tr').prev().find('input:last').val();
var rownext=$(this).parent('tr').next().find('input:first').val();
console.log($(this).parent('tr').prev().find('input:last'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-12">
<form class="className" name="form" id="form"
action="lot_registration_model_submit.php" data-toggle="validator"
enctype="multipart/form-data" method="POST">
<div class="form-group">
<label class="col-sm-3">Lot No.: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="text" id="lotno"
name="lotno" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Month of: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="date" id="monthof"
name="monthof" style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial Start: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serstart" name="serstart"
style="text-transform:uppercase" required>
</div>
</div>
<div class="form-group">
<label class="col-sm-3">Serial End: <font color="red">*</font></label>
<div class="col-sm-9">
<input autocomplete="off" class="form-control" type="number" id="serend"
name="serend" style="text-transform:uppercase" required>
</div>
</div>
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" disabled />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover"
id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow"
data-live-search="true" title="Select your model name"
onchange="selectmodel(this)" required>
<?php
$sql = mysqli_query($con,"SELECT model.id,model.model_name,model.code,model.status
FROM model left join grouped on model.id = grouped.modelandcode
WHERE cat_id='1' and model.status='1' and grouped.status is null
ORDER BY model_name ASC");
$con->next_result();
if(mysqli_num_rows($sql)>0)
{
while($row=mysqli_fetch_assoc($sql))
{
echo "<option value='".$row['id']."'>".$row['model_name']."</option>";
}
}
?>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" class="form-control"
</td>
</tr>
</tbody>
</table>
<input type="hidden" value="1" id="start" />
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>
You can get length of tr inside tbody then using that length get reference of previous tr then use td:eq(3) this will search fourth td because index starts from 0 then use that value to get value and add it in newly created tr input .
Also , you don't need to use same php code to create select-box just clone first select-box and then use same to pass inside td which are newly created .
Then , to intialize selectpicker which are added dynamically use $("table.order-list tr:last").find(".selectpicker").. this line will get last tr which is added and then inside that tr it will selectpicker .
Demo Code :
$(document).ready(function() {
$('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
$("#addrow").on("click", function() {
var cloned = $("tbody select:first").clone() //cloned first tr select
var value = $("tbody tr").length - 1 //get tr length - 1 (because tr start from 0 index)
var new_start = parseInt($("tbody tr:eq(" + value + ") td:eq(3) input").val()) + 1 //get previous input box value
var tbl = document.getElementById('tbl').rows.length;
if (tbl === 5) {
alert("It is limited for 5 rows only");
} else {
var newRow = $("<tr id='tablerow_'" + (value + 1) + "'>");
var cols = "";
cols += '<td><select onchange="selectmodel(this)"data-live-search="true" placeholder="Select your model name" class="form-control selectpicker show-menu-arrow " name="model[]" >' + $(cloned).html() + '</select></td>';
cols += '<td><input value="' + $("#lotno").val() + '" type="text" class="form-control" name="code[]" readonly="" /></td>';
cols +=
'<td><input type="number" class="form-control" name="serstart[]" value="' + new_start + '" readonly/></td>';
cols +=
'<td><input type="number" class="form-control"name="serend[]" value="' + $("#serend").val() + '"/></td>';
newRow.append(cols);
$("table.order-list").append(newRow)
//intialize selectpicker which added last
$("table.order-list tr:last").find('.selectpicker').selectpicker({
liveSearch: true,
showSubtext: true
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/css/bootstrap-select.min.css" integrity="sha512-ARJR74swou2y0Q2V9k0GbzQ/5vJ2RBSoCWokg4zkfM29Fb3vZEQyv0iWBMW/yvKgyHSR/7D64pFMmU8nYmbRkg==" crossorigin="anonymous"
/>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.18/js/bootstrap-select.min.js" integrity="sha512-yDlE7vpGDP7o2eftkCiPZ+yuUyEcaBwoJoIhdXv71KZWugFqEphIS3PU60lEkFaz8RxaVsMpSvQxMBaKVwA5xg==" crossorigin="anonymous"></script>
<div class="col-lg-12">
<input type="button" class="btn btn-primary pull-left" id="addrow" value="Add Row" />
<input type="button" class="ibtnDel btn btn-md btn-danger" id="remove" value="Delete Row">
<br>
<table width="100%" class="table order-list table-striped table-bordered table-hover" id="myTable">
<thead>
<tr>
<th class="col-sm-3">
<center />Model
</th>
<th class="col-sm-3">
<center />Code
</th>
<th class="col-sm-3">
<center />Serial Start
</th>
<th class="col-sm-3">
<center />Serial End
</th>
</tr>
</thead>
<tbody id='tbl'>
<tr id="tablerow_0">
<td>
<select name="model[]" id="model0" class="form-control selectpicker show-menu-arrow" data-live-search="true" title="Select your model name" onchange="selectmodel(this)" required>
<option selected disabled> Select your model name</option>
<option value='1'>A</option>
<option value='2'>A2</option>
<option value='3'>A3</option>
</select>
</td>
<td>
<input name="code[]" type="text" id="code0" value="M12" class="form-control" readonly="" />
</td>
<td>
<input type="number" name="serstart[]" id="serstart0" value="1" class="form-control" readonly />
</td>
<td>
<input type="number" name="serend[]" id="serend0" value="11" class="form-control"> </td>
</tr>
</tbody>
</table>
<button id="submit" type="submit" class="btn btn-primary pull-right"><span
class="fa fa-check"> &nbsp Submit</span></button>
</form>
</div>

JavaScript: Add increasing number to name attr

I'm creating an HTML table from data pulled from an XML file using JQuery. This data is to be posted via HTTP POST somewhere else.
When the XML contains multiple items (i.e. songs), it creates the respective HTML but the name attribute of the input elements stays the same.
This is the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$.get('test.xml', function(d){
$('body').append('<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank" />');
$('#myForm').append('<div id="mySongs" />');
$('#mySongs').append('<input type="submit" value="Submit">');
$(d).find('song').each(function() {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
});
});
});
</script>
The HTML code produced after pulling the XML data and running the above code looks currently this way:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price" value="25.00"></span>
<span id="currency">
<input type="text" name="currency" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price" value="30.00"></span>
<span id="currency">
<input type="text" name="currency" value="USD"></span>
</div>
</form>
I would like to add an increasing number to the name attribute so that when multiple items are pulled, the code shows the respective number to identify it (For example: name="title[1]").
I would like the HTML to look as shown below instead:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title[1]" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist[1]" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price[1]" value="25.00"></span>
<span id="currency">
<input type="text" name="currency[1]" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title[2]" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist[2]" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price[2]" value="30.00"></span>
<span id="currency">
<input type="text" name="currency[2]" value="USD"></span>
</div>
</form>
How to achieve this? Any suggestion is highly appreciated.
You can write
title[] instead title[1]
and server automaticaly set indexes.
Can use the index argument of each callback:
$(d).find('song').each(function(i) {
var html = '<div...> <span..><input name="title['+ i +']" value="' + title + '" /></span>'
});
What about this:
var idx = 0;
$(d).find('song').each(function () {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title[' + idx + ']" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist[' + idx + ']" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price[' + idx + ']" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency[' + idx + ']" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
idx++;
});

How to validate if all textbox value is not empty in an array name using jquery?

I have a problem in my form. In my form the user can add multiple discount codes. And what I need to validate are the two textboxes these are 'date start' and 'date expired' and I need to find out if these are empty. Before allowing the user to add another row again.
Here's my code:
function addProductDiscountCode() {
var html = '<tr id="row-count-' + iterator + '">';
html += ' <td>';
html += ' <input type="text" name="discount_code[' + iterator + '][code]" class="form-control" readonly="readonly" value="' + code + '" />';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <input type="text" name="discount_code[' + iterator + '][percentage]" class="form-control text-center" />';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <div class="input-group date"><input name="discount_code[' + iterator + '][date_start]" value="" id="start-date-' + iterator + '" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_set" type="text" readonly><span class="input-group-btn"><button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button></span></div>';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <div class="input-group date"><input name="discount_code[' + iterator + '][date_expired]" value="" id="end-date-' + iterator + '" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_end" type="text" readonly><span class="input-group-btn"><button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button></span></div>';
html += ' </td>';
html += ' <td style="width: 15%">';
html += ' <select class="form-control" name="discount_code[' + iterator + '][status ]">';
html += ' <option value="0">Disable</option>';
html += ' <option value="1">Activate</option>';
html += ' </select>';
html += ' </td>';
html += ' <td class="text-center"><button type="button" onClick="removeCode(' + iterator + ');" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
$("#product-discount-code tbody").append(html);
iterator++;
$('.date').datetimepicker({
pickTime: false
});
}
And this will result in a row like this:
<tr id="row-count-1">
<td>
<input name="discount_code[1][code]" class="form-control" readonly="readonly" value="4npi7YIIrv" type="text">
</td>
<td class="text-center">
<input name="discount_code[1][percentage]" class="form-control text-center" type="text">
</td>
<td class="text-center">
<div class="input-group date">
<input name="discount_code[1][date_start]" value="" id="start-date-1" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_set" readonly="" type="text">
<span class="input-group-btn">
<button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td class="text-center">
<div class="input-group date">
<input name="discount_code[1][date_expired]" value="" id="end-date-1" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_end" readonly="" type="text">
<span class="input-group-btn">
<button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td style="width: 15%">
<select class="form-control" name="discount_code[1][status ]">
<option value="0">Disable</option>
<option value="1">Activate</option>
</select>
</td>
<td class="text-center">
<button type="button" onclick="removeCode(1);" class="btn btn-danger">
<i class="fa fa-minus-circle"></i>
</button>
</td>
</tr>
I added a console print in the add action:
$(".date_start").val();
$(".date_end").val();
And It only get the value of the first row. I need
The getter method like .val(), in jQuery will return the value of the first element in the set not of all the elements(with exceptions like .text())
You can use a loop based logic to see whether all the elements has values
var date_set = true;
$('.date_set').each(function () {
if ($(this).val().length == 0) {
date_set = false;
return false;
}
})

Categories

Resources