Update a HTML table record via jQuery - javascript

I have created a form with only three inputs, a HTML table and a submit button
<div class="form-group">
<input type="text" id="inputText1" required>
<input type="text" id="inputText2" required>
<input type="text" id="inputText3" required>
</div>
<button type="button" class="btn btn-default" id="submit">Submit</button>
</form>
<div class="table-responsive">
<table class="table table-striped table-bordered table-condensed" id="myTable" style="width:90%; margin:0 auto;">
<thead>
<tr>
<th>ID</th>
<th>Last Name</th>
<th>Username</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
that works this way:
every time the user clicks the submit button the HTML table adds to its rows the value of the inputs via jQuery + two linkbuttons and the variable cont specified as a number in a hidden element in order to easily locate the row when it comes to update it.
$(document).ready(function () {
var cont=0;
$("#submit").click(function(e) {
e.preventDefault();
cont++;
var id = $("#inputText1").val().toLowerCase();
var lastname = $("#inputText2").val();
var name = $("#inputText3").val();
if (checkId(lastname)) {
return alert('El ID ya ha sido especificado');
}
$('#myTable tbody').append('<tr><td for="id">' + id + '</td><td for="lastname">' + lastname + '</td><td>' + name + '</td><td id="cont" style="visibility:hidden">' + cont + '</td><td>Modificar Eliminar</td></tr>');
$("#inputText1").val('');
$("#inputText2").val('');
$("#inputText3").val('');
$('#inputText1').focus();
});
});
the submit button works OK the problem is when I want to modify a row, what I do now is to populate the inputs with the values of the row selected in order to let the user to modify its content but I cannot retrieve the value of the variable cont that represents an specific and different number for each row and besides of that I don't know how to update the table's row once the user decide to update the record, could you please help me, this is the jQuery code I had for the moment
$(document).ready(function () {
$("#myTable").on('click', '#select', function (e) {
e.preventDefault();
var currentRow = $(this).closest("tr");
//var contador= currentRow.$("#cont").val();
//alert(contador);
//doesn't retrieve neither show anything
var col1 = currentRow.find("td:eq(0)").text();
var col2 = currentRow.find("td:eq(1)").text();
var col3 = currentRow.find("td:eq(2)").text();
$("#inputText1").val(col1);
$("#inputText2").val(col2);
$("#inputText3").val(col3);
});
});
and also would like to dd that when the user add the info from the inputs to the table, theres a gap where the hidden field is
how could I solve this?

Related

Storing count of table rows in a JS variable

I have some old code I am trying to poke through. This table is loaded via a Controller action returning a model, based off of a button click somewhere else in the page.
How can I find the number of rows in the table in a JS variable? I am terrible with JS. I have tried a few things and nothing has worked. Below is my code and also what I have tried to do to store the num of rows.
Table:
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
Here is what I have tried to do in JS:
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
console.log(rowId);
console.log(row);
Results from the console.log don't appear to be accurate. Anything helps. Thanks
Probably you want the number of rows of your table.
// javascript
var rowsInTable = document.getElementById("terminalReceipts").getElementsByTagName("tr").length;
//jquery
var rowsInTable2 = $("#customers").children('tbody').children('tr').length;
//if you need to do something with the rows:
var rows = $("#customers").children('tbody').children('tr');
rows.each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
you can also do that using jquery like this
var totalRowCount = $("#terminalReceipts tr").length; //this will give +1 row
var rowCount = $("#terminalReceipts td").closest("tr").length; //this will give actual row

Jquery append new data to old ones has duplicate issue

How can I add new data to old ones without duplicate my tables?
logic
I select option, data returns in table
I select different option, data adds to old ones
Issue
When I do second part of my logic it add new table as well, meaning based on how many times i change my selected option it adds new tables.
Screenshot
when i select my first option having 1 table
when i select my second option having 2 tables
What I want
What I want is when i select my second/third etc. option image 2, only have 1 table include data of all those past and current options and not to make 1 table for each of them.
Code
HTML
<div class="mt-20 options"></div>
JavaScript
<script>
$(function(){
$('select[name="options"]').on('change', function() {
var addressID = $(this).val();
if(addressID) {
$.ajax({
url: '{{ url('admin/getoptions') }}/'+encodeURI(addressID),
type: "GET",
dataType: "json",
success:function(data) {
// $('div.options').empty();
$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>'+
'<table id="table" class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th width="50" class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// 2. Loop through all entries
var keys = ['title'];
data.forEach(function(row) {
var $row = $('<tr />');
$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row['id']+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');
$('#table tbody').append($row);
});
}
});
}else{
$('div.options').empty();
}
});
});
</script>
Any idea?
Here are the steps to take:
Remove the $('div.options').append( ... ) call
Add the following HTML to your static div element, and hide it with style="display:none":
<div class="mt-20 options" style="display:none">
<div class="mb-20"><h4>Check mark your needed options only</h4></div>
<table id="table" class="table table-bordered table-hover table-responsive">
<thead>
<th width="50" class="text-center">Check</th>
<th class="text-center">Title</th>
<th class="text-center">Price</th>
</thead>
<tbody>
</tbody>
</table>
</div>
Add code after the data.forEach loop, to unhide the div:
$('#table tbody').append($row);
}); // end of loop
$("div.options").show(); // <---
First you need to build your table once. But you are appending new tables every success call. That happens in the line:
$('div.options').append('<div class="mb-20">...
That append is actually creating the table and appending it to the div.
Instead you should create the table only one time before the success callback, then just update it with the new data.
$(function(){
var updateTable = function() {
var addressID = $(this).val();
var data = JSON.parse(addressID);
// show the table div
$('div.options').show();
// clear old rows
$('tbody', myTable).empty();
// 2. Loop through all entries
var keys = ['title'];
data.forEach(function(row) {
var $row = $('<tr />');
$row.append('<td class="text-center" width="50"><label class="switch switch-small"><input type="checkbox" /><span><input class="form-control" type="text" name="optionID[]" value="'+row+'"></span></label></td>');
keys.forEach(function(key) {
$row.append('<td>' + row[key] + '</td>');
});
$row.append('<td class="text-center"><input class="form-control" placeholder="if fill this price, the price will add to product price when user select it." type="number" name="optionPRICE[]"></td>');
$('tbody', myTable).append($row);
});
};
// create and save table for later manipulations
var myTable = $('<table class="table table-bordered table-hover table-responsive">'+
'<thead>'+
'<th width="50" class="text-center">Check</th>'+
'<th class="text-center">Title</th>'+
'<th class="text-center">Price</th>'+
'</thead>'+
'<tbody></tbody>'+
'</table>');
// append h4
$('div.options').append('<div class="mb-20"><h4>Check mark your needed options only</h4></div>');
// append the table
$('div.options').append(myTable);
// select event
$('select[name="options"]').on('change', updateTable);
updateTable.call($('select[name="options"]').first());
});
{"d":4,"e":5,"f": 6}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="options">
<option value="[1,2,3]">Data1</option>
<option value="[4,5,6]">Data2</option>
</select>
<div class="options"></div>

how to generate dynamic table

I have data with me , which is one dropdown data and one from textbox values which i generate dynamic and get the values.
now i want to generate the table from these value. I get values in alert but I struggling to generate the table
here is my code:
$('#save_skills').on("click",function(){
$('.importance option:selected').each(function(){
importance = $(this).text();
})
$('input.skill ').each(function() {
skill = $(this).val();
alert(skill);
});
$('#div_skills').append('<table class="table table-bordered"><tr><td>'+ skill +'</td><td>'+ importance +'</td></tr></table>')
});
I tried this but i get only last record, how to use for loop for below code, I am confused:
$('#div_skills').append('<table class="table table-bordered"><tr><td>'+ skill +'</td><td>'+ importance +'</td></tr></table>')
i generate this html dynamically:
$("#addSkills_link").on("click", function () {
$("#table_skills").
append('<tr><td><input type="text" class="form-control skill" id="new_skill" placeholder="Skills"></td><td><select class="form-control importance" id="ddl_skills"><option value="">Select importance</option><option value="">1</option><option value="">2</option><option value="">3</option><option value="">4</option><option value="">5</option><option value="">6</option><option value="">7</option><option value="">8</option><option value="">9</option><option value="">10</option></select></td>');
});
You need to join all values like,
var importance = [],skill=[];
$('#save_skills').on("click",function(){
$('.importance option:selected').each(function(){
importance.push($(this).text());
});
$('input.skill').each(function() {
skill.push($(this).val());
});
$('#div_skills').append('<table class="table table-bordered"><tr><td>'+ skill.join(', ') +'</td><td>'+ importance.join(', ') +'</td></tr></table>')
});
Updated, after the comment php | 8 and in second row: java | 9 your code should be like,
$('#save_skills').on("click",function(){
table = $('<table class="table table-bordered"></table>').appendTo($('#div_skills').empty())
$('input.skill').each(function(index) {
skill= $(this).val();
importance= $('.importance').eq(index).find('option:selected').text();
table.append('<tr><td>'+skill+'</td><td>'+importance+'</td></tr>');
});
});
#div_skills{border:1px solid #0cf}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table><tr><td><input type="text" class="form-control skill" id="new_skill" placeholder="Skills"></td><td>
<select class="form-control importance" id="ddl_skills"><option value="">Select importance</option><option value="">1</option><option value="">2</option><option value="">3</option><option value="">4</option><option value="">5</option><option value="">6</option><option value="">7</option><option value="">8</option><option value="">9</option><option value="">10</option></select></td></tr>
<tr><td><input type="text" class="form-control skill" id="new_skill" placeholder="Skills"></td><td>
<select class="form-control importance" id="ddl_skills"><option value="">Select importance</option><option value="">1</option><option value="">2</option><option value="">3</option><option value="">4</option><option value="">5</option><option value="">6</option><option value="">7</option><option value="">8</option><option value="">9</option><option value="">10</option></select></td></tr>
</table>
<div id="div_skills"></div>
<button id="save_skills">Save Skills</button>
Just add your table in your html like so :
<table class="table table-bordered" id="div_skills_table"></table>
And modify your script with this :
$('input.skill').each(function() {
skill = $(this).val();
$('#div_skills_table').append('<tr><td>'+ skill +'</td><td>'+ importance +'</td></tr>');
});
It will add a new row per skill

Find Table Row Index for Dynamically Generated Table

Here is my scenario:
I have a table that displays the Name, Age, and Details content on each row. When a user selects the Details button, it should trigger a modal and show additional content specific to that Person in the table.
Issue at hand:
I am using Razor syntax and dynamically generating the rows within the table.
Question: How can I get the row index value for that specific row when selecting the Details button
Additional Notes:
I did some research online, but couldn't find anything that helped me in my scenario.
Html
<div class="col-md-12">
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Details</th>
</tr>
</thead>
<tbody>
#foreach (var viewModel in Model)
{
<tr>
<td>#viewModel.Name</td>
<td>#viewModel.Age</td>
<td><button onclick="PersonViewModel(this)" type="button" class="btn btn-success" data-toggle="modal" data-target="#details-modal"><span class="fa fa-external-link-square"></span> Details</button></td>
</tr>
}
</tbody>
</table>
</div>
JavaScript:
function PersonViewModel(x) {
$('body').on('click', 'a.showMore', function(event) {
var rowIndex = $(this).closest('tr').index();
alert("Row index is: " + rowIndex);
});
}
You are binding event in the PersonViewModel click handler. In order to get the index of parent tr, you need to use the x object.
Use
function PersonViewModel(x) {
var rowIndex = $(x).closest('tr').index();
alert("Row index is: " + rowIndex);
}
You can try like this. I think this will help you.
$(this).parents('tr')).index()
This will give you parent tr and index() function will give index of that tr.
Please check my code instead of your
function PersonViewModel(x) {
var index = $(".table tr").index( $(x).parents('tr'));
alert(index);
}

How to add to arraylist in javascript

I am using javascript for my server side validation.I need to add all data from a table which is dynamically generated while clicking an add button.
Clicking ADD button section is working fine.Also i added date picker to 2nd and 3rd columns.its working fine.The code is given below.....
function addRow(tableId) { //Add new row to given table having id tableId
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = '<input type="text" id="code'+ rowCount +'" name="code" maxlength="16"/>';
cell2.innerHTML = '<input type="text" id="datepicker2'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell3.innerHTML = '<input type="text" id="datepicker3'+ rowCount +'" class="datepicker" name="validFrom" maxlength="50" >';
$('.datepicker').datepicker({
format: 'yyyy-mm-dd'
});
cell4.innerHTML = '<input type="button" id="del'+ rowCount +'" name="del" />';
Html code
<div class="systemsettings">
<h3><spring:message code="systemSetting.ratePeriods.label"/></h3>
</div>
<div class="systemset" >
<!-- table table-hover table-striped table-bordered table-highlight-head-->
<table id="systemsettingstid" class="table-bordered table-striped">
<thead class="tax_thead" id="tdDetailList">
<tr >
<!-- <th>Applicable From</th> -->
<th width="200" id="code" title="Code" >Code</th>
<th width="200" id="from" title="from ">from</th>
<th width="200" id="to" title="to">to</th>
<th width="50" id="del" title="del">del</th>
<!-- <th width="45" ><div class="add_new">
</div></th> -->
</tr>
</thead>
<tbody></tbody>
</table>
</div>
<div>
<tr>
<button type="button" onClick="javascript:addRow('systemsettingstid');">Add</button>
</tr>
</div>
DELETE BUTTON:
I have a delete button also appended inside the html code.
While clicking it the corresponding row should be deleted(fixed automatically while clicking add button on every row).
MY PROBLEM:
Adding and delete does not affect back end it just need to alter in an arraylist.
During final form submission the arraylist needs to go to backend(built in spring mvc).
1) Can we create an arraylist in javascript?
2) If we can how to add the text boxes and date picker details into arraylist?.
4) How to pass that arraylist in to my spring mvc controller?
NB:I am new to javascript.Any help will be highly appreciable.
<script>
var tdDetailList = [];
function init() {
var tdDetailTable = document.getElementById("tdDetailTable");
for (var i = 0, row; row = tdDetailTable.rows[i]; i++) {
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
tdDetailList.push(tdDetail);
}
alert(getDetailTableJson());
}
function deleteRow(index){
tdDetailList.splice(index, 1);
var tdDetailTable = document.getElementById("tdDetailTable");
tdDetailTable.deleteRow(index);
alert(getDetailTableJson());
}
function getDetailTableJson(){
return JSON.stringify(tdDetailList);
}
</script>
<body onload="init();">
<table id="tdDetailTable">
<tr><td>1</td><td>2</td><td>3</td><td>del</td></tr>
<tr><td>4</td><td>5</td><td>6</td><td>del</td></tr>
</table>
</body>
Can we create an arraylist in javascript?
Yes. In my example var tdDetailList = []; is array (list).
You can add elements to it:
tdDetailList.push(tdDetail);
and remove element in index: tdDetailList.splice(index, 1);
If we can how to add the text boxes and date picker details into arraylist?.
You can create object like:
var tdDetail = {code : row.cells[0].innerHTML, datepicker2 : row.cells[1].innerHTML, datepicker3 : row.cells[2].innerHTML};
with fields of your table and add the object to your list.
How to pass that arraylist in to my spring mvc controller?
Convert the list to json
JSON.stringify(tdDetailList);
In my example: "[{"code":"1","datepicker2":"2","datepicker3":"3"},{"code":"4","datepicker2":"5","datepicker3":"6"}]"
and send.
If you want to add and delete using JAVA SCRIPT then it will very complex and lengthy.
But using JQUERY it will work fine and easily you can handle ADD, DELETE actions also
use JQUERY and in this append and remove methods are there you can use it and insert a row in table and delete a row in table
May be you new in jQUERY but once you get it, its amazing than JAVA SCRIPT
Hope you getting let me know if you have any confusion. ['}

Categories

Resources