How to loop a table in jQuery - javascript

I want to throw the last 2 digits of the clock, I use jquery but it always fails in looping
Only one row changes, i want to change all rows.
this is my code
$(document).ready(function(){
var jam = $("#jamberangkat").text();
var datearray = jam.split(":");
var newjam = datearray[0] + ":" + datearray[1];
return $("#jamberangkat").text(newjam);
});
<table>
<tbody>
<tr>
<td id="jamberangkat" style="width:20%;">{{ $data->jam }}</td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
this is my result

It seems like you want to iterate through all the <td> with the ID of jamberangkat. Remember that IDs must be unique throughout the DOM, so you will need to use a class to identify that cell that you want to change.
Most jQuery methods are actually implicit iterators, so you can simply use a callback in $('.jamberangkat').text(<callback>) to perform the text filtering for you for all elements that matches the selector. What you want in that filter is:
Extract the text value of the element. This is accessible as the second argument in the .text() method: refer to the jQuery API documentation for .text()
Split the text by : as you have intended
Keep only the first two elements (in your code I deduced you only want to keep the first and second fragment of the array). This can be done by using .slice(0, 2)
Rejoin the spliced array (which now retains only the first two elements) using .join(':').
See proof-of-concept example below:
$(document).ready(function(){
$(".jamberangkat").text(function(index, txt) {
return txt.split(':').slice(0,2).join(':');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td class="jamberangkat" style="width:20%;">12:34:56</td>
<td>Random text</td>
</tr>
<tr>
<td class="jamberangkat" style="width:20%;">12:34:56</td>
<td>Random text</td>
</tr>
<tr>
<td class="jamberangkat" style="width:20%;">12:34:56</td>
<td>Random text</td>
</tr>
<tr>
<td class="jamberangkat" style="width:20%;">12:34:56</td>
<td>Random text</td>
</tr>
</tbody>
</table>

Related

Show rows in table with cells name attribute containing string from input (JQuery)

I would like to have keyup function that would show only rows matching the input text by cell that spans on multiple rows.
Consider following table:
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1'> dummy1 </td>
</tr>
<tr>
<td name='Key1'> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2'> dummy3 </td>
</tr>
<tr>
<td name='Key2'> dummy4 </td>
</tr>
</table>
jsfiddle
Here each row has second td tag with name that matches its "parent" column text. So when I type 'Key1' at the input field I would like it to show only dummy1 and dummy2. Is it possible in jquery?
I understand that you want to display the rows that has a matching name. If this is wrong, please elaborate more, then I can update it.
Here is a demo: https://jsfiddle.net/erkaner/gugy7r1o/33/
$('input').keyup(function(){
$('tr').hide();
$("td").filter(function() {
return $(this).text().toLowerCase().indexOf(keyword) != -1; }).parent().show().next().show();
});
});
Here's my take on your issue, assuming you always want the first column to show. https://jsfiddle.net/gugy7r1o/2/
<input type="text" id="myInput" />
<table border='1'>
<tr>
<td rowspan='2'>Key1</td>
<td name='Key1' class="data"> dummy1 </td>
</tr>
<tr>
<td name='Key1' class="data"> dummy2 </td>
</tr>
<tr>
<td rowspan='2'>Key2</td>
<td name='Key2' class="data"> dummy3 </td>
</tr>
<tr>
<td name='Key2' class="data"> dummy4 </td>
</tr>
</table>
.data{
display:none;
}
var theData = $('td.data');
var input = $('#myInput').on('keyup', function(){
theData.hide();
var value = input.val();
var matches = theData.filter('[name="'+value+'"]');
matches.show();
});
Firstly, I would recommend using <ul> to wrap each key in as tables should be used for data structure (Forgive me if that is what it is being used for).
Secondly, just attach an on keyup event to the search box and then find matches based on the id. See example below:
JS Fiddle Demo
It is also worth mentioning that it could be useful attaching a timeout to the keyup event if you end up having large amounts of rows so that only one filter is fired for fast typers!

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
}

jQuery - Select current table row values

When someone clicks on the Download button in my table, I want to pass the date values from that particular row to a function. Currently I can only pass the date values from the first table row.
This is the selector I'm using:
$(this).parent().find('#period-start');
Which always returns:
[<td id=​"period-start">​5/1/2013​</td>]
I've tried combinations of the parent, child, find and closest selectors, but haven't been able to stumble across the correct one to grab the date values from the current row. Thanks.
Table
<table id="tblStatements" class="table">
<thead>
<tr>
<th>Period Starting</th>
<th>Period Ending</th>
<th>Download</th>
</tr>
</thead>
<tbody>
<tr>
<td id='period-start'>5/1/2013</td>
<td id='period-end'>5/31/2013</td>
<td><button type='submit'>Download</button></td>
</tr>
<tr>
<td id='period-start'>4/1/2013</td>
<td id='period-end'>4/30/2013</td>
<td><button type='submit'>Download</button></td>
</tr>
<tr>
<td id='period-start'>3/1/2013</td>
<td id='period-end'>3/31/2013</td>
<td><button type='submit'>Download</button></td>
</tr>
</tbody>
</table>
ID's are always supposed to be unique in HTML. So, you might try out this, w/o using an ID:
// Get the first td
var periodStart = $(this).closest('tr').children('td:eq(0)').text();
// Get the second td
var periodEnd = $(this).closest('tr').children('td:eq(1)').text();
FIDDLE DEMO
Use this - don't use duplicate ID's though, use class instead
$(this).closest('tr').find('#period-start');
or -
$(this).closest('td').siblings('#period-start');
try this
$(this).parent().siblings('#period-start');
Make sure all your ids is unique..your HTML is invalid.... change it to class and try this
$(this).parent().siblings('.period-start');
You should not use more then one element with the same id use class insidead.
<tr>
<td class='period-start'>5/1/2013</td>
<td class='period-end'>5/31/2013</td>
<td><button type='submit'>Download</button></td>
</tr>
<tr>
<td class='period-start'>4/1/2013</td>
<td class='period-end'>4/30/2013</td>
<td><button type='submit'>Download</button></td>
</tr>
<tr>
<td class='period-start'>3/1/2013</td>
<td class='period-end'>3/31/2013</td>
<td><button type='submit'>Download</button></td>
</tr>
and use this code to select proper element
$(this).parents('tr').find('.period-start');
try this
$.trim($(this).closest('tr').find('[id="period-start"]').html());//this gives start date

an easy way to get all the table rows from a table without using a loop

Is there an easy way to get all the table rows from a table without using a loop.
I thought that this would work but it only alerts the first row.
http://jsfiddle.net/THPWy/
$(document).ready(function () {
var O = $('#mainTable').find('tr');
//var O = $('#mainTable tr');
alert(O.html());
//alerts <th>Month</th><th>Savings</th>
});
<table id ="mainTable" border="1">
<caption>Monthly savings</caption>
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
<tr>
<td>February</td>
<td>$50</td>
</tr>
<tr>
<td>March</td>
<td>$50</td>
</tr>
<tr>
<td>a</td>
<td>$50</td>
</tr>
<tr>
<td>m</td>
<td>$50</td>
</tr>
<tr>
<td>j</td>
<td>$50</td>
</tr>
<tr>
<td>july</td>
<td>$50</td>
</tr>
<tr>
<td>aug</td>
<td>$50</td>
</tr>
<tr>
<td>sep</td>
<td>$50</td>
</tr>
</table>
Whatever you use will be iterating through each row to get the inner HTML out of it. So no, you cannot do it without a loop.
Here is an alternate method that gets the message in one line if that's what you're after, it's slightly less efficient than going with a loop though as it needs to make a new array.
jsFiddle
$(document).ready(function () {
var rows = $('#mainTable tr');
var message = $.map(rows, function (v) {
return v.innerHTML;
}).join('\n');
alert(message);
});
I would recommend just doing it in a regular loop.
FYI .html() only alerts the first row because that's what it was designed to do as that is what would be most useful.
Description: Get the HTML contents of the first element in the set of matched elements.
What about:
// get all tr (excluding the caption)
var O = $('table#mainTable').children().slice(1);
http://jsfiddle.net/THPWy/7/
What you have in your code already retrieves all table rows as an array of jQuery elements:
var trs = $('#mainTable').find('tr');
If you want to print the html contents of each row then you would have to use a loop:
trs.each(function (index, element) {
alert($(this).html());
});
You can get by using
gt(), lt(),eq()
.gt(index) // will get all the rows greater than specified index
.lt(index) // will get all the rows less than specified index
.eq(index) // will get all the rows equal to specified index
For Example
$('#mainTable tr').eq(1) will give second row
But when you want to know all the table rows data then go with Konstantin D - Infragistics solution

How to update table cell value using jQuery

I am having problem updating table cell value using jQuery 1.4.2. it all works in Firefox and Safari but IE8 and IE9 is simply not doing anything. There is no warning, error or anything that would give me some hint where to look for it.
Table looks following:
<table id="test">
<tr id="1">
<td id="name">sample name</td>
<td id="schedule">sample value</td>
<td id="day">sample value</td>
</tr>
<tr id="2">
<td id="name">sample name</td>
<td id="schedule">sample value</td>
<td id="day">sample value</td>
</tr>
<tr id="3">
<td id="name">sample name</td>
<td id="schedule">sample value</td>
<td id="day">sample value</td>
</tr>
</table>
I am executing ajax call and getting json data:
{"Test": [
{"id":"1", "name":"John", "day":"Monday"},
{"id":"2", "name":"Marry", "day":"Thursday"}
]}
once data is received there is a loop which iterates through the json dataset and updates appropriate column with received data as following:
$.each(json.Tests, function(){
/* update test with details */
var test = this.hash;
/*set values for each test */
$("table#test tr[id=" + test + "]").find("#name").html(this.name);
$("table#test tr[id=" + test + "]").find("#schedule").html(this.status);
$("table#test tr[id=" + test + "]").find("#day").html(this.changed);
});
As I mentioned, this has been tested in Safari and Firefox all works fine but IE8 and IE9 seems not to do anything.
I think the id attribute should be reserved for unique identifiers in my opinion. How about changing the id attribute of the td elements to a class attribute or even name attribute. I suspect that IE is getting confused.
Also, if you keep ids unique and change the id attribute of the td to a class then you can change your code to something like:
$("#" + test + " td.name").html(this.name);
And because a number could represent pretty much anything also prefixing those ids with some sort of identifier prefix would be good. Something like:
$("#thing-" + test + " td.name").html(this.name);
And the html would look like this:
<table id="test">
<tr id="thing-1">
<td class="name">sample name</td>
<td class="schedule">sample value</td>
<td class="day">sample value</td>
</tr>
<tr id="thing-2">
<td class="name">sample name</td>
<td class="schedule">sample value</td>
<td class="day">sample value</td>
</tr>
<tr id="thing-3">
<td class="name">sample name</td>
<td class="schedule">sample value</td>
<td class="day">sample value</td>
</tr>
</table>
Hope that helps!
Ids aren't supposed to start with a number. Perhaps IE9 isn't as forgiving as the other browsers.
Have you an URL for us to Test your Script?

Categories

Resources