Bootstrap Modal with Dynamic Content loads last data - javascript

I have a table that when I hit save, it would get all the input fields in the first column and check in the database if the data already exists. If the condition is true, it would show an icon per row. And when I click that icon, the info relevant to that specific data will show as a bootstrap modal.
I've been working on my problem the whole day. I first tried to make it work with only one data. When I got what I wanted, I started to work on multiple data.
When multiple data is checked and they are duplicates, only the last info is shown even if there are 2 or more.
Here's my code:
The save button:
$( "#save_Boxes" ).click(function() {
$.ajax({
type: "POST",
url: window.base_url+'oss/admin/check_receive_data',
data: $.param($('form#receiving-form').serializeArray()),
dataType : 'JSON',
success: function (response) {
var new_arr = response.receive_array;
console.log(new_arr);
var no_duplicate = 0;
//THIS IS WHERE THE PROCESS SHOULD TAKE PLACE
$('table#receiving-box-table tbody tr').each(function(index){
var ctno = $(this).find('td:first input').val(); // get courier trancking
var td_id = $(this).find('td:last button.duplicate-data').attr('id');
var target = $(this).find('td:last button.duplicate-data').attr('data-target');
// check if ctno is present in response array or not
var arr = $.grep(response.receive_array, function( n ) {
return ( n.courier_tracking_no === ctno);
});
if(arr.length){ // if present then show error message
// alert('wsdds');
no_duplicate = 1;
$(this).find('td:first input').attr('disabled', 'disabled');
$('button#'+td_id).show(); // let it be hidden by default
$(this).find('td:first input').closest('td').addClass('has-error');
}
var new_ctno = $('button#'+td_id).closest('tr').find('td:first input').val();
$.each(new_arr, function(idx, obj){
console.log(idx + ": " + obj.courier_tracking_no);
console.log(target);
$(target).on('hidden.bs.modal', function(){
$(target+' .modal-title').html('');
$(target+' .modal-body').html('');
});
$('button#'+td_id).off('click').on('click', function(){
$(target).load(window.base_url+'oss/admin/box_duplicate',
function(){
$(target+' .modal-title').html('Duplicate Courier Tracking Number - '+obj.courier_tracking_no);
$(target+' .modal-body').html("<p class='text-left'>This box already exists. Please delete.</p><table class='table table-hover table-bordered table-striped'><tbody><tr><th scope='row'>Batch No.</th><td>"+obj.batch_no+"</td></tr><tr><th scope='row'>Courier Name</th><td>"+ucword(obj.courier_name)+"</td></tr><tr><th scope='row'>Vendor Name</th><td>"+ucword(obj.vendor_name)+"</td></tr><tr><th scope='row'>Status</th><td>"+ucword(obj.status)+"</td></tr></tbody></table>");
$(target).modal('show');
});
});
});
});
if(no_duplicate == 0){
var check_if_empty = 0;
$('input[name^="courier_tracking_no[]"]').each(function(){
if($(this).val() != ""){
check_if_empty += 1;
}
});
if(check_if_empty > 0){
$('#receiving-form').submit();
}
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
console.log("There was an error: " + errorThrown);
}
});
});
The html table:
<table id="receiving-box-table" class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>Courier Tracking #</th>
<th>Courier</th>
<th>Vendor</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" form="receiving-form" class="form-control input-sm track_no" name="courier_tracking_no[]" id="courier_tracking_no_1" /></td>
<td><input type="text" form="receiving-form" class="form-control input-sm" name="courier_name[]" id="courier_name_1" onkeypress="if (event.keyCode == 13) {return false;}"/></td>
<td><input type="text" form="receiving-form" class="form-control input-sm" name="vendor_name[]" id="vendor_name_1" onkeypress="if (event.keyCode == 13) {return false;}"/></td>
<td class="box-action"><button class="btn btn-danger btn-xs clear-data" data-toggle="tooltip" data-placement="right" title="Clear input fields"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button> <button style="display:none;" id="dup-0" data-toggle = "modal" data-target = "#dupli-modal-0" class="btn btn-warning btn-xs duplicate-data" title="Duplicate Data"><span class="glyphicon glyphicon-info-sign" aria-hidden="true"></span></button><div class = "modal fade" id = "dupli-modal-0" tabindex = "-1" role = "dialog" aria-labelledby = "dupli-modal-0Label" aria-hidden = "true"></div></td>
</tr>
</tbody>
</table>
Note: Only the first row is shown because the following rows are dynamically created.
The html modal:
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title"></h4>
</div>
<div class="modal-body">
<div class="row" style="margin-left: 0; margin-right: 0;">
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Ok</button>
</div>
</div>
What am I missing? Even if the modal comes from only 1 file, it has unique ID's so it should not be a problem.
Thanks for your help!
-Eli

I tried a different approach. Instead of calling a url (I use CI) and showing the file that holds the modal template, I directly added the template inside my code:
$( "#save_Boxes" ).click(function() {
$.ajax({
type: "POST",
url: window.base_url+'oss/admin/check_receive_data',
data: $.param($('form#receiving-form').serializeArray()),
dataType : 'JSON',
success: function (response) {
var new_arr = response.receive_array;
console.log(new_arr);
var no_duplicate = 0;
//THIS IS WHERE THE PROCESS SHOULD TAKE PLACE
var stored = [];
$('table#receiving-box-table tbody tr').each(function(index){
var ctno = $(this).find('td:first input').val(); // get courier trancking
var td_id = $(this).find('td:last button.duplicate-data').attr('id');
var target = $(this).find('td:last button.duplicate-data').attr('data-mod_id');
stored.push(target);
var arr = $.grep(response.receive_array, function( n ) {
return ( n.courier_tracking_no === ctno);
});
if(arr.length){ // if present then show error message
// alert('wsdds');
no_duplicate = 1;
$(this).find('td:first input').attr('readonly', 'readonly');
$('button#'+td_id).show(); // let it be hidden by default
$(this).find('td:first input').closest('td').addClass('has-error');
}
});
$('div.modal_holder').html('');
all_modals = '';
var modal_list = $.each(new_arr, function(idx, obj){
all_modals += "<div class = 'modal fade' id = '"+stored[idx]+"' tabindex = '-1' role = 'dialog' aria-labelledby = '"+stored[idx]+"Label' aria-hidden = 'true'><div class='modal-dialog'><div class='modal-content'><div class='modal-header'><button type='button' class='close' data-dismiss='modal'>×</button><h4 class='modal-title'></h4></div><div class='modal-body'><div class='row' style='margin-left: 0; margin-right: 0;'><p class='text-left'>This box already exists. Please delete.</p><table class='table table-hover table-bordered table-striped'><tbody><tr><th scope='row'>Batch No.</th><td>"+obj.batch_no+"</td></tr><tr><th scope='row'>Courier Name</th><td>"+obj.courier_name+"</td></tr><tr><th scope='row'>Vendor Name</th><td>"+obj.vendor_name+"</td></tr><tr><th scope='row'>Status</th><td>"+obj.status+"</td></tr></tbody></table></div></div><div class='modal-footer'><button type='button' class='btn btn-default' data-dismiss='modal'>Ok</button></div></div></div></div>";
});
$('div.modal_holder').html(all_modals);
console.log(no_duplicate);
if(no_duplicate == 0){
var check_if_empty = 0;
$('input[name^="courier_tracking_no[]"]').each(function(){
if($(this).val() != ""){
check_if_empty += 1;
}
});
console.log(check_if_empty);
if(check_if_empty > 0){
$('#receiving-form').submit();
}
}
},
error: function (MLHttpRequest, textStatus, errorThrown) {
console.log("There was an error: " + errorThrown);
}
});
});

Related

Why is my checkbox array returing a length of zero in jquery ajax

I am dynamically generating checkboxes from my database using jquery ajax to call my web api. The problem is that I am trying to get the length of the checkbox array but constantly receiving an array length of zero when i debug. Please what might be wrong with my code.
HTML CODE
<div class="panel-body">
<form method="post">
<div class="form-group">
<label>Add Role Name</label>
<input type="text" class="form-control" placeholder="Role Name" />
</div>
<div class="col-md-6">
<div class="well">
<fieldset id="appName">
</fieldset>
</div>
<input id="saveUrl" type="button" value="Add Role" class="btn btn-success pull-right" />
</div>
</form>
</div>
JQUERY CODE
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
method: 'GET',
url: 'http://localhost:61768/api/users/GetUrls',
headers: {
'Authorization': 'Basic ' + btoa(localStorage.getItem('ApplicationId') + ":" + localStorage.getItem('ApiKey'))
},
success: function (data) {
if (Object.keys(data).length == 0) {
alert("Ewoo");
} else {
$.each(data, function (index, value) {
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
$('#appName').append(input); //Where I generate the checkboxes
});
}
},
error: function () {
alert("DonDy");
}
});
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
$('#saveUrl').click(function () {
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
});
</script>
The result of click the save button is alerting bad
In this code checkbox is getting appended but you are not checking the checkbox
var input = ('<label><input type="checkbox" name="chk[]" value=' + value.Id + ' />' + value.UrlName + '</label><br>');
Here you are checking length of checked checkbox..hence alerting to bad :
var $checkboxes = $('input[name="chk[]"]:checked');
Try this and that to inside save url click fucntion:
$('#saveUrl').click(function () {
var $checkboxes = $('input[name="chk[]"]');
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});
Since you are populating/creating checkbox inside an AJAX call, you should have $checkboxes inside the #saveUrl function, because before that, it would be empty when the JS is loaded. You need this variable when the #saveUrl is clicked, hence it should check for the checked inputs when the #saveUrl is triggered:
$('#saveUrl').click(function() {
var $checkboxes = $('input[name="chk[]"]:checked'); //Checkbox array
if ($checkboxes.length > 0) {
alert("Good");
} else {
alert("Bad"); //Result.
}
});

Submitting form resubmits the same data

I'm having some problems with a table that I created using a Gyrocode example. I modified it to fetch and submit data via ajax and to leverage Datatables server side processing.
Basically what is happening is I can select row1 and submit the form and everything works fine. I then de-select row1 and select row2 and when I submit, it will submit for row1 & row2.
I have created a JSFiddle to replicate and am logging the form variable to the console.
Step1: Selected row1 and clicked 'Request Selected' button, here is the output
<form id="frm-example">
<div class="table-responsive">...</div>
<input type="hidden" name="id[]" value="1">
</form>
Step2: Did not refresh page, de-selected row1, selected row2 and clicked 'Request Selected' button, here is the output. You can see the first row is still in the variable.
<form id="frm-example">
<div class="table-responsive">...</div>
<input type="hidden" name="id[]" value="1">
<input type="hidden" name="id[]" value="2">
</form>
I tried clearing the form variable when a request was successfully posted but it seems to come back. I'm not sure how to deselect everything and reset the variables back to null when a request was already submitted.
HTML:
<div class="row">
<div class="col-lg-12">
<div class="row">
<div class="col-lg-12">
<!-- /.panel-heading -->
<div class="panel-body">
<form id="frm-example">
<div class="table-responsive">
<div class="row">
<div class="col-lg-12" style="padding-bottom: 5px;">
<button id="btn-submit" class="btn btn-success" disabled><i class="fa fa-floppy-o"></i> Request Selected (0)</button>
</div>
</div>
<div class="table-responsive">
<table class="display select table table-striped table-bordered table-hover" id="example">
<thead>
<tr>
<th>
<input name="select_all" value="1" type="checkbox">
</th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Extn.</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
</table>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Javascript:
//
// Updates "Select all" control in a data table
//
function updateDataTableSelectAllCtrl(table) {
var $table = table.table().node();
var $chkbox_all = $('tbody input[type="checkbox"]', $table);
var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);
// If none of the checkboxes are checked
if ($chkbox_checked.length === 0) {
chkbox_select_all.checked = false;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If all of the checkboxes are checked
} else if ($chkbox_checked.length === $chkbox_all.length) {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If some of the checkboxes are checked
} else {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = true;
}
}
}
$(document).ready(function() {
// Array holding selected row IDs
var rows_selected = [];
var table = $('#example').DataTable({
'processing': true,
'serverSide': true,
'sAjaxSource': 'data.php',
'columnDefs': [{
'targets': 0,
'searchable': false,
'orderable': false,
'width': '1%',
'className': 'dt-body-center',
'render': function(data, type, full, meta) {
return '<input type="checkbox">';
}
}],
'order': [
[1, 'asc']
],
'rowCallback': function(row, data, dataIndex) {
// Get row ID
var rowId = data[0];
// If row ID is in the list of selected row IDs
if ($.inArray(rowId, rows_selected) !== -1) {
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
}
});
setInterval(function test() {
table.ajax.reload(null, false); // user paging is not reset on reload
$(".dataTables_processing").hide();
}, 2000);
// Handle click on checkbox
$('#example tbody').on('click', 'input[type="checkbox"]', function(e) {
var $row = $(this).closest('tr');
// Get row data
var data = table.row($row).data();
// Get row ID
var rowId = data[0];
// Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected);
// If checkbox is checked and row ID is not in list of selected row IDs
if (this.checked && index === -1) {
rows_selected.push(rowId);
// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1) {
rows_selected.splice(index, 1);
}
if (this.checked) {
$row.addClass('selected');
document.getElementById("btn-submit").innerHTML = '<i class="fa fa-floppy-o"></i>' + " Request Selected (" + rows_selected.length + ")";
} else {
$row.removeClass('selected');
document.getElementById("btn-submit").innerHTML = '<i class="fa fa-floppy-o"></i>' + " Request Selected (" + rows_selected.length + ")";
}
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
$('#btn-submit').prop('disabled', (!rows_selected.length));
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle click on table cells with checkboxes
$('#example').on('click', 'tbody td, thead th:first-child', function(e) {
$(this).parent().find('input[type="checkbox"]').trigger('click');
});
// Handle click on "Select all" control
$('thead input[name="select_all"]', table.table().container()).on('click', function(e) {
if (this.checked) {
$('#example tbody input[type="checkbox"]:not(:checked)').trigger('click');
} else {
$('#example tbody input[type="checkbox"]:checked').trigger('click');
}
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle table draw event
table.on('draw', function() {
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
});
// Handle form submission event
$('#frm-example').on('submit', function(e) {
if (!e.isDefaultPrevented()) {
var url = "process.php";
var form = this;
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId) {
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
console.log(form);
}
});
return false;
}
})
});
I just figured it out! I ended up iterating back over the selected rows and removing the elements from the form variable after I get a success back from ajax.
$('#frm-example').on('submit', function (e) {
if (!e.isDefaultPrevented()) {
var url = "process.php";
form = this;
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'id[]')
.val(rowId)
);
});
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
$.each(rows_selected, function(index, rowId){
// Remove hidden element
$(form).children("input").remove();
});
}
});
return false;
}
})

Adding Jquery UI to UL in HTML

I want to be able to add jquery UI to the list on GoalNotes This table gets populated by what the user enters in the "name1" and "data1" input fields. Every time I give the an id, the program breaks and I get no errors. Any ideas on how I could apply animations to the table rows that get added after the user inputs data?
html
<section class="section section--active color1" data-letter="M">
<article class="section__wrapper">
<h1 class="section__title">Monday</h1>
<div id="Monday" class="tabcontent">
<form name="goalsList1" action = "/created" method="POST">
<div id="tab1">
<table>
<tr>
<td><b>New Goal:</b><input type="text" name="name1" id="name1"></td>
<td><b>Notes:</b><input type="text" name="data1" id="data1"></td>
<td>
<input type="submit" value="Save" onclick="SaveItem(1)">
</td>
</tr>
</table>
</div>
<div id="items_table1">
<h2>List of goals</h2>
<table id="list1" contenteditable> </table>
<p>
<label><input type="button" value="Clear" onclick="ClearAll(1)"></label>
</p>
</div>
</form>
</div>
</article>
</section>
javascript
function doShowAll(numOfWeek) {
if (CheckBrowser()) {
var key = "";
var list = "**<tr><th>Goal</th><th>Notes</th></tr>**\n";
var i = 0;
var goals = localStorage[numOfWeek] ? JSON.parse(localStorage[numOfWeek]) : {};
var goalsKeys = Object.keys(goals);
for (i = 0; i < goalsKeys.length; i++) {
key = goalsKeys[i];
list += "<tr><td>" + key + "</td>\n<td>"
+ goals[key] + "</td></tr>\n";
}
if (list == "<tr><th>Goal</th><th>Notes</th></tr>\n") {
list += "<tr><td><i>nothin' here</i></td>\n<td><i>nothin' here either</i></td></tr>\n";
}
document.getElementById('list'+numOfWeek).innerHTML = list;
} else {
alert('Cannot store list as your browser do not support local storage');
}
}
$(document).ready(function(e) {
$('#due-date').datepicker();
$('#add-todo').button({
icons: {
primary: "ui-icon-circle-plus"
}
}).click(function() {
$('#new-todo').dialog('open');
}); // end click
$('#new-todo').dialog({
modal: true,
autoOpen: false,
close: function() {
$('#new-todo input').val(''); /*clear fields*/
},
buttons : {
"Add task" : function() {
var taskName = $('#task').val();
var dueDate = $('#due-date').val();
var beginLi = '<li><span class="done">%</span><span class="delete">x</span>';
var taskLi = '<span class="task">' + taskName + '</span>';
var dateLi = '<span class="due-date">' + dueDate + '</span>';
var endLi = '</li>';
$('#todo-list').prepend(beginLi + taskLi + dateLi + endLi);
$('#todo-list').hide().slideDown(250).find('li:first')
.animate({
'background-color': '#ff99c2'
},250)
.animate({
'background-color': '#d9b3ff'
},250).animate; // end animate
$(this).dialog('close');
},
"Cancel" : function() {
$(this).dialog('close');
}
}
});
$('#todo-list').on('click','.done',function(e) {
var $taskItem = $(this).parent("li");
var $copy = $taskItem.clone();
$('#completed-list').prepend($copy);
$copy.hide().slideDown();
$taskItem.remove();
}
); // end on
$('#todo-list, #completed-list').on('click','.delete',function(e) {
$(this).parent("li").slideUp(250, function() {
$(this).remove();
}); // end slideup
}); // end on
$('#todo-list').sortable();
}); // end ready
http://jsbin.com/digefufeca/edit?html,css,js,console,output
The problem
The form with nane goalsList1 is sending whenever you click on the button.
Why? because the button is submit button.
The solution(s)
Replace the button's type to button. (link)
Prevent the form submission by event.preventDefault(). (link)
There are more ways but those are the major.
Note: your code still not working but now you can see the error message.

jQuery - reusing code without duplicating it

I have a page that is essentially a table which has its rows duplicated when the button is pushed. Each additional row has a unique id/name.
I now have this problem. I essentially have a similar table on a different page. Main difference is that it may have additional inputs. At the moment, it looks something like this:
JavaScript
var cloned;
$(function() {
initDatepickersAndSelect();
$('#add_row').on('click', function(evt) {
addRow();
});
$('#delete_row').on('click', function(evt) {
deleteRow();
});
$('#add_row2').on('click', function(evt) {
addRow(x);
});
$('#delete_row2').on('click', function(evt) {
deleteRow(x);
});
});
function initDatepickersAndSelect() {
cloned = $("table tr#actionRow0").eq(0).clone();
$(".dateControl").datepicker({
dateFormat: "dd-mm-yy"
});
$(".responsibility").select2({
tags: true
});
$(".campaignType").select2({
tags: true
});
}
function addRow() {
var $tr = cloned.clone();
var newRowIdx = $("table#actionTable tr").length - 1;
$tr.attr('id', 'actionRow' + newRowIdx);
$tr.find("input, select").each(function(i_idx, i_elem) {
var $input = $(i_elem);
if ($input.is("input")) {
$input.val("");
}
$input.attr({
'id': function(_, id) {
return id + newRowIdx;
},
'name': function(_, name) {
return name.replace('[0]', '[' + newRowIdx + ']');
},
'value': ''
});
});
$tr.appendTo("table#actionTable");
$(".dateControl", $tr).datepicker({
dateFormat: "dd-mm-yy"
});
$(".responsibility", $tr).select2({
tags: true
});
$(".campaignType", $tr).select2({
tags: true
});
}
function deleteRow() {
var curRowIdx = $("table#actionTable tr").length;
if (curRowIdx > 2) {
$("#actionRow" + (curRowIdx - 2)).remove();
curRowIdx--;
}
}
HTML
<div class="col-md-12 noPadding">
<table class="table table-bordered table-hover additionalMargin" id="reportTable">
<thead>
<tr>
<th class="text-center">Something</th>
<th class="text-center">Something else</th>
</tr>
</thead>
<tbody>
<tr id='actionRow0'>
<td>
<select class="campType" name='reportInput[0][campType]' id="reportInput">
<option value=""></option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</td>
<td>
<input type="text" name='reportInput[0][campDelivery]' id="dateInput" class="form-control" />
</td>
</tr>
</tbody>
</table>
<a id="add_row" class="btn btn-default pull-right">Add Row</a>
<a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
The last thing I want to do is duplicate all of my JavaScript and rename things to match the above.
What I am wondering, is there anyway I could reuse the JavaScript?
Any advice appreciated.
Thanks
(code also available as JSFiddle)
Based on my understanding of the question, I think you could do something like this. Assuming a function called addRow as seen in your fiddle, the first step is to include that JS on all pages where you want that functionality. You then mentioned that other pages might have additional controls. For this, I'd override the function...
On the page with normal controls
function addRow() {
// Row adding code...
}
On the page with extra controls
var oldAddRow = addRow;
var addRow = function(){
$('.some_other_control').click(ctrlHandler);
$('.some .input').val('');
oldAddRow();
}
I suggest to have an invisible "template row" in your table, which you can copy to add new rows.
Something like this:
<style>
tr.template { display: none; }
</style>
<table id="table1">
<tr class="template"><td><input id="blah">/td><td><input id="foo"></td></tr>
</table>
<button id="add">Add Row</button>
<script>
function add_row($table) {
var count = $table.find('tr').length - 1;
var tr_id = ""+(count+1);
var $template = $table.find('tr.template');
var $tr = $template.clone().removeClass('template').prop('id', tr_id);
$tr.find(':input').each(function() {
var input_id = $(this).prop('id');
input_id = tr_id + '_' + input_id;
$(this).prop('id', input_id);
});
$table.find('tbody').append($tr);
}
$('#add').on('click', function() { add_row($('#table1')); });
</script>
I think it will be easier to make the code generic in this way. If you don't want the inputs in the template to be submitted, you can disable them or remove them somehow.
Demo: http://sam.nipl.net/table-demo.html
You may just clone a row and reset attibutes within with something like:
function addRow(id) {
var c = $("table#"+id+" tr").last();
$("table#"+id+" tbody").append(c.clone().attr({id: "addedrow" + Math.random()*10+1}));
}
function deleteRow(id,index) {
var curRowIdx = $("table#"+id+" tr").length;
if (curRowIdx > 2) {
if(index != void 0) {
$("table#"+id+" tr")[index].remove();
}else{
$("table#"+id+" tr").last().remove();
}
}
}
Call it with
$('#add_row').on('click', function(evt){addRow("reportTable");});
$('#delete_row').on('click', function(evt){deleteRow("reportTable",1);});
Maybe you'll prepare new rows for your table with something like
var emptyRow[id] = $("table#"+id+" tr").last();
and change
$("table#"+id+" tbody").append(c.clone().attr({id: "addedrow" + Math.random()*10+1}));
to
$("table#"+id+" tbody").append(emptyRow[id].clone().attr({id: "addedrow" + Math.random()*10+1}));

Add row with Jquery - Need to increment inputs names and onkeyup event caller

I am a bit new to JQuery and still trying to figure out how to add (clone) a table row at the end of the table and increment the input name="code10", onkeyup="recordTrans1(this.value)", and this div (<div class="txtHint3"></div>) inside a table cell.
Essentially I just want those 3 things to increment by 1 (e.g : name="code11", onkeyup="recordTrans2(this.value)", <div class="txtHint4"></div>, and so on...)
The code I have now is working perfectly to add or remove the table rows.
The problem I have is when I add a new table row, I don't see it in the "View source" of the page and the name="codeX", onkeyup, and div is not incrementing.
I tried a few different ways and can't seem to figure it out so any help would be greatly appreciated!
Here is the code I have to far :
<script>
jQuery.fn.addClone = function() {
return this.each(function() {
// get row for cloningg
var row = $(this).parents('tr');
var parent = {};
// use tbody or table parent
if ( $(row).parents('tbody').length>0) {
parent = $(row).parents('tbody');
} else {
parent = $(row).parents('table');
}
// inject clone
var copy = $(row).clone();
$(copy).addClass('sadey');
$(copy).addClass('isclone');
$(parent).append( copy );
// remove last td and replace with remove html
$('.sadey').children('td:last').remove();
$('.sadey').append('<td><button class="btn btn-block btn-danger" onclick="$(this).killClone()">Retirer</button></td>');
// increment all ids and names
var id = ($('.isclone').length + 1);
$('.sadey').find('*').each(function() {
var tempId = $(this).attr('id');
if (typeof tempId != 'undefined' && tempId!='') {
$(this).attr('id',tempId + '_' + id);
}
var tempName = $(this).attr('name');
if (typeof tempName != 'undefined' && tempName!='') {
$(this).attr('name',tempName + '_' + id);
}
});
// remove active tag
$('.sadey').removeClass('sadey');
});
};
// remove a row and re-index the clones
jQuery.fn.killClone = function() {
var row = $(this).parents('tr');
$(row).remove();
// re-index
var id = 2;
$('.isclone').each(function() {
$(this).find('*').each(function() {
var tempId = $(this).attr('id');
if (typeof tempId != 'undefined' && tempId!='') {
tempId = tempId.split('_');
$(this).attr('id',tempId[0] + '_' + id);
}
var tempName = $(this).attr('name');
if (typeof tempName != 'undefined' && tempName!='') {
tempName = tempName.split('_');
$(this).attr('name',tempName[0] + '_' + id);
}
});
id++;
});
};
</script>
And here's the HTML :
<table class="table table-striped" id="FinancialDataTable">
<thead>
<tr>
<th style="width: 10%;">Code</th>
<th style="width: 5%;">Qté</th>
<th>Produit</th>
<th>Description</th>
<th>Prix</th>
<th style="width: 10%;">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="form-group">
<input type="text" id="code10" name="code16" class="form-control" onkeyup="recordTrans1(this.value)" />
</div>
</td>
<td>
<div class="form-group">
<input type="text" name="qte16" class="form-control" value="1" />
</div>
</td>
<div id="txtHint3">
<td></td>
<td> </td>
<td> </td>
</div>
<td><button type="button" class="btn btn-primary btn-sm" onClick="$(this).addClone();">Ajouter un autre article</button></td>
</tr>
</tbody>
</table>
You can not see the updated source code by
Right click -> View page source
Browser loads the source code in a new Tab again when you click it. So,
Instead of using it use Code Inspector
Right click -> Inspect element
To get onkeyup attribute updation, you can modify a part of your the code by this:
$('.sadey').find('*').each(function() {
var tempId = $(this).attr('id');
if (typeof tempId != 'undefined' && tempId!='') {
$(this).attr('id',tempId + '_' + id);
$(this).attr('onkeyup','recordTrans' + id + "()");
}
var tempName = $(this).attr('name');
if (typeof tempName != 'undefined' && tempName!='') {
$(this).attr('name',tempName + '_' + id);
}
});

Categories