I have following table
<table class="data">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1 data
</td>
<td>
2 data
</td>
<td>
123456789123
</td>
</tr>
</tbody>
</table>
how can I dynamically scan table and replace only values in third table body td values where information like 123456789123 is stored.
This information should be placed with certain character on certain string location so
<td> 123456789123 </td> should be <td> 12345678*12* </td>
Please find below code block for your need, I have added one specific class to TD for which you want to modify value.
$( document ).ready(function() {
$('.value_td').each(function(key, ele){
// Getting Original Value
var original_val = $(ele).text().trim();
// You can change your logic here to modify text
var new_value = original_val.substr(0, 8) + '*' + original_val.substr(9, 2) + '*';
// Replacing new value
$(ele).text(new_value);
});
});
<table class="data">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
</tr>
</thead>
<tbody>
<tr>
<td>
1 data
</td>
<td>
2 data
</td>
<td class="value_td">
123456789123
</td>
</tr>
</tbody>
</table>
JS Fiddle
To replace the selected texts by indexs, use this:
// replace the 'n'th character of 's' with 't'
function replaceAt(s, n, t) {
return s.substring(0, n) + t + s.substring(n + 1);
}
$('td:nth-of-type(3)').each(function(i, item){
$(this).text($(this).text().trim()); // remove extra spaces
$(this).text(replaceAt($(this).text(), 8, '*')); // replace character in position 8
$(this).text(replaceAt($(this).text(), 11, '*')); // replace character in position 11
});
See the working demo: https://jsfiddle.net/lmgonzalves/6ppo0xp3/
Try this:
$('.data td:nth-child(3n)').text('foo');
This will change every 3rd td’s text inside .data to foo. Here’s a demo: http://jsbin.com/katuwumeyu/1/edit?html,js,output
Let me know if that helps, I’ll gladly adapt my answer in case this isn’t what you need.
You can use jquery ":eq(2)" to track 3rd td position like this:
var el = $('table.data tbody tr td:eq(2)');
el.text(el.text().replace('123456789123','12345678*12*'));
https://jsfiddle.net/v25gu3xk/
or maybe you need to replace char positions:
var el = $('table.data tbody tr td:eq(2)');
var vl = el.text().trim();
el.text(vl.substr(0, 8) + '*' + vl.substr(9, 2) + '*');
https://jsfiddle.net/v25gu3xk/1/
Related
I have an html table generated dynamically from a database. Rows where a particular cell value is the same represents paired data and I want to separate those pairs with an empty row. The best way I can think of is to find where that value differs from the preceding value. Is this possible?
<table id="myTable">
<tr>
<th>Team #</th>
<th>Name</th>
<th>Age</th>
</tr>
<tbody>
<tr class="data-in-table">
<td class="id">12345</td>
<td>Tom</td>
<td>46</td>
<tr class="data-in-table">
<td class="id">12345</td>
<td>Dick</td>
<td>32</td>
<tr class="data-in-table">
<td class="id">34567</td>
<td>Harry</td>
<td>45</td>
<tr class="data-in-table">
<td class="id">76543</td>
<td>Will</td>
<td>45</td>
</tr>
<tr class="data-in-table">
<td class="id">76543</td>
<td>Sam</td>
<td>45</td>
</tr>
</tbody>
This is code I've seen comparing adjacent cells and tried to change for my needs:
$("#myTable").each(function () {
$(this).find('tr').each(function (index) {
var currentRow = $(this);
var nextRow = $(this).next('tr').length > 0 ? $(this).next('tr') : null;
if (index%2==0&&nextRow && currentRow(td[0].text() != nextRow(td[0].text()) {
$('#myTable tr:next').after('<tr><td></td><td></td><td></td></tr>');
}
});
});
I'd like it to look something like this:
Team # Name Age
12345 Tom 46
12345 Dick 32
34567 Harry 45
76543 Will 45
76543 Sam 45
As the database updates, team members will always be positioned adjacent to each other, but sometimes one teammate will appear before the second teammate and the table should reflect that.
I found that this works, through trial and error:
var last = ''
var rowCount = $('#myTable >tbody >tr').length;
for (var i=0;i<rowCount-1;i++) {
if (last != $('#myTable tr .id:eq('+i+')').html()) {
var lastRow = $('#myTable tr .id:eq('+i+')')
$(lastRow).parents('tr').before('<tr><td></td><td></td><td></td></tr><tr><td></td><td></td><td></td></tr>')
}
var last = $('#myTable tr .id:eq('+i+')').html()
}
I don't know if there is a more efficient way than using a for.. statement to run through each row.
I have a table that are like a grid with a horizontal list in the top with week numbers within th tags and below each week are different values in rows of tr and td tags.
I'm trying to get the data-attribute for the week when I click below in one of the td tags with the data-id attribute. But I can't get it right and wonder what I have done wrong to be able to read this value?
Some of the combinations I have tested:
var test = $(this).closest("th").attr("data-week");
var test = $(this).parents().find(".week").attr("data-week");
var test = $(this).parents("th").attr("data-week");
The HTML with data-attributes for the table:
<table>
<thead>
<tr>
<th class=""></th>
<th class="week" data-week="15">15</th>
<th class="week" data-week="16">16</th>
<th class="week" data-week="17">17</th>
<th class="week" data-week="18">18</th>
<th class="week" data-week="19">19</th>
</tr>
</thead>
<tbody>
<tr>
<td>Stina (1)</td>
<td data-id="40">10</td>
<td data-id="12">20</td>
<td data-id="13">40</td>
<td data-id="14">45</td>
<td data-id="15">40</td>
</tr>
<tr>
<td>Linda (2)</td>
<td data-id="0">0</td>
<td data-id="0">0</td>
</tr>
<tr>
<td>Lasse (3)</td>
<td data-id="21">5</td>
<td data-id="22">39</td>
<td data-id="23">40</td>
<td data-id="24">40</td>
</tr>
</tbody>
</table>
#Sean DiSanti, good one!
Here is a slightly more efficient version, without warping $ in $, by using eq method
$('td').on('click', function(e) {
var index = $(this).index() -1;
var week = $('.week').eq(index).data('week');
console.log('week', week);
});
jsfiddle
Here is a way you can find the data-week attribute of the clicked th element.
$(document).ready(function(){
$("td").on("click",function(){
$td=$(this);
$th = $td.closest('table').find('th').eq($td.index());
alert($th.attr("data-week"));
});
});
Demo: https://jsfiddle.net/7b146hor/2/
You need to find it by index. Get which child number the clicked element has and then look for same number in .weeks
Demo
$('td').on('click', function(e){
index = $(this).index();
week = $('.weeks').find(":eq("+index+")").attr('data-week');
console.log(week);
});
This worked for me
$('td').on('click', function(e) {
index = $(this).index();
week = $($('.week')[index - 1]).data('week');
console.log('week', week);
});
jsfiddle example
Having such table
<table>
<thead> ... </thead>
<tbody>
<tr class="TableOdd">
<td class="TableCol0"> 1 </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> x </td>
<td class="TableCol3"> # </td>
</tr>
<tr class="TableEven">
<td>....</td>
</tr>
</tbody>
E.g. each cell has own class indicating it's column number TableCol0,1,2..N
In each row, needed compare the content of the cells in column 1 and 2 and write the result into colum3.
Managed the following script,
$(document).ready(function() {
var toterr = 0;
$('tbody tr.TableEven,tbody tr.TableOdd').each(function() {
var wanted = $(this).find('.TableCol1' ).html();
var actual = $(this).find('.TableCol2' ).html();
//console.log('wanted='+wanted+'=actual='+actual+'=');
if ( wanted == actual ) {
$(this).find('.TableCol3').text('ok');
} else {
$(this).find('.TableCol3').text('ERROR');
toterr++;
}
});
$('#totalerror').text(toterr);
});
It is probably not optimal, but works.
Now have a bit different scenario: Need compare two cells what are before a cell with a specified content (:CMP:), e.g:
<table>
<thead> ... </thead>
<tbody>
<tr class="TableOdd">
<td class="TableCol0"> x </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> :CMP: </td>
<td class="TableCol3"> etc </td>
</tr>
<tr class="TableEven">
<td class="TableCol0"> N </td>
<td class="TableCol1"> x </td>
<td class="TableCol2"> y </td>
<td class="TableCol3"> :CMP: </td>
</tr>
</tbody>
For each row, need compare cells what are before :CMP:, and replace the :CMP: with the result. e.g.
in the 1st row need compare the x and x and write ok in the cell .TableCol2
in the 2nd row need compare the x and y and write ERROR in the cell .TableCol3
I haven't idea how to modify the above script.
Can easily get the index of the cell that contains ':CMP:' and use the index to reference the previous cells. Or use traverses like prev() or use eq() once index is found.
$('tbody tr').each(function () {
var $cells = $(this).children(),
$cmp = $cells.filter(':contains(":CMP:")'),
cmpIndex = $cells.index($cmp);
// array of values of previous cells
var values = $.map($cells.slice(cmpIndex - 2, cmpIndex), function (el) {
return $.trim($(el).text());
});
// make sure we have 2 cells with values and compare
var cmpText = values.length === 2 && values[0] === values[1] ? 'OK' : 'ERROR';
$cmp.text(cmpText);
});
DEMO
I have a list of table rows and these tr's have numbered classes for some reason (leg-1, leg-2 etc). It is already possible to delete a single tr from within this context.
After deleting a tr I need to rename the remaining tr's.
Example:
I have
<tr class="leg-1"></tr>
<tr class="leg-2"></tr>
<tr class="leg-3"></tr>
Now I delete leg-2. Remaining are:
<tr class="leg-1"></tr>
<tr class="leg-3"></tr>
Now I want to rename the remaining tr's, so that it's back to leg-1 and leg-2.
How can this be done??
Thx for any help!
EDIT:
I forgot to mention that it can have more than one tr with class "leg-1", "leg-2" ... So the right starting example would be
<tr class="leg-1"></tr>
<tr class="leg-1"></tr>
<tr class="leg-2"></tr>
<tr class="leg-3"></tr>
<tr class="leg-3"></tr>
Now when I delete leg-2 , both of the tr's with class="leg-3" have to be renamed to be class="leg-2". ..
Sorry I didn't mention this earlier!!
SEE IT IN ACTION
http://jsfiddle.net/Lynkb22n/2/
I'd suggest, at its most straightforward:
$('tr').each(function(i) {
// looking for a class-name that starts with (follows a
// word-boundary: \b) leg- followed by one or more numbers (\d+)
// followed by another word-boundary:
var matchedClass = this.className.match(/\bleg-\d+\b/);
// if a match exists:
if (matchedClass) {
// set the node's className to the same className after replacing
// the found leg-X class name with the string of 'leg-' plus the
// index of the current element in the collection plus one:
this.className = this.className.replace(matchedClass[0], 'leg-' + (i + 1));
}
});
$('tr').each(function(i) {
var matchedClass = this.className.match(/\bleg-\d+\b/);
// if a match exists:
if (matchedClass) {
this.className = this.className.replace(matchedClass[0], 'leg-' + (i + 1));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr class="leg-2323523">
<td>1</td>
</tr>
<tr class="leg-2323523">
<td>2</td>
</tr>
<tr class="leg-2323523">
<td>3</td>
</tr>
<tr class="leg-2323523">
<td>4</td>
</tr>
</tbody>
</table>
Using an id is somewhat easier, since we don't need to preserve pre-existing concurrent ids, as we do with classes:
// selects all <tr> elements, sets their `id` property
// using the anonymous function available within prop():
$('tr').prop('id', function (i) {
// i: the index amongst the collection of <tr> elements:
return 'leg-' + (i+1);
});
$('tr').prop('id', function (i) {
return 'leg-' + (i+1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
</tbody>
</table>
If the index/row-number is simply to be available to JavaScript, then you could just as easily use the native rowIndex property available to all HTMLTableRowElements:
// selects <tr> elements, binds the 'mouseenter' event-handler:
$('tr').on('mouseenter', function() {
// logs the HTMLTableRowElement rowIndex property
// to the console:
console.log(this.rowIndex);
});
$('tr').on('mouseenter', function() {
console.log(this.rowIndex);
});
td {
border: 1px solid #000;
width: 4em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>1</td>
</tr>
<tr>
<td>2</td>
</tr>
<tr>
<td>3</td>
</tr>
<tr>
<td>4</td>
</tr>
</tbody>
</table>
References:
JavaScript:
HTMLTableRowElement.
JavaScript Regular Expression Guide.
String.prototype.match().
String.prototype.replace().
jQuery:
each().
prop().
Updated
Based on your comment below and your updated question, here is an updated solution.
var removed = $(".leg-2"),
siblings = removed.nextAll(), // affect only next siblings to removed element
pos = ""; // store current number after "leg-"
removed.remove(); // remove element
siblings.each(function (k) {
$(this).removeClass(function (i, key) {
pos = key.split("-")[1]; // update number after "leg-"
return (key.match(/\bleg-\S+/g) || []).join(' ');
}).addClass("leg-" + (pos - 1)); // add "leg-" plus new position
});
See it working here.
You can use .removeClass() with .match() to remove class starts with leg and then add class leg plus tr's index using .addClass().
See it working here.
$("tr").each(function (k) {
k++;
$(this).removeClass(function (i, key) {
return (key.match(/\bleg-\S+/g) || []).join(' ');
}).addClass("leg-" + k);
});
Try this it will re-name the class:
$(document).ready(function(){
$("#click").click(function(){
reorder();
});
});
function reorder(){
$('#myTable > tbody > tr').each(function(index) {
console.log($(this).attr('class','leg-'+(index+1)));//avaoid starting fron 0
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
<tr class="leg-1"><td>a1</td></tr>
<tr class="leg-2"><td>a2</td></tr>
<tr class="leg-3"><td>a3</td></tr>
<tr class="leg-7"><td>a4</td></tr><!--after click on button class will become class="leg-4" -->
<tr class="leg-8"><td>a5</td></tr><!--after click on button class will become class="leg-5" -->
</table>
<button id="click">CliCk</button>
I'm trying to count how many starting table row tags <tr> that would be in the following text. Keep in mind that I said text, not html. I get this data back in a textarea (don't ask) and I need to count how many starting tr tags are in this textarea. How would I do that? Whats the appropriate method in jquery to achieve this?
<textarea name='details' id='details'>
<table>
<tbody>
<tr>
<th></th>
</tr>
<tr>
<th></th>
</tr>
</tbody>
</table>
</textarea>
you can do:
var temp =$('#details').val();
var count = temp.match(/<tr[^>]*>/gi);
jsfiddle
now count <tr > <tr class=""> <TR>
You should wrap your text in a jquery object and then use length property:
var myText = $.trim($('#details').val());
var numberTRs = $(myText).find('tr').length;
jsFiddle ©Blake Plumb 2013 ;)