How to send selected table rows value to another page in javascript - javascript

I have 2 pages and 2 tables, in page 1(table 1) I want to send selected rows to page 2(table 2) where in table 2 I show the selected rows
This is the first table in page 1:
<table class="src-table">
<tr>
<th>Select</th>
<th>Firstname</th>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>Jill</td>
</tr>
<tr>
<td>
<input type="checkbox">
</td>
<td>Eve</td>
</tr>
</table>
<br>
<input type="button" value="Submit" id="submit">
Like image below
This is the second table in page 2:
<table class="target-table">
<tr>
<th>Select</th>
<th>Firstname</th>
</tr>
</table>
Like image below

If you really need this. You can use localStorage.
localStorage not working in the sandbox. But you can use it your application as well.
run storeItems when you need to save selected to store (for example on element select)
run appendStoredToAnouther on window event window.onload on page with the target table
function storeItems() {
const selectedItems = document.querySelectorAll("#first-table .selected");
const selectedHtml = nodeListToString(selectedItems);
localStorage.add('selectedTableItems', selectedHtml);
}
function nodeListToString(nodeList) {
let string = '';
nodeList.forEach(function(node) {
string += node.outerHTML;
});
return string;
}
function appendStoredToAnouther() {
const itemsHtml = window.localStorage.get('selectedTableItems');
const targetTable = document.getElementById('target-table');
targetTable.innerHTML = itemsHtml + targetTable.innerHTML;
}
<table id="first-table">
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr>
<td>2</td>
<td>Not Selected</td>
<td>Item</td>
</tr>
</table>
<button type="button" onclick="storeItems()">Send to anouther</button>
<button type="button" onclick="appendStoredToAnouther()">Append stored to anouther</button>
<table id="target-table">
<tr class="selected">
<td>1</td>
<td>Selected</td>
<td>Item</td>
</tr>
<tr>
<td>2</td>
<td>Not Selected</td>
<td>Item</td>
</tr>
</table>

Below I demonstrated how some lines could be carried over from one table to another one on a following page. However, since both pages are probably hosted on the same server it is in most cases more practical to first collect some unique identifiers for the selected table records, transmit them to the next page and then get the actual table contents from the original data source again (in many cases a database table or view). This approach will also make your page safer against unauthorised injections.
In case that the tables are to be shown in two consecutive pages you can do the following:
// shortcut for utility function querySelectorAll():
const qsa=(s,o)=>[...(o||document)['querySelectorAll'](s)];
const log=qsa('#log')[0];
qsa('#submit')[0].addEventListener('click',function(){
var dat="tbl="+JSON.stringify(
qsa('tr',qsa('.src-table')[0]).filter(tr=>qsa('input:checked',tr).length)
.map(tr=>qsa('td',tr).slice(1)
.map(td=>td.innerHTML))
);
log.innerHTML+="<hr>dat:"+dat;
log.innerHTML+="\nwindow.location=\"page2.html?\"+encodeURIComponent(dat)";
// this second part would be placed in the onload section if the next page:
log.innerHTML+='var dat=window.location.search.substr(1)'
var args=dat.split("&").reduce((a,v)=>{
var t=v.split('=');
a[t[0]]=JSON.parse(decodeURIComponent(t[1]));
return a;},
{}
);
qsa('.trg-table')[0].innerHTML+=
args.tbl.map((r,i)=>'<tr><td>'+(i+1)+'</td><td>'+r.join('</td><td>')+'</td></tr>').join('');
})
<h2>page one</h2>
<table class="src-table">
<tr><th>Select</th><th>Firstname</th><th>Familyname</th></tr>
<tr><td><input type="checkbox"></td><td>Jill</td><td>Jones</td></tr>
<tr><td><input type="checkbox"></td><td>Eve</td><td>Adams</td></tr>
</table>
<br>
<input type="button" value="Submit" id="submit">
<h2>this would be the second page</h2>
<table class="trg-table">
<tr><th>no</th><th>Firstname</th><th>Familyname</th></tr>
</table>
<pre id="log"></pre>
As this is a sandbox the last lines had to modified a bit. In your page you should actually redirect your page with the window.location assignment.
On the second page you then need to read the passed information from window.location.search and use that information to append it to your table there.

Related

How to get checkbox value from inside an HTML table using JS

I'm currently working on a simple website where I have a list of PC parts in a table. In this table I also have checkboxes which are meant to be checked if the parts are owned. At the bottom of a table is a button which will be pressed that is meant to check the status of the checkboxes and output the list of parts still needed and the approximate cost.
I'm having issues with accessing the checked state of the checkboxes through Javascript and keep getting undefined when I try to output the value in the console.
Site Table Image:
HTML Code:
<div class="beginnersguide">
<h1>What parts go into a gaming PC?</h1>
<table id="partsTable">
<tr>
<th onclick="sortTable(0)" id="partName">Part Name</th>
<th>Image</th>
<th>Description</th>
<th onclick="sortTable(3, 1)" id="averagePrice">Average Price ($CAD)</th>
<th>Already Owned?</th>
</tr>
<tr>
<td>Case</td>
<td><img src="../img/case.jpg"></td>
<td>The nicely designed box/container for all your PC parts. This is what you will first see when looking at your PC!</td>
<td>150</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Motherboard</td>
<td><img src="../img/motherboard.jpg"></td>
<td>The Motherboard is a large circuit board which acts as the central hub for all your internal PC components. It will connect all the parts inside together to run!</td>
<td>210</td>
<td><input type="checkbox"></td>
</tr>
<tr>
// Code continues on like this for the rest of the table and ends like this:
<tr>
<td>Input and Output Devices</td>
<td><img src="../img/iodevice.jpg"></td>
<td>This would cover items such as a mouse, keyboard and monitors. These are needed to interact with your PC.</td>
<td>250</td>
<td><input type="checkbox"></td>
</tr>
</table>
<input type="submit" name="check" value="Check List" onclick="checkList()">
JavaScript Code:
/* Function for Parts checklist */
function checkList(){
var table, rows = 0;
table = document.getElementById("partsTable");
rows = table.rows;
for (i = 1; i < (rows.length - 1); i++) {
x = rows[i].getElementsByTagName("TD")[4];
//console.log(x);
if (x.checked == true){
/* code to output what parts are necessary */
}
}
}

Click event does not return $event on click

I have the following structure in my HTML in an angular 7 application:
What I am trying to do is to call the GetContent() function on click of any of the text inside the div. I am able to get the $event as "Liquidity" when I click on the text but if I click on any empty space between the text, the $event is empty. I tried every possible permutation of changing the location of the function call and id but same issue. Can anyone let me know what is wrong.
<tr (click)="GetContent($event)">
<td>
<table>
<tbody>
<tr>
<td>
<div id="Liquidity"> lot of text....................... </div>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
Because there is no content in your TR's and TD's, its not creating a space at all. Look at my code, I have added padding for table row's ,table and table data tags
<table>
<tbody>
<tr (click)="GetContent($event)" >
<td style="padding:20px;background:red">TD
<table style="padding:20px;background:green">Table
<tbody>
<tr>
<td style="padding:20px;background:blue">TD
<div id="Liquidity" style="padding:10px;background:green"> lot of text....................... </div>
</td>
</tr>
</tbody>
</table>
</td>
<tr>
</tbody>
</table>
example stackblitz
Do it this way ,
UPDATED
<table>
<tbody>
<tr>
<td>
<div id="Liquidity" (click)="GetContent($event)"> lot of text....................... </div>
</td>
</tr>
</tbody>
</table>
ts file
GetContent(event) {
var target = event.target || event.srcElement || event.currentTarget;
var idAttr = target.attributes.id;
var value = idAttr.nodeValue;
console.log(value) //you will get liquid here.
}

How to get cell value by clicking on a button

I have a problem that I can't solve how much I try. By clicking on the Edit Customer button I wan't to get the value from the CustomerNr cell. My problem is that I don't know how to get the row index by clicking on a button and then pass it to my function so I can specifically get the CustomerNr on that row I pressed the button on. You can take a look at my jsfiddle link and note, this is the first time I code in Javascript/Jquery. I'm open for smart solutions.
Here you can see how far I came. I managed to select value from a specific cell.
function GetCellValues() {
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
}
I have managed to get the row index by clicking on on a td but I want to get it by pressing a button.
function myMethod(obj) {
alert(obj.parentNode.rowIndex); // parentNode is also used
}
I wan't to somehow combine this two functions, like in C#. (I'm a C# programmer)
function GetCellValues(e) {
//Something here
alert(Cells[0].Rows[e] innerText);
}
http://jsfiddle.net/6srjc7qL/
I've changed the id's of your buttons to classes, as you can't name two elements with the same id, then I looped through the elements... Working fiddle
You should avoid to use inline functions and pereferably do it like this, this might safe you a lot of time and keeps it better maintainability:
Javascript:
var a = document.getElementsByClassName('otherButton');
for (var i = 0; i<a.length;i++) {
a[i].addEventListener('click',function(){
var b = this.parentNode.parentNode.cells[0].textContent;
alert(b);
});
}
HTML:
<table id="somerow">
<tr>
<th>CustomerNr</th>
<th>Name</th>
<th>Contact</th>
</tr>
<tr >
<td>1</td>
<td>Cigarettes Inc</td>
<td>Rambo</td>
<td>
<button class="otherButton" >Edit Customer</button>
</td>
</tr>
<tr >
<td >22</td>
<td>Razor</td>
<td>David</td>
<td>
<button class="otherButton">Edit Customer</button>
</td>
</tr>
<tr>
<td>3</td>
<td>H&M</td>
<td>Samuel Adams</td>
<td>
<button class="otherButton" >Edit Customer</button>
</td>
</tr>
}
the button is inside the td which is inside the tr, so you need to go 2 nodes up. Try this:
function GetCellValues(obj) {
alert(obj.parentNode.parentNode.rowIndex);
}
HTML
<html>
<head>
<style>
table, td {
border: 1px solid black;
}
.selected {
background-color: yellow;
}
</style>
</head>
<body>
<center>
<table id="somerow">
<tr>
<th>CustomerNr</th>
<th>Name</th>
<th>Contact</th>
</tr>
<tr>
<td>1</td>
<td>Cigarettes Inc</td>
<td>Rambo</td>
<td>
<button id="otherButton" onclick="GetCellValues()">Edit Customer</button>
</td>
</tr>
<tr>
<td onclick="myMethod(this);">22</td>
<td>Razor</td>
<td>David</td>
<td>
<button id="otherButton" onclick="GetCellValues()">Edit Customer</button>
</td>
</tr>
<tr>
<td>3</td>
<td>H&M</td>
<td>Samuel Adams</td>
<td>
<button id="otherButton" onclick="GetCellValues()">Edit Customer</button>
</td>
</tr>
</center>
</body>
</html>
JS
function GetCellValues(elm) {
alert(elm.parentNode.parentNode.cells[0].textContent);
}
function myMethod(obj) {
alert(obj.parentNode.rowIndex);
}

checking number of td tags in a dynamic table and divide them into two equal tr tags

The question title might seems ambiguous but I will try to explain in detail over here.
So I am generating a dynamic table based on the JSON data. Inside the table I have few tags and in one of the tag I am further populating table data enclosed in tags. Number of tables inside the td tag might varies but the maximum number of tables are 4. Here is the rough HTML markup which is generated after the table is populated.
Current mark up
<table>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
Expected mark up
<table>
<tbody>
<tr>
<td></td>
</tr>
<tr>
<td></td>
</tr>
<tr>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
</tr>
<tr>
<td>
<table>
</table>
</td>
<td>
<table>
</table>
</td>
</tr>
<tr>
<td></td>
</tr>
</tbody>
</table>
As you can see in the third tag I have 4 tag which contains individual tables. What I am trying to achieve if the number of tags in the third row is greater than 2 then I should create another tag below that and divide the 4 tags (which contains tables) into 2 tags (with 2 tags each).
Since the tables are generated dynamically I don't have a predefined HTML mark up.
This is my relevant JS function
drawRunningDailyDoublesTables: function (events, table) {
var indexes = $(table).data('BetTableData').eventIndexes;
table.innerHTML = '';
// Drawing STAB / NSW product selection
betTable.drawBetTypeProductSelection(table);
// Error space
betTable.drawErrorSpace(table);
var trForTables = $('<tr/>')
.appendTo(table);
// Drawing tables for doubles
$.each(indexes, function(j, index) {
var betTableData = new BetTableData();
betTableData.setMarketId(events[index].markets[0].id);
var doubleTable = $('<table/>')
.data('BetTableData', betTableData);
// Names and info of races
betTable.drawHeaderForDoubles(doubleTable, events[index], 3);
// Horse selections
betTable.drawSelectionsForRunningDoubles(table, doubleTable, events[index], j+1);
// here I am generating the td tag with tables as mentioned in the question. It could be 2,3 or 4 depending on the different situation.
$('<td style="vertical-align: top;"/>')
.appendTo(trForTables)
.append(doubleTable)
// Footer
createFooterRowForRunningDoubles("white", 2, table, doubleTable, j+1);
});
// draw button for betting
betTable.drawExoticBetBtnForDoubles(table);
betTable.selectDefaultRadioProduct(table);
},
Please see this fiddle:
http://jsfiddle.net/MXGBu/2/
var thirdRow = $('table:first>tbody>tr:nth-child(3)');
var tablesInThird = thirdRow.find('table');
if(tablesInThird.length === 4)
{
thirdRow.after('<tr class="arse"></tr>');//creates a new tr after 3rd row
tablesInThird.eq(2).parent().appendTo($('tr.arse')); //adds 3rd table
tablesInThird = thirdRow.find('table');
tablesInThird.eq(2).parent().appendTo($('tr.arse')); //adds 4th table
}

how to get values of columns for a selected row through jQuery on click of element calling method to retrieve value

here i am trying to fetch values of a particular column for a selected row via jquery.In Following code i have two rows which do not have any id.I tried following way and getting both rows value for that column appending each other.how to get value for that row only using jquery only.I want to call test function on click of that element, dont want to use http://jsfiddle.net/SSS83/
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript">
function test(){
var id = $(".use-address").closest("tr").find('td:eq(2)').text();
alert(id);
}
</script>
</head>
<body>
<table id="choose-address-table" class="ui-widget ui-widget-content">
<thead>
<tr class="ui-widget-header ">
<th>Name/Nr.</th>
<th>Street</th>
<th>Town</th>
<th>Postcode</th>
<th>Country</th>
<th>Options</th>
</tr>
</thead>
<tbody>
<tr>
<td class="nr"><span>50</span>
</td>
<td>Some Street 1</td>
<td>Glas</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" onclick="test();">Use</button>
</td>
</tr>
<tr>
<td class="nr"><span>30</span>
</td>
<td>Some Street 2</td>
<td>Glasgow</td>
<td>G0 0XX</td>
<td>United Kingdom</td>
<td>
<button type="button" class="use-address" onclick="test();">Use</button>
</td>
</tr>
</tbody>
</table>
</body>
</html>
Not sure why you don't want to use jQuery Click event!!
Any way, if you want to stick with your test function, you need to tell the function from where it got called.
so change the
<button type="button" class="use-address" onclick="test();">Use</button>
to
<button type="button" class="use-address" onclick="test(this);">Use</button>
And update your test function as
function test(el) {
var id = $(el).closest("tr").find('td:eq(2)').text();
alert(id);
}
Enjoy!!
If you change your mind you can use the following code
jQuery('document').ready(function() {
jQuery('.use-address').on('click',function() {
var id = $(this).closest("tr").find('td:eq(2)').text();
alert(id);
})
});
Based on a click of a TD:
$('td').on('click',function() {
//get the column of the TD
var myCol = $(this).index();
//loop through the rows of this table, get the TD in the same column
$(this).parent('table').find('tr').each(function() {
var colValue = $(this).find('td').eq(myIndex).html()
}
})
"colValue" in the loop will grab the contents of the TD at that position.

Categories

Resources