I'm trying to add row to table dynamically and calculates the age from ID card number.
ID card number for example: 88xxxxxxxxxx (age 33) // 00xxxxxxxxxx (age 21) // 01xxxxxxxxxx (age 20) and so on.
Problem here, as I'm adding row to the table. First row works fine but for the following rows, the results of age selector is applied to all rows in the table.
I've tried to clear the input of age class as new rows are added but seems like it removes all the input of the age selector as well.
var num = 0;
//adds row to table
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="${++num}">
<td class="row-index text-center">
<p>${num}</p>
</td>
<td class="row-index text-center">
<input type="text" class="form-control name">
</td>
<td class="row-index text-center">
<input type="text" class="form-control noic">
</td>
<td class="row-index text-center">
<input type="text" class="form-control age">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button"><span class="glyphicon glyphicon-minus"></span></button>
</td>
</tr>`);
$(".noic").blur(function() {
var currentYear = new Date().getFullYear().toString().substr(-2); // 20(21)
var yearNow = new Date().getFullYear(); // 2021
var yearID = $(".noic").val().substring(0, 2); // from ID: (88)xxxxxxxxxx
var age;
if (yearID > currentYear) {
age = (+yearNow - (+1900 + +yearID));
} else {
age = (+yearNow - (+2000 + +yearID));
}
$(".age").val(age);
});
});
// removes row from table
$('#tbody').on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
num--;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">No.</th>
<th class="text-center">Name</th>
<th class="text-center">ID Card Number</th>
<th class="text-center">Age</th>
<th class="text-center"><button class="btn btn-md btn-primary" id="addBtn" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
You need to use $(this) to get a reference to the currently blurred .noic, and use it as a reference to access itself and it's sibling elements:
var num = 0;
//adds row to table
$('#addBtn').on('click', function() {
$('#tbody').append(`<tr id="${++num}">
<td class="row-index text-center">
<p>${num}</p>
</td>
<td class="row-index text-center">
<input type="text" class="form-control name">
</td>
<td class="row-index text-center">
<input type="text" class="form-control noic">
</td>
<td class="row-index text-center">
<input type="text" class="form-control age">
</td>
<td class="text-center">
<button class="btn btn-danger remove"
type="button"><span class="glyphicon glyphicon-minus"></span></button>
</td>
</tr>`);
$(".noic").blur(function() {
var currentYear = new Date().getFullYear().toString().substr(-2); // 20(21)
var yearNow = new Date().getFullYear(); // 2021
var yearID = $(this).val().substring(0, 2); // from ID: (88)xxxxxxxxxx
var age;
if (yearID > currentYear) {
age = (+yearNow - (+1900 + +yearID));
} else {
age = (+yearNow - (+2000 + +yearID));
}
$(this).closest("tr").find(".age").val(age);
});
});
// removes row from table
$('#tbody').on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(1));
idx.html(`${dig - 1}`);
$(this).attr('id', `${dig - 1}`);
});
$(this).closest('tr').remove();
num--;
});
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="table table-bordered">
<thead>
<tr>
<th class="text-center">No.</th>
<th class="text-center">Name</th>
<th class="text-center">ID Card Number</th>
<th class="text-center">Age</th>
<th class="text-center"><button class="btn btn-md btn-primary" id="addBtn" type="button">
<span class="glyphicon glyphicon-plus"></span>
</button></th>
</tr>
</thead>
<tbody id="tbody">
</tbody>
</table>
Related
I have a modal and there is an Dynamic Editable table. I am seeking a way of getting the data of the editable table to the JS variables. Then I can pass these data to the controller via AJAX. I tried so many codes. but I couldn't find the suitable way. How should I get values to variables ?
Form blade
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody id="opening_invoice_table_body">
<tr>
<td><input type="date" class="form-control form-control-alternative date" name="opening_invoice[1][date]"></td>
<td><input type="text" class="form-control form-control-alternative detail" name="opening_invoice[1][detail]"></td>
<td><input type="text" class="form-control form-control-alternative invoice-no" name="opening_invoice[1][invoice_no]"></td>
<td><input type="number" class="form-control form-control-alternative amount" name="opening_invoice[1][amount]" min="0" step="any" placeholder="0.00"></td>
<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success"><i class="fas fa-download"></i> Save</button>
<button type="reset" class="btn btn-success"><i class="fas fa-eraser"></i> Clear</button>
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="fa fa-window-close"></i> Close</button>
</div>
</div>
</form>
Script
<script>
$(document).ready(function(){
var counter = 2;
//add rows
$("#add_row").on("click", function () {
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="date" class="form-control form-control-alternative date" name="opening_invoice[' + counter + '][date]"></td>';
cols += '<td><input type="text" class="form-control form-control-alternative detail" name="opening_invoice[' + counter + '][detail]"></td>';
cols += '<td><input type="text" class="form-control form-control-alternative invoice-no" name="opening_invoice[' + counter + '][invoice_no]"></td>';
cols += '<td><input type="number" class="form-control form-control-alternative amount" name="opening_invoice[' + counter + '][amount]" min="0" step="any" placeholder="0.00"></td>';
cols += '<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>';
newRow.append(cols);
$("#opening_invoice_table").append(newRow);
counter++;
});
//delete rows
$("#opening_invoice_table").on("click", "#delete_row", function (event) {
$(this).closest("tr").remove();
counter -= 1
counter++
});
});
//calculate total amount
$("#opening_invoice_table").on('input', '.amount', function () {
var calculated_total_sum = 0;
$("#opening_invoice_table .amount").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_amount").val(calculated_total_sum);
});
function newOpeningInvoice() {
var e = window.event || arguments.callee.caller.arguments[0];
e.preventDefault();
//Here I want to get table data. Below variables used for just testing purpose.
//var date = +$('.amount').val();
// var detail = $("input[class='detail']").val();
// var invoice_no = +$('.detail-no').val();
// var amount = +$('.amount').val();
// var date = "2020-03-27";
// var detail ="value";
//alert(amount);
$.ajax({
url: "opening_invoice/create",
type: "POST",
data: {'date': date, 'detail': detail, 'invoice_no': invoice_no, 'amount': amount, '_token':'{{csrf_token()}}' },
success: function (data) {
$('#add_opening_invoice_modal').modal('hide');
swal({
title: "Success!",
text: "Opening Invoice Saved Successfully!",
type: "success",
showConfirmButton: false,
timer: 1500,
});
}
});
return false;
}
</script>
Okey well I think this code might help you a lot.
I recommend you to create the "dynamic" parts in the javascript itself. This way you can use the data easier in my opinion. Here is how:
Javascript:
//To use them globally in the script. NOTE: Needs to be above the onload, otherwise javascript does not know the elements yet.
let trElement;
let tdElement;
let inputElement;
window.onload = onload();
function onload() {
//Create elements
trElement = document.createElement("tr");
tdElement = document.createElement("td");
inputElement = document.createElement("input");
//Set elements parameters
inputElement.type = "date";
inputElement.classList.add("form-control", "form-control-alternative", "date");
inputElement.name = "opening_invoice[1][date]";
//Appends
tdElement.append(inputElement);
trElement.append(tdElement);
document.getElementById("opening_invoice_table_body").appendChild(trElement);
//I do not have jQuery installed but you should create them like this:
// let inputElement = $('<input/>', {
// 'class': 'form-control form-control-alternative date'
// 'name': ...
// });
}
function createPartOfATable() {
console.log(inputElement.value);
}
HTML:
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
//This part has changed. Removed the HTML inside this tbody since I create it in javascript.
<tbody id="opening_invoice_table_body"></tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row" onclick="createPartOfATable();"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
Keep in mind that I created it in pure Javascript since I did not have jQuery installed at the moment. But I wrote some examples on how you should do it. Also jQuery documentation gives you a lot of info to do it with jQuery.
I could find the answer and it is working fine. serialize() is used to send the array of dynamic table data via AJAX to the controller.
//add rows
$('#add_row').on('click', function () {
var tr = '<tr>'+
'<td><input type="date" class="form-control form-control-alternative date" name="date[]"></td>'+
'<td><input type="text" class="form-control form-control-alternative detail" name="detail[]"></td>'+
'<td><input type="text" class="form-control form-control-alternative invoice-no" name="invoice_no[]"></td>'+
'<td><input type="number" class="form-control form-control-alternative amount" name="amount[]" min="0" step="any" placeholder="0.00"></td>'+
'<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>'+
'<tr>';
$('tbody').append(tr);
});
//delete rows
$('#opening_invoice_table').on('click', '#delete_row', function (event) {
var last=$('tbody tr').length;
if(last==1){
//do nothing
} else {
$(this).parent().parent().remove();
}
});
//calculate total amount
$("#opening_invoice_table").on('input', '.amount', function () {
var calculated_total_sum = 0;
$("#opening_invoice_table .amount").each(function () {
var get_textbox_value = $(this).val();
if ($.isNumeric(get_textbox_value)) {
calculated_total_sum += parseFloat(get_textbox_value);
}
});
$("#total_amount").val(calculated_total_sum);
});
});
//submit opening invoice data
$('#opening_invoice_form').on('submit', function(event){
event.preventDefault();
$.ajax({
url:"opening_invoice/create",
method:'post',
data:$(this).serialize(),
dataType:'json',
success:function(data)
{
$('#add_opening_invoice_modal').modal('hide');
swal({
title: "Success!",
text: "Opening Invoice Saved Successfully!",
type: "success",
showConfirmButton: false,
timer: 1500,
});
}
})
});
<form id="opening_invoice_form">
#csrf
<div class="modal-body">
<div class="col-lg-12 mt-4 mb-3">
<div class="table-responsive">
<table class="table table-hover align-items-center customizable-table text-center" id="opening_invoice_table">
<thead class="thead-light">
<tr>
<th scope="col">Date</th>
<th scope="col">Detail</th>
<th scope="col">Invoice No</th>
<th scope="col">Amount</th>
<th scope="col">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="date" class="form-control form-control-alternative date" name="date[]"></td>
<td><input type="text" class="form-control form-control-alternative detail" name="detail[]"></td>
<td><input type="text" class="form-control form-control-alternative invoice-no" name="invoice_no[]"></td>
<td><input type="number" class="form-control form-control-alternative amount" name="amount[]" min="0" step="any" placeholder="0.00"></td>
<td><a class="btn btn-sm delete-record btn-danger" id="delete_row"><i class="fas fa-trash-alt"></i></a></td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><label>Total Amount</label></th>
<th><input type="number" class="form-control form-control-alternative amount-calculate" name="total_amount" id="total_amount" placeholder="0.00" readonly></th>
<th></th>
</tr>
</tfoot>
</table>
<a class="btn btn-info pull-right add-record mt-2" data-added="0" title="Add Row" id="add_row"><i class="fa fa-plus"></i> Add Row</a>
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-lg-12 text-right">
<button type="submit" class="btn btn-success" id="sad"><i class="fas fa-download"></i> Save</button>
<button type="reset" class="btn btn-success"><i class="fas fa-eraser"></i> Clear</button>
<button type="button" class="btn btn-success" data-dismiss="modal"><i class="fa fa-window-close"></i> Close</button>
</div>
</div>
</form>
I'm trying to set value to header <th></th> where the input type is text. Below is my jquery that should put value in my th.
Here's my table format.
<table id="tblCustomer" class="display" style="width:100%">
<thead>
<tr>
<th>
<input type="button" class="btn btn-default" value="Update" />
</th>
<th>
<input id="Import_Sequence" name="Import_Sequence" type="text" value="" />
</th>
<th>
<input id="Line" name="Line" type="text" value="" />
</th>
</tr>
<tr>
<th>
</th>
<th data-toggle="tooltip" data-container="body" data-placement="top" title="">
Import_Sequence
</th>
<th data-toggle="tooltip" data-container="body" data-placement="top" title="Line number for reference.">
Line
</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
I already tried to hardcoded the value in:
th.val(sequence);
But still cannot show the value in <input id="Import_Sequence" name="Import_Sequence" type="text" value="" />
$("#tblCustomer > tbody > tr").click(function (event) {
var sequence = $(this).find("td:eq(1)").html();
var line_no = $(this).find("td:eq(2)").html();
var th = $('#tblCustomer thead tr').find("th:eq(1)");
th = th.find('input[name="Import_Sequence"]');
th.val(sequence);
});
When I remove the $('#tblCustomer').DataTable({"scrollX": true}); it works as expected.
<script>
$(document).ready(function () {
var tblCust = $('#tblCustomer').DataTable({
"aLengthMenu": [[20, -1], [20, "All"]],
iDisplayLength: 20,
bScrollInfinite: true, //this property disables pagination
"scrollCollapse": true,
"pagingType": "simple_numbers",
"lengthChange": false,
"bInfo": false,
"dom": 'lrtip',
"scrollX": true,
"autoWidth": true
});
tblCust.columns.adjust().draw();
$("#tblCustomer > tbody > tr").click(function (event) {
var sequence = $(this).find("td:eq(1)").html();
var line_no = $(this).find("td:eq(2)").html();
var th = $('#tblCustomer thead tr').find("th:eq(1)");
th = th.find('input[name="Import_Sequence"]');
th.val(sequence);
});
});
</script>
You have binded the above function to click event of $("#tblCustomer > tbody > tr") you you need to have tr inside your tbody and click on it.
$(function () {
$("#tblCustomer > tbody > tr").click(function (event) {
var sequence = $(this).find("td:eq(1)").html();
var line_no = $(this).find("td:eq(2)").html();
var th = $('#tblCustomer thead tr').find("th:eq(1)");
th = th.find('input[name="Import_Sequence"]');
th.val(sequence);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblCustomer" class="display" style="width:100%">
<thead>
<tr>
<th>
<input type="button" class="btn btn-default" value="Update" />
</th>
<th>
<input id="Import_Sequence" name="Import_Sequence" type="text" value="" />
</th>
<th>
<input id="Line" name="Line" type="text" value="" />
</th>
</tr>
<tr>
<th>
</th>
<th data-toggle="tooltip" data-container="body" data-placement="top" title="">
Import_Sequence
</th>
<th data-toggle="tooltip" data-container="body" data-placement="top" title="Line number for reference.">
Line
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Td 1
</td>
<td>
click here
</td>
</tr>
</tbody>
</table>
If you want your code to be executed on load of the page then simply add your code inside document ready
$(function() {
var sequence = $(this).find("td:eq(1)").html();
var line_no = $(this).find("td:eq(2)").html();
var th = $('#tblCustomer thead tr').find("th:eq(1)");
th = th.find('input[name="Import_Sequence"]');
th.val(sequence);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tblCustomer" class="display" style="width:100%">
<thead>
<tr>
<th>
<input type="button" class="btn btn-default" value="Update" />
</th>
<th>
<input id="Import_Sequence" name="Import_Sequence" type="text" value="" />
</th>
<th>
<input id="Line" name="Line" type="text" value="" />
</th>
</tr>
<tr>
<th>
</th>
<th data-toggle="tooltip" data-container="body" data-placement="top" title="">
Import_Sequence
</th>
<th data-toggle="tooltip" data-container="body" data-placement="top" title="Line number for reference.">
Line
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
Td 1
</td>
<td>
copy its html
</td>
</tr>
</tbody>
</table>
Try to use .html to add text and html tags and add function to the update button using jquery.
html:
<input type="button" class="btn btn-default" value="Update" id='update' />
<table id="tblCustomer" class="display" style="width:100%">
<td =id='tdId'></td>
</table>
for example:
<script>
$(document).ready( function ()
{
$('#update').click(function(){
$Imp_Sequence = $('input[name="Import_Sequence"]').val();
$("#tblCustomer #tdId").html("<p>" + $Imp_Sequence + "</p>")
})
})
</script>
i have a table when the table row is selected.i want that particular row to be appended in another table.
<table class="myTable" border="1">
<tr class="table">
<th class="table">
ID
</th>
<th class="table">
Name
</th>
<th class="table">
Price
</th>
</tr>
<tr class="table">
<td class="table">
1
</td>
<td class="table">
A
</td>
<td class="table">
1500
</td>
<td>
<input type="checkbox" name="">
</td>
</tr>
<tr class="table">
<td class="table">
2
</td>
<td class="table">
B
</td>
<td class="table">
3455
</td>
<td>
<input type="checkbox" name="">
</td>
</tr>
</table>
<table id="printTable" border="1">
<tr>
<td>ID</td>
<td>Name</td>
<td>Price</td>
</tr>
</table>
i have a popup page where i have a table with multiple checkbox.When the user select any of the checkbox and clicked on button that particular row has to be saved from popup page to parent page
<script>
$("table tr").click(function() {
var items=[];
var tablerow = $(this).closest("tr").clone();
var tableData = $(this).children("td").map(function() {
return $(this).text();
}).get();
alert("Your data is: " + $.trim(tableData[0]) + " , " + $.trim(tableData[1]) + " , " + $.trim(tableData[2]));
$(tablerow).children("td:last").html(tableData);
items.push(tablerow);
alert(items);
tablerow.appendTo($("#printTable"));
});
</script>
There is no need to map all the data, you can just clone the tr and append it to the other table. Like so:
<script>
$("table tr").click(function () {
// If you don't use a tbody, remove 'tbody' here
$("#printTable tbody").append($(this).clone());
});
</script>
EDIT: Used loop instead repeating
Probably not the best answer, but this can insert the value into the second table regardless to the column sorting.
https://jsfiddle.net/o4copkrz/2/
$("#input tr").click(function(){
var $this = $(this)
var arrIndex = ["id", "name", "price"]
var arrData = []
for (var i = 0; i < arrIndex.length; i++) {
arrData[arrIndex[i]] = $this.find("[data-" + arrIndex[i] + "]").text()
}
var $clone = $("#output thead tr").clone()
for (var i = 0; i < arrIndex.length; i++) {
$clone.find("[data-" + arrIndex[i] + "]").text(arrData[arrIndex[i]])
arrIndex[i]
};
$clone.appendTo($("#output tbody"))
})
<h3>First clone the row by clicking on row, then click on button to add to another table</h3>
<table id="firstTable">
<tr>
<th>id</th>
<th>Name</th>
<th>Price</th>
<th>Select</th>
</tr>
<tr class="row">
<td>1</td>
<td>Comp</td>
<td>2000</td>
<td class="removeIt"><input type="checkbox" name="rowSelect" class="selectCheck"/></td>
</tr>
<tr class="row">
<td>2</td>
<td>mouse</td>
<td>3000</td>
<td class="removeIt"><input type="checkbox" name="rowSelect" class="selectCheck"/></td>
</tr>
<tr>
</table>
<button id="appendToTable">Append to table</button>
<table id="printTable">
<tr>
<th>id</th>
<th>Name</th>
<th>Price</th>
</tr>
</table>
<div id="clonedData" style="display: none;"></div>
<script>
$(".selectCheck").click(function() {
if($(this).prop("checked") == true){
$("#clonedData").append($(this).parent().parent().clone());
$("#clonedData").find(".removeIt").remove();
}else{
var rowCheck = $(this).parent().parent().clone();
rowCheck.children(".removeIt").remove();
$('#clonedData tr').each(function(){
if(rowCheck.html()==$(this).html()){
$(this).remove();
}
});
}
});
$("#appendToTable").click(function() {
$("#printTable").append($("#clonedData").children().clone());
$("#clonedData").html('');
});
I have also created a fiddle https://jsfiddle.net/kgbet3et/11/ for the same. Please check if it adresses your issue.
$('#myModal').modal('toggle');
$(document).on('change', 'input[type="checkbox"]', function(e){
if($(this).is(":checked"))
{
var row = $(this).closest('tr').html();
$('.table2 tbody').append('<tr>'+row+'</tr>');
}
else
{
$('#row').find('input:checkbox[value="' + $(this).val() + '"]').closest('tr').remove();
}
$('#row').on('click', ':checkbox', function (event) {
$(this).closest('tr').remove();
});
});
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<body>
<div class="col-md-6">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<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">
<table class="table1 table table-bordered" id="echo">
<h3 style="text-align: center;"></h3>
<tr>
<td>1</td>
<td name="echo">A</td>
<td>1500</td>
<td><input type="checkbox" value="1" class="check-box"></td>
</tr>
<tr>
<td id="2">2</td>
<td name="fetal_echo">B</td>
<td>2000</td>
<td><input type="checkbox" value="2" class="check-box"></td>
</tr>
<tr>
<td id="1">3</td>
<td value="abc">C</td>
<td>8500</td>
<td><input type="checkbox" value="3" class="check-box"></td>
</tr>
<p id="output"></p>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal" id="closebtn">Close</button>
</div>
</div>
</div>
</div>
<table class="table2 table table-bordered" id="row">
<tbody>
</tbody>
</table>
<div>
#vijay mishra and #Vishnu Bhadoriya thankyou for your support....You are really awesome.
I think I got problem with js and html (bootstrap),
I got these snippet from bootsnip and try to modified it for need of my job.
but on the third lines, sorry for typo or bad using english.
the bootsnip here (my modification) : http://bootsnipp.com/snippets/o8r0G
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#addr'+i).html("<td>"+ (i+1) +"</td><td><input name='name"+i+"' type='text' placeholder='Name' class='form-control input-md' /> </td><td><input name='mail"+i+"' type='text' placeholder='Mail' class='form-control input-md'></td><td><select class='form-control' name='slct"+i+"' placeholder='Select'><option value='1'>1</option><option value='2'>2</option></select></td>");
$('#tab_logic').append('<tr id="addr'+(i+1)+'"></tr>');
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
$('.buttonx').click(function() {
var total = 0;
$('#tab_logic tbody tr').each(function(index) {
var price = parseInt($(this).find('.optx sltx option value').text());
var quantity = parseInt($(this).find('.optx sltx option').val());
var value = $(this).find('.value');
var subTotal = price * quantity;
value.text(subTotal);
value.text(price);
total = total + subTotal;
testotal = price;
});
$('.totality').text('Total : '+testotal);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Value1
</th>
<th class="text-center">
Value2
</th>
<th class="text-center">
Select
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input type="text" name='va10' placeholder='Val1' class="form-control"/>
</td>
<td>
<input type="text" name='va20' placeholder='Val2' class="form-control"/>
</td>
<td class="optx">
<select class="form-control sltx" name="slct0" placeholder="Select"><option value="1">1</option><option value="2">2</option></select>
</td>
</tr>
<tr id='addr1'></tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><a id="buttonx" class="btn btn-default btn-danger pull-right">Calculate</a></th>
<th id="totality" style="vertical-align: middle;">Total : </th>
</tr>
</tfoot>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
I'm trying to create the total from the table but I can't load the value from table with js, maybe I got wrong on the script which I got from other answer on stack. Reference is here : getting values from a html table via javascript/jquery and doing a calculation
I want to ask, how can I got the calculation from select option on table, alternatively from input textbox and without I push the button (real time calculation).
Thanks before.
Well, as per my understand-ability, you need a real time calculator, which calculate value as user entering and leave any textbox or change the select without using the calculate button.
In your code there are some error, I have built and change some of your function to implement the real time calculator. calculation formula is different because I am not able to understand how you are going to calculate. I am implementing it using the class selector of the element and fetching the value with the use of this.
Here is the updated code which is using both, on click button and also real time calculator.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<div class="container">
<div class="row clearfix">
<div class="col-md-12 column">
<table class="table table-bordered table-hover" id="tab_logic">
<thead>
<tr >
<th class="text-center">
#
</th>
<th class="text-center">
Value1
</th>
<th class="text-center">
Value2
</th>
<th class="text-center">
Select
</th>
</tr>
</thead>
<tbody>
<tr id='addr0'>
<td>
1
</td>
<td>
<input type="text" name='va10' placeholder='Val1' class="form-control va10"/>
</td>
<td>
<input type="text" name='va20' placeholder='Val2' class="form-control va20"/>
</td>
<td class="optx">
<select class="form-control sltx slct0" name="slct0" placeholder="Select"><option value="1">1</option><option value="2">2</option></select>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
<th><a id="buttonx" class="btn btn-default btn-danger pull-right">Calculate</a></th>
<th id="totality" style="vertical-align: middle;">Total : </th>
</tr>
</tfoot>
</table>
</div>
</div>
<a id="add_row" class="btn btn-default pull-left">Add Row</a><a id='delete_row' class="pull-right btn btn-default">Delete Row</a>
</div>
<script type="text/javascript">
$(document).ready(function(){
var i=1;
$("#add_row").click(function(){
$('#tab_logic').append("<tr id='addr"+i+"'><td>"+ (i+1) +"</td><td><input name='name'"+i+" type='text' class='form-control va10' placeholder='Name' class='form-control input-md' /> </td><td><input name='mail'"+i+"' type='text' placeholder='Mail' class='va20 form-control input-md'></td><td><select class='form-control slct0' name='slct'"+i+" placeholder='Select'><option value='1'>1</option><option value='2'>2</option></select></td></tr");
i++;
});
$("#delete_row").click(function(){
if(i>1){
$("#addr"+(i-1)).html('');
i--;
}
});
});
function calculator(){
var total = 0;
$('#tab_logic tbody tr').each(function(index) {
var val1 = $(this).find('.va10').val().length==0?0:parseInt($(this).find('.va10').val());
var val2 = $(this).find('.va20').val().length==0?0:parseInt($(this).find('.va20').val());
var select = $(this).find('.slct0').val().length==0?0:parseInt($(this).find('.slct0').val());
var subTotal = (val1 + val2)*select;
total+=subTotal;
});
$('#totality').text(total);
}
$('#tab_logic').on('blur change','.va10,.va20,.slct0',function(){
calculator()
})
$('#buttonx').click(function() {
calculator();
});
</script>
I am trying to update a row using jQuery Ajax.
When i click on Edit button it changes <tr> to <input type='text'>, I have added .Change method and it successfully fires but i want to change it back to <tr> when change event is fired.
Kindly check it and guide me how to change it back to <tr> whenever user updates a row.
Thanks
var editing = false;
$(document).on("click", ".updateUser", function() {
if (!editing) {
editing = true;
$(this).closest('tr').find('.edited').each(function() {
var html = $(this).html();
var input = $('<input type="text" />');
input.val(html);
$(this).html(input);
});
}
}).change(function() {
editing = false;
alert("change Event");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<table class=" table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Password</th>
<th>Role</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td class="id edited">ID</td>
<td class="id edited">Username</td>
<td class="id edited">Password</td>
<td class="id edited">Role</td>
<td>
<button type="button" class="updateUser btn btn-primary btn-xs" data-userId="<?php echo $id; ?>">
EDIT BUTTON
</button>
</td>
</tr>
<!-- ROW 2 -->
<tr>
<td class="id edited">ID</td>
<td class="id edited">UsernameText</td>
<td class="id edited">PasswordText</td>
<td class="id edited">RoleText</td>
<td>
<button type="button" class="updateUser btn btn-primary btn-xs" data-userId="<?php echo $id; ?>">
EDIT BUTTON
</button>
</td>
</tr>
</tbody>
</table>
All you have to do is the reverse of what you already have done:
var editing = false;
$(document)
.on(
"click",
".updateUser",
function(){
if(!editing){
editing = true;
$(this)
.closest('tr')
.find('.edited')
.each(
function() {
var html = $(this).html(),
input = $('<input type="text" />');
input.val(html);
$(this).html(input);
}
);
}
}).change(
function(e){
if(editing){
editing = false;
$(e.target)
.closest('tr')
.find('.edited')
.each(
function() {
var val = $(this).children('input').val();
$(this).html(val);
}
);
}
});
JS Bin here.
I've changed your jquery and it's working. I've added change event for .edited input and also a little change in .updateUser click event.
var editing = false;
$(document).on("click", ".updateUser", function() {
if (!editing) {
editing = true;
$(this).closest('tr').find('.edited').each(function() {
if (!$(this).find('input').length) {
var html = $(this).text();
var input = $('<input type="text" />');
input.val(html);
$(this).html(input);
}
});
}
}).on('change', '.edited input', function() {
$(this).parent().text(this.value);
editing = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<table class=" table table-hover">
<thead>
<tr>
<th>#</th>
<th>Username</th>
<th>Password</th>
<th>Role</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
<tr>
<td class="id edited">ID</td>
<td class="id edited">Username</td>
<td class="id edited">Password</td>
<td class="id edited">Role</td>
<td>
<button type="button" class="updateUser btn btn-primary btn-xs" data-userId="<?php echo $id; ?>">
EDIT BUTTON
</button>
</td>
</tr>
<!-- ROW 2 -->
<tr>
<td class="id edited">ID</td>
<td class="id edited">UsernameText</td>
<td class="id edited">PasswordText</td>
<td class="id edited">RoleText</td>
<td>
<button type="button" class="updateUser btn btn-primary btn-xs" data-userId="<?php echo $id; ?>">
EDIT BUTTON
</button>
</td>
</tr>
</tbody>
</table>
This is also a fine solution to inline editing in a table row - JSBIN
$(document).on("click", ".updateUser", function() {
var editing = false;
if (!editing) {
editing = true;
$(this).closest('tr').find('.edited').each(function() {
var html = $(this).html();
var input = $('<input type="text" />');
input.val(html);
$(this).html(input);
});
$(this).addClass('save');
$(this).removeClass('updateUser');
}
});
$(document).on('click', '.save', function(){
$(this).closest('tr').find('input').each(function(){
$(this).closest('td').html($(this).val());
$(this).remove();
});
$(this).removeClass('save');
$(this).addClass('updateUser');
});