.each() function on affect current object - javascript

having some issues with my code below, first here is the HTML:
<table class="finance-table">
<tbody><tr>
<th></th>
<th>Deposit</th>
<th>Balance</th>
<th>Fees</th>
<th>Total Payable</th>
<th>Term</th>
<th>Fixed Rate</th>
<th>Representative APR</th>
<th>Monthly Pmt</th>
</tr>
<tr class="hp">
<td><strong>HP</strong></td>
<td id="td_finance_deposit">£11700.00</td>
<td id="td_finance_balance">£105300.00</td>
<td id="td_finance_fees">£298.00</td>
<td id="td_finance_total_inc_deposit">£146255.50</td>
<td id="td_finance_term">60 mths</td>
<td id="td_finance_rate">5.50%</td>
<td id="td_finance_apr">10.1%</td>
<td id="td_finance_monthly_payments">£2242.59 p/m* x 60 mths</td>
</tr>
</tbody></table>
There is about 10 of these tables [within the same document], all with the same id's and class's. I'm using an each loop to execute some code against each table found, however it only seems to be working on the first table and disregards the others.
Below is the jQuery, like I said works find on the first table, but ignores the rest!
<!-- Remove First and Final Payment from Showroom Finance Examples -->
<script>
$(".finance-table").each(function(key, value) {
// Display loading
var html = $(this);
// Remove the First Payment and Final Payment Column
$(this).find("#td_finance_first_payment, #td_finance_final_payment").remove();
$(this).find("th:contains('1st Pmt')").remove(); $(this).find("th:contains('Final Pmt')").remove();
// Get the Term and update the monthly payment
var term = $(this).find("#td_finance_term").html(); // .replace(/\D/g,'')
var payments = ($(this).find("#td_finance_monthly_payments").html()).split('x')[0];
($(this).find("#td_finance_monthly_payments")).html(payments + " x " + term);
})
</script>
Edit:
Please note, I can't change the HTML at all

You should first give a unique ID to each <td>, perhaps with your DB identifier for that record. You don't need it now but this will allow you to do other thing later if you need it.
Then change all the <td> ids to classes:
<td class="td_finance_fees">£298.00</td>
Finally change all your javascript accordingly to use class instead of IDs:
$(this).find(".td_finance_first_payment, .td_finance_final_payment").remove();

Using Attribute Equals Selector
Change your code from:
$(this).find("#td_finance_first_payment, #td_finance_final_payment").remove();
to:
$(this).find('td[id="td_finance_first_payment"], td[id="td_finance_final_payment"]').remove();
Do this type of change for all areas of #xxx to id="xxx"
What this does is find all tds with attribute id="xxx", rather than using #id identifier, this is forces jQuery to do a tree search.
Also your HTML does not match your code, (theres no td_finance_first_payment in your html, I assume you removed it?)
Edit: This solution is useful if you 100% cannot edit the html (comes from a source you have no control over, such as an API or internal software). Best solution would be to fix the ids!

Related

Select and sort a column in a table using Javascript

I want to select a particular column of a table and sort it accordingly using Javascript (No frameworks or plugins). Could anyone help me regarding this?
<table>
<thead>
<tr>
<td>Col1</td>
<td>Col2</td>
<td>Col3</td>
<td>Col4</td>
</tr>
</thead>
<tbody>
<tr>
<td>Data11</td>
<td>Data23</td>
<td>Data53</td>
<td>Data45</td>
</tr>
<tr>
<td>Data81</td>
<td>Data42</td>
<td>Data33</td>
<td>Data4854</td>
</tr>
<tr>
<td>Data84681</td>
<td>Data452</td>
<td>Data354</td>
<td>Data448</td>
</tr>
<tr>
<td>Data1846</td>
<td>Data25635</td>
<td>Data3232</td>
<td>Data44378</td>
</tr>
</tbody>
</table>
function sortTableByColumn(tableId,columnNumber) { // (string,integer)
var tableElement=document.getElementById(tableId);
[].slice.call(tableElement.tBodies[0].rows).sort(function(a, b) {
return (
a.cells[columnNumber-1].textContent<b.cells[columnNumber-1].textContent?-1:
a.cells[columnNumber-1].textContent>b.cells[columnNumber-1].textContent?1:
0);
}).forEach(function(val, index) {
tableElement.tBodies[0].appendChild(val);
});
}
In your page, add id to the table tag:
<table id="myTable">
From javascript, use:
sortTableByColumn("myTable",3);
tBodies[0] is used because there can be many. In your example there is only one.
If we have var arr=[123,456,789], [].slice.call(arr) returns a copy of arr.
We're feeding it the html-rows-collection, found in tBodies[0] of tableElement.
Then, we sort that array with an inline function that compares two array elements, here: rows (<tr>).
Using cells[columnNumber] we access the <td>s, and textContent to access the text content. I've used columnNumber-1 so you can enter 3 for third column instead of 2, because the index of first element of an array (column 1) is 0...
The forEach goes through the elements of the array, which is by now in order, and appendChild row to the tBody. Because it already exist, it just moves it to the end: moving the lowest value to the end, then moving the second lowest to the (new) end, until it ends with the highest value, at the end.
I hope this is what you want. If so, enjoy!
Try using datatables you can get it from http://datatables.net its reallt easy to use. depends on jQuery
$("table").dataTable();
boom! and its done.

Reading HTML Table Head value in Adobe DTM

I'm using Adobe DTM and I'm trying to get the value from a table (I have no control over this format or naming) and I'd like to grab the value of "Opened Account" in the example below but not sure how to go about it in DTM? I'm trying to target "th.rich-table-headercell" but not sure how to grab value?
<table class="rich-table home table" id="startForm:OpenedReviewApps" border="1" cellpadding="0" cellspacing="0">
<colgroup span="0"></colgroup>
<thead class="rich-table-thead">
<tr class="rich-table-header">
<th class="rich-table-headercell" scope="colgroup">Opened Accounts</th>
</tr>
</thead>
<tbody id="startForm:OpenedReviewApps:tb">
<tr class="rich-table-row rich-table-firstrow">
<td class="rich-table-cell" id="startForm:Open" style="width:80%">
some data here
</td>
</tr>
</tbody>
</table>
There may be a better way to do this, depending on what/when/where you are trying to get the value (e.g. page load rule vs. event based rule), but in general, based on your html, here is one way to do it.
Go to Rules > Data Elements, and click on Create New Data Element.
Name the Data Element something like "table_header" or whatever convention you currently use.
For Type, choose "CSS Selector".
For CSS Selector Chain, use "th.rich-table-headercell" (no quotes).
For get the value of, select "text".
(Optional, but recommended) Check the Scrub whitespace and linebreaks using cleanText option.
Now, for example, you can create a page load rule, and use %table_header% in your condition(s) or variable field(s). Or, if you need to reference it in javascript in a custom code box, use _satellite.getVar('table_header')

contenteditable - JQuery save content just to webpage (as well as adding and removing)

Upon thorough research I was able to allow one data value to be edited and updated within my table. However, when I attempt to alter where the contenteditable can be edited, It removes my formatting of the table (it actually removes the table format completely, rendering my idea pointless.
Here is my current code.
<div class="bs-docs-example">
<table class="table table-striped">
<thead>
<tr>
<th>#</th>
<th>IRC Name</th>
<th>Ingame Name</th>
<th>Position</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>[Cr|m|nAl]</td>
<td id="content2" contenteditable="true">Herbalist</td>
<td>Aeterna Top</td>
</tr>
<tr>
<td >2</td>
<td >bandido</td>
<td >Bananni</td>
<td >Aeterna Top</td>
</tr>
<tr>
<td>3</td>
<td>Funkystyle</td>
<td>Funkystyle</td>
<td>Aeterna Top</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
<button id="save">Save Changes</button>
<!-- begin the script -->
<script src="js/jquery.js" type="text/javascript"></script>
<script>
var theContent = $('#content2');// set the content
$('#save').on('click', function () { // store the new content in localStorage when the button is clicked
var editedContent = theContent.html();
localStorage.newContent = editedContent;
});
if (localStorage.getItem('newContent')) { // apply the newContent when it is exist ini localStorage
theContent.html(localStorage.getItem('newContent'));
}
</script>
Now, ideally I would like it to output like this screenshot below;
http://i.imgur.com/R4TYhRB.png
With the column of "Ingame Name" editable.
Add Row/Remove Row, I'm wanting to implement too, but I'm not too sure if you can do it with such a simple HTML table.
My First question-
how would I make a particular row (i.e Ingame Name) be the only one editable? I'm terrible have Javascript/Jquery and my research unfortunately, only allows me to refine one row. (I know I could probably replicate the javascript/jquery, but surely there is an easier way?)
Second question-
Is it possible to actually add the ability for a HTML table to add/remove rows without having a database of some sort?
Thanks for any guidance in regards to this.
Rather than making td editable you could wrap div inside td and make it editable and assign fixed width and height to div.
.clEdit {
width: 200px;
/*Try chaging it as per need*/
overflow: hidden;
/* try scroll with more height */
height: 15px;
/*Try chaging it as per need*/
}
Now there are 2 options either allow overflow to be hidden or scroll. You could examine the behavior and select either one. As a user friendly experience you could assign tooltip to div on hover or click so that whenever values inside div are being overflown user could see what are the current values inside.
$(".clEdit").hover(function(e) {
$(this).prop("title", $(this).html());
});
Yes you could add/delete rows from table without DB if you know the values. id can be calculated from previous id value.
Adding/removing from table does not guarantee DB will be updated you need handle that.
On adding rows you need to bind event for contenteditable as well.
$("#add").click(function() {
//LOGIC TO ADD ROW TO TABLE
var trRow = "<tr><td>" + ++idFirstCol + "</td><td>" + "SecondColValue" + "</td><td><div class='clEdit'>" + "ThirdColValue" + "</div></td> <td> " + "LastColValue" + " </td></tr>";
$("#ConTable").append(trRow);
$(".clEdit").hover(function(e) {
$(this).prop("title", $(this).html());
});
$(".clEdit").prop('contenteditable', true);
});
You could refer to JSFiddle here. http://jsfiddle.net/8mt6d7bz/
Lmk if that answers your question

How to show a table on click of a button in php?

I want to list files from mysql table to a webpage in php. For this i use tables so that i have more regular view. Now there are n numbers of tables on a page. This n is depending upon a mysql query. I am able to list the files on the page. But if numbers of rows in table get increased and value of n is also get increased then my page length will be very long. So i want to give a tree view to each table. Like there will be a button over each table with value '+'. when i click on it the value get change to '-' and that table should be visible.
Here what i tried
<script type="text/javascript">
$(document).ready(function(){
$(".show").html("<input type='checkbox'>");
$('.tree td').hide();
$('th ').click( function() {
$(this).parents('table').find('td').toggle();
});
});
<table width="100%" class="tree">
<tr width="20px"><th colspan="2" class="show"> </th></tr>
<tr>
<td width="50%"><b>Name</b></td>
<td width="50%"><b>Last Updated</b></td>
</tr>
while($row = $result_sql->fetch_assoc())
{
<tr>
<td width='50%'><a href='http://127.0.0.1/wordpress/?page_id=464&name_file={$row['name']}&cat={$cat}&sec={$sec}' target='_blank'>{$row['title']}</a></td>
<td width='50%'>{$row['created']}</td>
</tr>
}
</table>
This is not exact code.
as you can see i am able to do it but i am using a chackbox. i want to have a button with value + or - . There is one problem with this code. The line in which checkbox is showing if i click on it the table is expanded means it taking the entire row not only the checkbox. So anybody can help me with this?
Thanks
I know that this is a code sample, in the future try to provide a jsFiddle to make it easier for people to help. If you want to use +/-, you can make a minor modification like my example
<th colspan="2" width="100%"><span class="show"></span></th>
I basically added the show class to a span within the <th> and attached a click handler on it as well. When you click on it, it will toggle the <td> within the parent <table>... in addition, it will check the text-value in the <th> and inverse it
$('.show').click(function () {
$(this).parents('table').find('td').toggle();
$(this).text() == '+' ? $(this).text('-') : $(this).text('+');
});
Since you don't need a checkbox and you are using a <span>, it won't wrap across the entire <th>. Was this what you were looking for?
Get solution
<script type="text/javascript">
$(document).ready(function(){
$(".show").html("<input type='button' value='+' class='treebtn'>");
$('.tree td').hide();
$('.treebtn ').click( function() {
$(this).parents('table').find('th').parents('table').find('td').toggle();
if (this.value=="+") this.value = "-";
else this.value = "+";
});
});
It is working fine the way i wanted.

Complex jQuery filter() not working

I am trying to dynamically insert links to return to the top of the document at the end of every section of a web page (sad to say, but it's table-based layout). I'm using the jQuery filter() selector, and while I get no error, it's not making any changes in the browser output. When I use alert() with the variable, it says Object object. I understand that the problem is in the line where I define the filter itself, but I was unable to find a similar example, and I don't know how to fix it.
Here's the code:
HTML
<table>
<tr class="head"><td colspan="2">section title 1 </td></tr>
<tr><td>text</td>
<td><img /></td>
</tr>
<tr><td>text</td>
<td>< img /></td>
</tr>
<tr class="head"><td colspan="2">section title 2 </td></tr>
<tr><td>text</td>
<td><img /></td>
</tr>
<tr><td>text</td>
<td>< img /></td>
</tr>
<!-- you get the point -->
JavaScript
$(document).ready(function(){
var lastRow = $('tr').filter(function(){
return $(this).next()==$(".head"); // Here's the problem, IMO
});
var a = '<tr class="toTop"><td class="top" style="text-align:right" colspan="2">go to top ↑</td></tr>';
lastRow.after(a);
});
The script attempts to select each row that precedes a row with class="head" and insert a row with a top link.
That's because you are comparing 2 different objects that is always false, you should use is method or length property:
var lastRow = $('tr').filter(function(){
return $(this).next(".head").length;
// return $(this).next().is(".head");
});
However, I'd suggest using .prev() method:
$('tr.head').prev(); // selects the previous sibling tr element

Categories