Unable to remove rows from table - javascript

I am having the table with following data in it
<table>
<tr>
<td> cat </td>
<td> dog </td>
</tr>
<tr>
<td> hen </td>
<td> cock </td>
</tr>
</table>
I would like to delete the row based on the particular data given in table.
But I don't have any idea on how to delete the rows based on the particular data

Try this:
var table = document.querySelector('table');
var filterInput = document.querySelector('#filter');
filterInput.onkeyup = function () {
var val = this.value;
var td = table.getElementsByTagName('td');
var rows = [];
[].slice.call(td).forEach(function (el, i) {
if (el.textContent === val) {
rows.push(el);
}
});
rows.forEach(function(el) {
el.parentNode.style.display = 'none';
});
};
<input type="text" id="filter" placeholder="Hide row containing...">
<table>
<tr>
<td>cat</td>
<td>dog</td>
</tr>
<tr>
<td>hen</td>
<td>cock</td>
</tr>
</table>

Find the required element and then use style property to hide it. In the example, I went onto hide the table data element corresponding to the data dog.
var tds = $("td");
for(var i =0 ; i< tds.length ; i++)
{
var tdval = tds[i].innerHTML;
if(tdval.trim()=="dog")
{
document.getElementsByTagName("td")[i].style.display = "none";
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td> cat </td>
<td> dog </td>
</tr>
<tr>
<td> hen </td>
<td> cock </td>
</tr>
</table>

Related

How to do calculation where a value has to be entered in a row for each row of table using Razor Pages and JavaScript?

I have a table for product data and the user can enter the amount of a product to buy in each row.
I would like to compute the total price per product in each row and then the total price of the whole purchase below the table.
This is my table:
<table id="productTable">
<thead>
<tr>
<th>Amount</th>
<th>
#Html.DisplayNameFor(model => model.Products[0].Name)
</th>
<th>
#Html.DisplayNameFor(model => model.Products[0].Price)
</th>
<th>Total</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model.Products)
{
<tr>
<td>
<input type="number" id="quantityInput" onchange="calcSubTotal()" min="0" value="0" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td id="priceLabel">
#Html.DisplayFor(modelItem => item.Price)
</td>
<td id="labelSubTotal"></td>
</tr>
}
</tbody>
The items are coming from the model (IList). I want to multiply the entered value of the input (type number) and the price of the corressponding row using JavaScript.
In JavaScript I am using getElementById to access the UI-Elements. How I can access the row of the table where the focus of the HTML-Input is?
My JavaScript:
<script type="text/javascript">
function calcSubTotal() {
var numberInput = document.getElementById('quantityInput');
var val = numberInput.value;
var amount = parseFloat(val);
var priceLabel = document.getElementById('priceLabel');
var priceValue = priceLabel.innerText;
var price = parseFloat(priceValue);
var totalPrice = amount * price;
var subTotalLabel = document.getElementById('labelSubTotal');
subTotalLabel.innerText = totalPrice.toString();
}
</script>
It may work if only have one record.But you have several raws of record.Each id of Price and Total are the same.You need to distinguish the id like below:
<table id="productTable">
//..
<tbody>
#{
int i = 0; //add this..
}
#foreach (var item in Model.Products)
{
<tr>
<td>
//change the onchange function...
<input type="number" id="quantityInput" onchange="calcSubTotal(this,#i)" min="0" value="0" />
</td>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td id="priceLabel_#i"> //change here...
#Html.DisplayFor(modelItem => item.Price)
</td>
<td id="labelSubTotal_#i"></td> //change here...
</tr>
i++; //add this....
}
</tbody>
</table>
#section Scripts
{
<script type="text/javascript">
function calcSubTotal(element,index) {
var numberInput = $(element).val();
var amount = parseFloat(numberInput);
var priceLabel = document.getElementById('priceLabel_'+index);
var priceValue = priceLabel.innerText;
var price = parseFloat(priceValue);
var totalPrice = amount * price;
var subTotalLabel = document.getElementById('labelSubTotal_'+index);
subTotalLabel.innerText = totalPrice.toString();
}
</script>
}
Result:

How do I get and pass the field of the row having class="name" in the following html?

<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata(parameter)">Fetch Details</button>
</td>
</tr>
</tbody>
In the above html, I want that the function fetchdata('parameter') to contain the text content of the td which has a class of name and is hidden, as the parameter.
OR
I need a way in which I can get the text content of the td having class of name in my javascript function.
i.e.
function fetchdata() {
const name = document.somethingThatGivesMeName()
}
NOTE: There are going to be multiple rows that I may require to get the name of so I can't directly do document.queryselector('.name')
Sorry, This might be pretty simple but I can't quite figure it out.
When clicking the button find the first row up in the tree relative to the button with the closest method. Then from the row select the element with the class name and read the textContent or innerText of that element.
const buttons = document.querySelectorAll('.js-fetch-details');
function fetchDetails(event) {
const row = event.target.closest('tr');
const name = row.querySelector('.name').textContent;
console.log(name);
}
buttons.forEach(button => button.addEventListener('click', fetchDetails));
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button class="js-fetch-details">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
You just need the quotes ':
function fetchdata(value){
console.log(value)
}
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata('parameter')">Fetch Details</button>
</td>
</tr>
</tbody>
or you can use event listener and data value:
document.querySelectorAll('button').forEach(el => {
el.addEventListener('click', e => {
e = e || window.event;
e = e.target || e.srcElement;
console.log(e.dataset.value)
})
})
<tbody>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button data-value="parameter">Fetch Details</button>
</td>
</tr>
</tbody>
You can use document.getElementsByClassName('name')
This will get all the elements that have class of name.
I would put the listener on the <tbody> instead.
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.parentNode.parentNode.querySelector('.name').textContent;
console.log(name);
}
});
UPDATE
closest would also work
document.querySelector('tbody').addEventListener('click', (e) => {
// Clicking on the whole row
if (e.target.nodeName === 'TR') {
const name = e.target.querySelector('.name').textContent;
console.log(name);
}
// Clicking on the button
// Give the button a class
if (e.target.classList.contains('.somebuttonclass')) {
const name = e.target.closest('tr').querySelector('.name').textContent;
console.log(name);
}
});
First you get all elements with class="name", then you pick just (the first) one with the attribute "hidden".
It's a way to do it anyway.
function fetchdata() {
const tds = document.getElementsByClassName("name")
for(let i = 0; i < tds.length; i++){
if(tds[i].getAttribute("hidden") != null) {
console.log(tds[i].innerHTML)
}
}
}
<table>
<tr>
<td class="name">gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td class="name">1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
With jQuery you can just do:
function fetchdata() {
console.log($('.name[hidden]').html());
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td>gibberish</td>
<td class="name" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</table>
Note that you need to have a table around your structure for any of this to work properly. You can't have tbody, tr and td outside a table.
If you use document.getElementsByClassName you will get what you want.
However, if there will be a case where more than one instance of that class name will occur, then you need to iterate through the classes and get their values.
The following should solve your problem
<html>
<head>
<script>
function fetchdata(){
var data = document.getElementsByClassName("data");
var t = data.length;
for(i = 0; i< t; i++){
var content = data[i].innerHTML;
alert (content);
}
}
</script>
<body>
<table>
<tbody>
<tr>
<td>gibberish</td>
<td class="data" hidden>200398</td>
<td>iPhone X 64Gb Grey</td>
<td>$999.00</td>
<td>1</td>
<td>
<button onclick="fetchdata()">Fetch Details</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Jquery parse HTML Table

I have the following table:
<table id="tableData" name="tableData">
<tr>
<td class="tdvalue"><a class="XXX">10</a></td>
<td class="tdvalue"><a class="YYY">4</a></td>
<td class="tdvalue"><a class="XXX">7</a></td>
</tr>
</table>
I need to get the td value which has hyperlink with class name in an array
The following code is not working
var rows = [];
$("#tableData tr").each(function() {
$tr = $(this);
var row = [];
$tr.find(".tdvalue").each(function(){
row.push($(this).text());
});
});
This gives the value of the text with in the td.
but I need to class name of XXX <a class="XXX">10</a>
result would be:
Array[3] 0:"XXX" 1:"YYY" 2:"XXX"
Please help anyone
target the a's directly:
var row = [];
$(".tdvalue a").each(function() {
row.push($(this).attr('class'));
});
//gives row= ["XXX","YYY","XXX"]
var row = [];
$(".tdvalue a").each(function() {
row.push($(this).attr('class'));
});
console.log(row)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tableData" name="tableData">
<tr>
<td class="tdvalue"><a class="XXX">10</a></td>
<td class="tdvalue"><a class="YYY">4</a></td>
<td class="tdvalue"><a class="XXX">7</a></td>
</tr>
</table>

merging <td> rows in one column of html table

I have a requirement, if i have same data in column1 of 's with same id then i need to merge those cells and show their respective values in column2.
i.e., in fiddle http://jsfiddle.net/7t9qkLc0/12/ the key column have 3rows with data 1 as row value with same id and has corresponding different values in Value column i.e., AA,BB,CC. I want to merge the 3 rows in key Column and display data 1 only once and show their corresponding values in separate rows in value column.
Similarly for data4 and data5 the values are same i.e.,FF and keys are different, i want to merge last 2 rows in Value column and dispaly FF only one time and show corresponding keys in key column. All data i'm getting would be the dynamic data. Please suggest.
Please find the fiddle http://jsfiddle.net/7t9qkLc0/12/
Sample html code:
<table width="300px" height="150px" border="1">
<tr><th>Key</th><th>Value</th></tr>
<tr>
<td id="1">data 1</td>
<td id="aa">AA</td>
</tr>
<tr>
<td id="1">data 1</td>
<td id="bb">BB</td>
</tr>
<tr>
<td id="1">data 1</td>
<td id="cc">CC</td>
</tr>
<tr>
<td id="2">data 2</td>
<td id="dd">DD</td>
</tr>
<tr>
<td id="2">data 2</td>
<td id="ee">EE</td>
</tr>
<tr>
<td id="3">data 3</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="4">data 4</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="5">data 5</td>
<td id="ff">FF</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3" style="padding-left: 0px; padding-right: 0px; padding-bottom: 0px">
</td>
</tr>
</table>
Building on tkounenis' answer using Rowspan:
One option to implement what you need would be to read all the values in your table after being populated, then use a JS object literal as a data structure to figure out what rows/columns are unique.
A JS object literal requires a unique key which you can map values to. After figuring out what rows/columns should be grouped, you can either edit the original table, or hide the original table and create a new table (I'm creating new tables in this example).
I've created an example for you to create a new table either grouped by key or grouped by value. Try to edit the examples provided to introduce both requirements.
Let me know if you need more help. Best of luck.
JSFiddle: http://jsfiddle.net/biz79/x417905v/
JS (uses jQuery):
sortByCol(0);
sortByCol(1);
function sortByCol(keyCol) {
// keyCol = 0 for first col, 1 for 2nd col
var valCol = (keyCol === 0) ? 1 : 0;
var $rows = $('#presort tr');
var dict = {};
var col1name = $('th').eq(keyCol).html();
var col2name = $('th').eq(valCol).html();
for (var i = 0; i < $rows.length; i++) {
if ($rows.eq(i).children('td').length > 0) {
var key = $rows.eq(i).children('td').eq(keyCol).html();
var val = $rows.eq(i).children('td').eq(valCol).html();
if (key in dict) {
dict[key].push(val);
} else {
dict[key] = [val];
}
}
}
redrawTable(dict,col1name,col2name);
}
function redrawTable(dict,col1name,col2name) {
var $table = $('<table>').attr("border",1);
$table.css( {"width":"300px" } );
$table.append($('<tr><th>' +col1name+ '</th><th>' +col2name+ '</th>'));
for (var prop in dict) {
for (var i = 0, len = dict[prop].length; i< len; i++) {
var $row = $('<tr>');
if ( i == 0) {
$row.append( $("<td>").attr('rowspan',len).html( prop ) );
$row.append( $("<td>").html( dict[prop][i] ) );
}
else {
$row.append( $("<td>").html( dict[prop][i] ) );
}
$table.append($row);
}
}
$('div').after($table);
}
Use the rowspan attribute like so:
<table width="300px" height="150px" border="1">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td id="1" rowspan="3">data 1</td>
<td id="aa">AA</td>
</tr>
<tr>
<td id="bb">BB</td>
</tr>
<tr>
<td id="cc">CC</td>
</tr>
<tr>
<td id="2" rowspan="2">data 2</td>
<td id="dd">DD</td>
</tr>
<tr>
<td id="ee">EE</td>
</tr>
<tr>
<td id="3">data 3</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="4">data 4</td>
<td id="ff">FF</td>
</tr>
<tr>
<td id="5">data 5</td>
<td id="ff">FF</td>
</tr>
</table>
http://jsfiddle.net/37b793pz/4/
Can not be used more than once the same id. For that use data-id attribute
HTML:
<table width="300px" height="150px" border="1">
<tr>
<th>Key</th>
<th>Value</th>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valaa">AA</td>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valbb">BB</td>
</tr>
<tr>
<td data-id="key1">data 1</td>
<td data-id="valcc">CC</td>
</tr>
<tr>
<td data-id="key2">data 2</td>
<td data-id="valdd">DD</td>
</tr>
<tr>
<td data-id="key2">data 2</td>
<td data-id="valee">EE</td>
</tr>
<tr>
<td data-id="key3">data 3</td>
<td data-id="valff">FF</td>
</tr>
<tr>
<td data-id="key4">data 4</td>
<td data-id="valff">FF</td>
</tr>
<tr>
<td data-id="key5">data 5</td>
<td data-id="valff">FF</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="3" style="padding-left: 0px; padding-right: 0px; padding-bottom: 0px"></td>
</tr>
</table>
JQ:
//merge cells in key column
function mergerKey() {
// prevents the same attribute is used more than once Ip
var idA = [];
// finds all cells id column Key
$('td[data-id^="key"]').each(function () {
var id = $(this).attr('data-id');
// prevents the same attribute is used more than once IIp
if ($.inArray(id, idA) == -1) {
idA.push(id);
// finds all cells that have the same data-id attribute
var $td = $('td[data-id="' + id + '"]');
//counts the number of cells with the same data-id
var count = $td.size();
if (count > 1) {
//If there is more than one
//then merging
$td.not(":eq(0)").remove();
$td.attr('rowspan', count);
}
}
})
}
//similar logic as for mergerKey()
function mergerVal() {
var idA = [];
$('td[data-id^="val"]').each(function () {
var id = $(this).attr('data-id');
if ($.inArray(id, idA) == -1) {
idA.push(id);
var $td = $('td[data-id="' + id + '"]');
var count = $td.size();
if (count > 1) {
$td.not(":eq(0)").remove();
$td.attr('rowspan', count);
}
}
})
}
mergerKey();
mergerVal();
Use below snippet of javascript. It should work fine for what you are looking.
<script type="text/javascript">
function mergeCommonCells(table, columnIndexToMerge){
previous = null;
cellToExtend = null;
table.find("td:nth-child("+columnIndexToMerge+")").each(function(){
jthis = $(this);
content = jthis.text();
if(previous == content){
jthis.remove();
if(cellToExtend.attr("rowspan") == undefined){
cellToExtend.attr("rowspan", 2);
}
else{
currentrowspan = parseInt(cellToExtend.attr("rowspan"));
cellToExtend.attr("rowspan", currentrowspan+1);
}
}
else{
previous = content;
cellToExtend = jthis;
}
});
};
mergeCommonCells($("#tableId"), 1);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

creating table within table by pressing button

I currently have a table and in one of the <td>, I have input type of checkbox. where if user clicks on it, it will create different table.
<div style="padding-left:170px;">
<table width="80%" border="1" padding-left:50px>
<tr>
<td>
<table border="1" style="float:left">
<th>Portal01</th>
<tr>
<td style= "padding:12px;" align="left" >
<input type="test0" id = "test0" name="liveDiff" onchange = "expandService()"> blah_0
</td>
<td>
blah_1
</td>
<td>
blah_2
</td>
</tr>
</table>
</td>
</tr>
</table>
I have it set up where if user clicks on checkbox next to blah_0, it should create different table within this table. I am not sure if this is possible with JavaScript and if not, what would be alternate way to approach this situation.
it is possible.
function expandService(){
document.getElementById('the_id_of_the_td_that_will_contain_the_new_table').innerHTML =
'<table><tr>...</tr></table>';
}
Another way is to use appendChild(), here is an example:
function expandService(chkId, tblId, totalRows, totalCols){
var tbl = document.createElement('table');
tbl.id = tblId;
var row, col, spn;
for(var i=0; i<totalRows; i++){
row = document.createElement('tr');
for(var j=0; j<totalCols; j++){
col = document.createElement('td');
spn = document.createElement('span');
spn.innerHTML = 'your-text';
col.appendChild(spn);
row.appendChild(col);
}
tbl.appendChild(row);
}
var chk = document.getElementById(chkId);
// td is the parent of checkbox
chk.parentNode.appendChild(tbl);
}
Sample usage:
<input type="checkbox" id="test0" name="liveDiff" onchange="expandService(this.id, 'your-table-id', 5, 4)">
It creates a table with 5 rows and 4 columns.
This is possible with javascript. One potential way to go is to use innerHTML. Use jQuery or just document.getElementByID to select the element that corresponds to your cell and insert a table inside of it. Here is an example fiddle using your code as a base.
<div style="padding-left:170px;">
<table width="80%" border="1" padding-left:50px>
<tr>
<td>
<table border="1" style="float:left">
<th>Portal01</th>
<tr>
<td id="foo" style= "padding:12px;" align="left" >
<input type="test0" id = "test0" name="liveDiff"> blah_0
</td>
<td>
blah_1
</td>
<td>
blah_2
</td>
</tr>
</table>
</td>
</tr>
</table> ​
js:
var makeTable = function(contents){
return '<table><td>' + contents + '</td></table>'
}
document.getElementById("test0").onchange = function(){
document.getElementById("foo").innerHTML = makeTable("foo")
}
​

Categories

Resources