How to remove an item from the array on button click - javascript

I have a table with few rows and delete button. I have stored all the list of table in an array 'arr'. How can I remove the selected item from that array on button click.
<table id="sum_table">
<tr class="titlerow">
<th>S.N.</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td>John</td>
<td><button class="dm" data-id="0">Remove</button></td>
</tr>
<tr>
<td>2</td>
<td>Henry</td>
<td><button class="dm" data-id="1">Remove</button></td>
</tr>
</table>
var arr= [
["name", John],
["name", Henry]
];
function clickHandler(clickEvent) {
}
document.addEventListener('DOMContentLoaded', function() {
document.addEventListener('click', clickHandler);
});

Your array need to be an array of object and not an array of array. Also you can give a class to the name column of a table to access its value and then use findIndex to find the index of the name attribute in array and then splice to remove it.
$(function(){
var arr= [
{"name": "John"},
{"name": "Henry"}
];
$('.dm').click(function(){
var val = $(this).closest('tr').find(".name").text();
console.log(val);
var index = arr.findIndex(function(item) {return item.name == val})
console.log(index)
arr.splice(index, 1)
console.log(arr);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="sum_table">
<tr class="titlerow">
<th>S.N.</th>
<th>Name</th>
<th>Action</th>
</tr>
<tr>
<td>1</td>
<td class="name">John</td>
<td><button class="dm" data-id="0">Remove</button></td>
</tr>
<tr>
<td>2</td>
<td class="name">Henry</td>
<td><button class="dm" data-id="1">Remove</button></td>
</tr>
</table>

Lets say you send the name of the person on click event then you can use array.splice method as shown below :
for(var i = arr.length - 1; i >= 0; i--) {
if(arr[i] === name) {
arr.splice(i, 1);
}
}
You have to note that it will delete all the values from array which has the same name.
With Index - Just send the data-id on click of button and splice the array on that index
arr.splice(dataid, 1)

Related

Print array in the table td

I am new in Javascript, I have an array, and want to print it in the table td.
This is my array:
array = [100, 200, 300];
This is my table:
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
I want to print my array in the td with class name 'result'
You can use querySelectorAll() and Node.textContent:
const array = [100, 200, 300];
const elements = [...document.querySelectorAll('.result')];
for(let i = 0; i < array.length; i++) {
elements[i].textContent = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Just iterate over the array and use the current index for the HTML element as well.
Possible ES5-only solution:
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
document.getElementsByClassName("result")[i].innerHTML = array[i];
}
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 2</td>
<td class='result'></td>
</tr>
<tr>
<td> My result 3</td>
<td class='result'></td>
</tr>
</tbody>
</table>
Note: You need an equal amount of array elements and elements with the .result class.
Assign an id attribute to the table tag, id = "tab". Then add the below javascript code
pointer=0
arr=[100,200,300];
// selecting all the tags having result as class name
var nodes=document.getElementById("tab").getElementsByClassName("result");
arr.forEach((ele)=>{nodes[pointer].innerHTML=ele;pointer+=1});
Look at this example:
I use querySelectorAll
It considers the case if the array elements and the quantity of rows are diffrerent.
Also added '.myTable' to prevent target other '.result' nodes out of the selected table.
Hope it helps.
<table class="myTable">
<th> Result</th>
<tbody>
<tr><td> My result 1</td><td class='result'></td></tr>
<tr><td> My result 2</td><td class='result'></td></tr>
<tr><td> My result 3</td><td class='result'></td></tr>
<tr><td> My result 4</td><td class='result'></td></tr>
</tbody>
</table>
<script>
const array = [100, 200, 300];
const rows = document.querySelectorAll('.myTable .result') // <-- I added '.myTable' to prevent target other '.result' nodes out of the selected table
rows.forEach((row, i) => {
if (array[i]) row.innerHTML = array[i] // <-- I replace the innerHTML if the array has content at that index
});
</script>
You can do this,
var result = document.getElementsByClassName("result")
var array = [100,200,300]
for (var i=0;i<result.length;i++){
result[i].innerHTML = array[i];
}
Demo
Hope this helps you... No need to update table according to array data....
Table code:
<table>
<th colspan="2" >Result</th>
<tbody id="myTableBody"></tbody>
</table>
JavaScript code:
<script>
var tableRef = document.getElementById('myTableBody');
var array = [100, 200, 300];
for (var i = 0; i < array.length; i++){
tableChild = document.createElement('tr');
tableChild.innerHTML = "<td> My result "+(i+1)+"</td><td class='result'>"+array[i]+"</td>";
tableRef.appendChild(tableChild);
}
</script>
Example: https://codepen.io/Nishanth_V/pen/rEZmxN
var el = document.getElementsByClassName('result');
var array = [100, 200, 300];
for(var i =0 ; i < el.length && i < array.length; ++i) {
el[i].innerHTML = array[i];
}
You have to replace ' by " and add numbers to your class , after that your code with look like this:-
<table>
<th> Result</th>
<tbody>
<tr>
<td> My result 1</td>
<td class="result1"></td>
</tr>
<tr>
<td> My result 2</td>
<td class="result2"></td>
</tr>
<tr>
<td> My result 3</td>
<td class="result3"></td>
</tr>
</tbody>
</table>
Your JavaScript code will look like this:-
<script>
var array = [100, 200, 300];
array.foreach(function (item, index){
var resultNum = index + 1;
document.getElementByClassName("result" + resultNum).innerHTML = item;
});
</script>

Hide empty html table rows

Problem
I have a table with one or more empty rows. How to hide empty rows from the table?
For example
1 - John | Alfredo
2 - Mark | Zuck
3 - |
4 - Carl | Johnson
In this case, I'd like to delete the third row.
Step Tried
I found how to delete a specific row, what about deleting all the empty rows?
deleteEmptyRows();
function deleteEmptyRows() {
var myTable = document.getElementById("myTable")
var rowToDelete = 2;
myTable.deleteRow(rowToDelete)
}
<table border="1" cellspacing="1" cellpadding="1" id ="myTable">
<tbody>
<tr>
<td>John</td>
<td>Alfredo</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuck</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Carl</td>
<td>Johnson</td>
</tr>
</tbody>
</table>
This is how you can dynamically hide empty table rows with javascript.
deleteEmptyRows();
function checkIfCellsAreEmpty(row) {
var cells = row.cells;
var isCellEmpty = false;
for(var j = 0; j < cells.length; j++) {
if(cells[j].innerHTML !== '') {
return isCellEmpty;
}
}
return !isCellEmpty;
}
function deleteEmptyRows() {
var myTable = document.getElementById("myTable");
for(var i = 0; i < myTable.rows.length; i++) {
var isRowEmpty = checkIfCellsAreEmpty(myTable.rows[i]);
if (isRowEmpty) {
myTable.rows[i].style.display = "none";
}
}
}
<table border="1" cellspacing="1" cellpadding="1" id ="myTable">
<tbody>
<tr>
<td>John</td>
<td>Alfredo</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuck</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Carl</td>
<td>Johnson</td>
</tr>
</tbody>
</table>
Here, a simple method for row is empty (this allows us to check for other conditions easily later).
Loop over rows and call remove if empty.
const rowIsEmpty = (tr) => Array.from(tr.querySelectorAll('td')).every(td => td.innerText === "");
deleteEmptyRows();
function deleteEmptyRows() {
var myTable = document.getElementById("myTable");
myTable.querySelectorAll('tr').forEach(tr => {
if(rowIsEmpty(tr)) tr.remove();
});
}
<table border="1" cellspacing="1" cellpadding="1" id ="myTable">
<tbody>
<tr>
<td>John</td>
<td>Alfredo</td>
</tr>
<tr>
<td>Mark</td>
<td>Zuck</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td>Carl</td>
<td>Johnson</td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</tbody>
</table>
Was answered in another thread.
Jquery: hiding empty table rows
Loops through all table tr rows, and checks td lengths. If the td length is empty will hide.
$("table tr").each(function() {
let cell = $.trim($(this).find('td').text());
if (cell.length == 0){
console.log('Empty cell');
$(this).addClass('nodisplay');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>1</td>
</tr>
<tr>
<!-- Will hide --> <td></td>
</tr>
</table>
With native Javascript:
function removeRow(src) {
var tableRows = document.getElementById(src).querySelectorAll('tr');
tableRows.forEach(function(row){
if((/^\s*$/).test(row.innerText)){
row.parentNode.removeChild(row);
}
});
}
removeRow('myTable');
The only problem is when you have some other characters in the row, except the whitespaces. This regex checks for blank characters, but if u have a dot inside or any other non empty character, it will fail.

How to get all the elements of a column from html table and validate if a particular string exists in that list

I have a html table with multiple rows and columns. I want to pull all the values by column id and compare with some matching string. If matches i want to enable a button on the page.
Could you please let me know how to refer the column by id in $(document).ready function.
Here is the table
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th:block th:each="it : ${data}">
<tr>
<td th:text="${it.id}">id</td>
<td th:text="${it.name}">name</td>
<td th:text="${it.place}">place</td>
</tr>
</th:block>
</table>
Button:
style="visibility:hidden">Submit
$(document).ready(function(){
//here i want to pull the place column and verify if one of the
places matches my input string enable submit button
$("#submitbutton").css("visibility", "visible");
}
}
This function will take all information inside you td and search for the string you looking for :
But i cannot get the point that you search for a particular string instead of searching for an object.
const addresses = [...document.querySelectorAll(".address")];
const serchFromList = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).filter(el => el === str)
}
console.log(serchFromList(addresses, "NY"))
/* in case you want a boolean you can use some*/
const isAddressExist = (arr, str) => {
return arr.map(el =>
el = el.innerHTML
).some(el => el === str)
}
console.log(isAddressExist(addresses, "NY"))
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<th>
<tr>
<td>4545</td>
<td>5454</td>
<td>65687</td>
</tr>
<tr>
<td>aziz</td>
<td>david</td>
<td>paul</td>
</tr>
<tr>
<td class='address'>NY</td>
<td class='address'>MTL</td>
<td class='address'>BC</td>
</tr>
</th>
</table>
Should be pretty doable with XPath if you don't want to add extra attributes to Place cell. Just find out the position of Place column and get the text from the same position of <td>.
// Get the table node first
let node = document.getElementById('data')
// Find out position of `Place` column
let nth = document.evaluate('count(//th[text()="Place"]/preceding-sibling::*)+1', node).numberValue
// Get all the place cell by the position
let placeCells = document.evaluate(`//td[position()=${nth}]`, node)
// Get all the place names
let places = [],
placeNode = placeCells.iterateNext()
while (placeNode) {
places.push(placeNode.textContent)
placeNode = placeCells.iterateNext()
}
console.log(places)
// ['NYC', 'SF', 'LA']
<table id="data" class="table">
<thead>
<tr class="DataT1">
<th>Id</th>
<th>Name</th>
<th>Place</th>
</tr>
</thead>
<tbody>
<tr>
<td>0001</td>
<td>Mary</td>
<td>NYC</td>
</tr>
<tr>
<td>0002</td>
<td>John</td>
<td>SF</td>
</tr>
<tr>
<td>0003</td>
<td>Bob</td>
<td>LA</td>
</tr>
</tbody>
</table>

Render JSON to table, if id matches

I've got a table with 5 rows and two columns. Each row, has an ID column, ranging from 1-5.
I want to add JSON data to that said table, IF, that data has a matching ID to that row. If NO data matches that rows ID, add "No Matching Record" to that rows second column.
HTML Table
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
Json Data
{"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]}
Expected Result
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Doe</td>
</tr>
<tr>
<td>2</td>
<td>No Matching Record</td>
</tr>
<tr>
<td>3</td>
<td>Jones</td>
</tr>
<tr>
<td>4</td>
<td>No Matching Record</td>
</tr>
<tr>
<td>5</td>
<td>No Matching Record</td>
</tr>
</tbody>
</table>
You can do this with .each() to loop each tr and then use find() to get object from data that has same id as text in td.
//Loop each row or tr
$('tbody tr').each(function() {
//Get text or number from each first td in every row
var i = $(this).find('td:first').text();
//Find object from data with this id or current id of td
var r = data.data.find((e) => e.id == i);
//Select second td from current row
var t = $(this).find('td:eq(1)');
//If Object is found with current id add lastName as text else add dummy text or No Matching Record
(r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
});
var data = {"data":[{"id":"1", "lastName":"Doe"},{"id":"3", "lastName":"Jones"}]}
$('tbody tr').each(function() {
var i = $(this).find('td:first').text();
var r = data.data.find((e) => e.id == i);
var t = $(this).find('td:eq(1)');
(r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
If you want to filter by index of rows instead of text from td you can just use $(this).index() + 1; and the rest is same
var data = {
"data": [{
"id": "1",
"lastName": "Doe"
}, {
"id": "3",
"lastName": "Jones"
}, ]
}
//Loop each row or tr
$('tbody tr').each(function() {
//Get index of row
var i = $(this).index() + 1;
//Find object from data with this id or current id of td
var r = data.data.find((e) => e.id == i);
//Select second td from current row
var t = $(this).find('td:eq(1)');
//If Object is found with current id add lastName as text else add dummy text or No Matching Record
(r != undefined) ? t.text(r.lastName): t.text('No Matching Record');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
First, add classes to the two types of td's for convenience. Then following code should work. Here I am iterating through all rows in tbody and then searching through the json if any matching value is found. If no matching value is found, default value ("No data found") is put in the lastName column.
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td class="id">1</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">2</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">3</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">4</td>
<td class="name"></td>
</tr>
<tr>
<td class="id">5</td>
<td class="name"></td>
</tr>
</tbody>
</table>
var json = {"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]};
$(".table tbody tr").each(function(index){
var curId = $(this).find(".id").text();
var nameField = "No data found";
for( var i = 0; i < json.data.length; i++ )
{
var row = json.data[i];
if( row.id == curId )
{
nameField = row.lastName;
return false;
}
}
$(this).find(".name").text( nameField );
});//each
The following code would do the trick:
var response = {"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]};
var myData = response.data;
var rows = $('#myDataTable tbody tr');
var cells, index, itemFound = false;
rows.each(function (index) {
cells = $(this).find('td');
itemFound = false
for (index=myData.length-1 ; index>= 0 && !itemFound; index--) {
if (cells.eq(0).text() == myData[index].id) {
itemFound = true;
cells.eq(1).text(myData[index].lastName);
myData.splice(index, 1);
}
}
if (!itemFound) {
cells.eq(1).text('No matching record');
}
});
See my working js fiddle:
https://jsfiddle.net/gkptnnxe/
If you don't want to add class or id's to your td's then you can use this.
var obj = {"data":[
{"id":"1", "lastName":"Doe"},
{"id":"3", "lastName":"Jones"}
]};
var trs = document.getElementsByTagName("tr");
// don't need for i==0
for(var i=1; i<trs.length; i++){
var tds = trs[i].children;
var id = tds[0].innerHTML;
var nameFound = false;
//search this id in json.
var len = obj.data.length;
for(var j=0; j<obj.data.length; j++){
if(obj.data[j].id == id){
// If found then change the value of this lastName cell.
tds[1].innerHTML = obj.data[j].lastName;
nameFound = true;
}
}
// If id is not found is json then set the default message.
if(nameFound == false){
tds[1].innerHTML = "No mathcing records";
}
}
<table class="table table-striped">
<thead>
<tr>
<th>ID</th>
<th>Lastname</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td></td>
</tr>
<tr>
<td>2</td>
<td></td>
</tr>
<tr>
<td>3</td>
<td></td>
</tr>
<tr>
<td>4</td>
<td></td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</tbody>
</table>
You can get td by index and check the text of td if it matches add name to next td
var data = {
"data": [
{ "id": "1", "lastName": "Doe" },
{ "id": "3", "lastName": "Jones" }
]
};
$(".table-striped tbody tr").each(function(){
var index = data.data.map(function (e) { return e.id }).indexOf($(this).first().text().trim());
if(index > -1)
$(this).children('td:eq(1)').text(data.data[index].lastName);
else
$(this).children('td:eq(1)').text('No matching record');
});

How to extract text inside nested HTML using JQuery?

I have here HTML Code:
<div class="actResult" style="border: solid">
<table>
<tbody>
<tr>
<td>Order Number</td>
<td>1</td>
</tr>
<tr>
<td>Customer Number</td>
<td>3</td>
</tr>
<tr>
<td>Complaint Code</td>
<td>b</td>
</tr>
<tr>
<td>Receivable Receipt Number</td>
<td>5</td>
</tr>
<tr>
<td>Date Called</td>
<td>2014-03-19</td>
</tr>
<tr>
<td>Scheduled Day Of Checkup</td>
<td>2014-03-19</td>
</tr>
<tr>
<td>Scheduled Day Of Service</td>
<td>2014-03-21</td>
</tr>
<tr>
<td>Checkup Status</td>
<td>Y</td>
</tr>
<tr>
<td>Service Status</td>
<td>N</td>
</tr>
<tr>
<td>Technician Number Checkup</td>
<td>3</td>
</tr>
<tr>
<td>Technician Number Service</td>
<td>1</td>
</tr>
</tbody>
</table>
</div>
I want to get the values of the tags and put them into an array with the a structure like array("first td" => "second td"), so for this case the array would be array("Order Number" => "1", "Customer Number" => "3", "Complaint Code" => "b", ...) and so on.
After that, the final array would be sent into a PHP code.
I've been trying to extract some of the values from the HTML using var html = $(this).filter(function( index ){ return $("td", this) }).filter(":odd").text(); and various other combinations of filter(), but it doesn't seem to work for me.
How do I go about doing what I want to do?
jsFiddle Demo
You are going to want to use .each for that and iterate through the rows in the table. For each row, take the first cell (.eq(0)) as the key, and the second cell (.eq(1)) as the value. Place these in a result object.
//object to hold resulting data
var result = {};
//iterate through rows
$('.actResult tr').each(function(){
//get collection of cells
var $tds = $(this).find('td');
//set the key in result to the first cell, and the value to the second cell
result[$tds.eq(0).html()] = $tds.eq(1).text();
});
You can get the rows property of the table element and create an object based on the cells' value:
var rows = document.querySelector('.actResult table').rows,
data = {}, c, l = rows.length, i = 0;
for (; i < l; i++) {
c = rows[i].cells;
data[c[0].innerHTML] = c[1].innerHTML;
}
http://jsfiddle.net/tG8F6/

Categories