Iterate over cells with incrementing ids - javascript

I want to fill a table with values using Javascript/Jquery.
I have a table with incrementing ids (td-1until td-42) and I want to fill this table using JQuery/Javascript.
Currently I am using this script, but I know the error $('#td-'+i) can't work, because the ID used is build wrong: $('#td-'12) is not a valid id.
Has someone a quick fix for this? I am stuck...
for (var i = 1; i < 43; i++) {
if (i < firstDay || i >= (howMany + firstDay)) {
$('#td-'+i).value("");
} else {
$('#td-'+i).value(i-firstDay);
}
}

Use text() and it worked.
var firstDay = 3, howMany = 1;
for (var i = 1; i < 7; i++) {
if (i < firstDay || i >= (howMany + firstDay)) {
$('#td-'+i).text("");
} else {
$('#td-'+i).text(i-firstDay);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id='td-1'></td>
</tr>
<tr>
<td id='td-2'></td>
</tr>
<tr>
<td id='td-3'></td>
</tr>
<tr>
<td id='td-4'></td>
</tr>
<tr>
<td id='td-5'></td>
</tr>
<tr>
<td id='td-6'></td>
</tr>
</table>

First off, reconsider putting a large amount of IDs on elements for efficiency reasons, but putting that aside:
There's a convenience callback for .each() in jQuery, which accepts incremented (current) index and reference to element.
Depending on the DOM structure, you could do:
$('td', '#mytable').each(function(ix, tdel){
$(tdel).attr('id', 'td-' + ix).text(ix); // or $(this).attr...
});
...and see where it takes you to.

Related

Display specific coinmarketcap coin with API while using jQuery

I am trying to read some data about a specific coin of the Coinmarketcap API by using javascript, but nothing is happening. I really don't know where it's going wrong...
var coin = "spectrecoin";
$.get("https://api.coinmarketcap.com/v1/ticker/spectrecoin/", function(data, status) {
for (var i = 0; i < data.length - 1; i++) {
if (data[i].id == "spectrecoin") {
$("#rank").html(data[i].rank);
$("#price").html(data[i].price_usd);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Coin Price</th>
</tr>
<tr>
<td id="rank"></td>
<td id="price"></td>
</tr>
</table>
You're never entering the for loop. Change
i < data.length - 1
to
i < data.length

Changing <td> <i> CSS based on the value

I have been asked to implement a small validation on values and if the values are greater or less than 0 i need to change or add/remove the css for the td and i tag
My table looks something like this
<table class="table table-hover" id="studentweek">
<thead>
<tr>
<th>Year</th>
<th">Weeks</th>
</tr>
</thead>
<tbody>
<tr>
<td>VAR (%)</td>
<td class="text-warning"> <i class="classname">-10.65%</i></td>
</tr>
<tr>
<td>VAR (diff)</td>
<td class="text-warning"> <i class="classname">-13,953</i></td>
</tr>
<tr>
<td>VAR (%)</td>
<td class="text-navy"> <i class="classname">8.81%</i></td>
</tr>
<tr>
<td>VAR (diff)</td>
<td class="text-navy"> <i class="classname">11,320</i></td>
</tr>
</tbody>
</table>
currently i am hard coding the css but i would like to be able to dynamicly change these as the values change automatically, can someone suggest the best way to archive this?
i was thinking in my Ajax request to do something like this:
var sdlyvar = $(parseFloat(".classname").text());
if (sdlyvar < 0){
$('.classname').removeClass(".classname").addClass("fa-level-down");
} else {
$('.classname').removeClass(".classname").addClass("fa-level-up");
}
Use JavaScript parseFloat for parsing percentage (http://www.w3schools.com/jsref/jsref_parsefloat.asp).
var percent = $('#sdlyvar').text();
var result = parseFloat(percent) / 100.0;
if (result < 0){
$('#sdlyvar').removeClass("fa-level-up");
$('#sdlyvar').addClass("fa-level-down")
} else {
$('#sdlyvar').removeClass("fa-level-down");
$('#sdlyvar').addClass("fa-level-up")
}
Your first problem is that you can't compare a string like "-10.95%" with an integer, because of the final % symbol. You have to use parseFloat on tha value:
var sdlyvar = parseFloat($('#sdlyvar').text());
It will take care of all the non-numeric stuff after the number.
Then, you'd probably want to remove the opposite class when updating:
if (sdlyvar < 0){
$('#sdlyvar').removeClass("fa-level-up").addClass("fa-level-down");
} else {
$('#sdlyvar').removeClass("fa-level-down").addClass("fa-level-up");
}
A few random suggestions:
Make clear what's wrong in your code when posting on StackOverflow
When referring an element more than once with jQuery, consider putting the selection in a variable, like var $sdlyvar = $("sdlyvar");: faster to type and execute.
Save us some whitespaces when posting code :/
Here .slice will remove the % sign in this code and the rest of the code will compare the value and assign or remove class
var sdlyvar = $('#sdlyvar').text();
if (sdlyvar.slice(0,-1) < 0){
$('#sdlyvar').removeClass("fa-level-up");
$('#sdlyvar').addClass("fa-level-down");
} else {
$('#sdlyvar').removeClass("fa-level-down");
$('#sdlyvar').addClass("fa-level-up");
}
var lis=document.querySelectorAll("tr td i");
for(var i in lis){
if(parseInt(lis[i].innerHTML)<0){
lis[i].className+=" fa-level-down";
}
else{
lis[i].className+=" fa-level-up";
}
}

check value in table row column

I have a html table - TemplateData. Inside the Tbody I have a column on each row 'data-uid', which may not be unique. I have sorted the table before it is displayed in ascending order. It looks like so:
<tr id="Tr2" data-uid="1" role="row" class="odd"/>
<tr id="Tr2" data-uid="2" role="row" class="even"/>
<tr id="Tr2" data-uid="2" role="row" class="odd"/>
<tr id="Tr2" data-uid="2" role="row" class="even"/>
<tr id="Tr2" data-uid="3" role="row" class="odd"/>
<tr id="Tr2" data-uid="4" role="row" class="odd"/>
NOTE 2 appears three times. Each value may appear more than once
I can get the table by using:
var table = $('#TemplateData').dataTable();
My Question being: if I have a value stored in 'val' how can I check the table to get the row with data-uid=val;
so...something like table.rows[val]
From here check the next row to see if its data-uid is different from val. If so pass back this value. If not continue onto the next row until you find a different value.
So....
val = 2
get table.row[where val = data-uid]
check next row
if table.rows[data-uid = val] continue until it is not the same, when value is different pass back
var newVal = ?
....any help would be appreciated thanks
This is with pure JavaScript, hope it helps.
var elements = document.getElementsByTagName('tr');
var elementsLength = elements.length;
for (var i = 0; i < elements.length; i++) {
var currentElement = elements[i].getAttribute('data-uid');
for (var j = i + 1; j < elements.length; j++) {
var nextElement = elements[j].getAttribute('data-uid');
if(currentElement !== nextElement) {
return elements[j].getAttribute('data-uid');
}
}
}
God luck,
Zorken17
Even if you are not using it, id attribute should be unique.
Then, you can use jquery select syntax to get rows with some characteristics:
function datavalchanged(value) {
..put code to execute at change detection;
}
var group = $('tr[role="row"]');
var desired dataval = group[0].getAttribute('data-uid');
/* additionally put dataval=0 to detect also first data-uid change. */
to get all rows that have role = row and cycle trought them like an array.
for (var i = 0; i < group.length; i++) {
var row = group[i];
var value = row.getAttribute('data-uid');
while (value == dataval) {
continue;
}
datavalchanged(value);
dataval=value;
/*ready for next change detection or force exit if interested in first change*/
}
at the end of while loop the value has the next value u need.
edit:
it looks like that what i wrote it does not work if the html is not complete:
<table>
<tr id="Tr2" data-uid="1" role="row" class="odd" ><td></td></tr>
<tr id="Tr2" data-uid="2" role="row" class="even"><td></td></tr>
<tr id="Tr2" data-uid="2" role="row" class="odd" ><td></td></tr>
<tr id="Tr2" data-uid="2" role="row" class="even"><td></td></tr>
<tr id="Tr2" data-uid="3" role="row" class="odd" ><td></td></tr>
<tr id="Tr2" data-uid="4" role="row" class="odd" ><td></td></tr>
</table>

jQuery: select tr having all td matching the filter criteria dynamically

Title might be a bit confusing, but this is the best I could come up with.
I need to find all tr elements which contains td elements matching the filter criteria provided.
Here is my sample,
<tr class="row" id="1">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="lamp">Lamp<td>
</tr>
<tr class="row" id="2">
<td class="philips">PHILIPS</td>
<td class="h5">H5</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="3">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="4">
<td class="philips">PHILIPS</td>
<td class="h4">H4</td>
<td class="bulb">Bulb<td>
</tr>
<tr class="row" id="5">
<td class="osram">OSRAM</td>
<td class="hb3">HB3</td>
<td class="tube">Tube<td>
</tr>
<tr class="row" id="6">
<td class="neglin">NEGLIN</td>
<td class="w5w">W5W</td>
<td class="lamp">Lamp<td>
</tr>
If I pass filter[0] as 'phillips', the result return tr with id
1
2 and
4
Then if I pass second filter; filter[1] as 'h4', the result should be filtered down to
1 and
4
I have tried this question.
Which has this answer.
$('tr')
.has('td:nth-child(1):contains("Audi")')
.has('td:nth-child(2):contains("red")')
.doSomeThing();
But, I want my filters to be applied dynamically. How would I be able to insert a 3rd has function?
I don't want to go the if-else or switch-case way, if this is possible with out them.
You can try this.
<script type="text/javascript">
$(document).ready(function () {
var result = filter([".philips", ".h4"]);
alert(result);
var result_2 = filter([".philips"]);
alert(result_2);
});
function filter(params) {
var select = "tr";
for (var i = 0; i < params.length; i++) {
select += ":has(" + params[i] + ")";
}
return $(select).map(
function () {
return $(this).attr('id');
}
).get();
}
</script>
if you have an array of filters needed, iterate that array and pass the filter string to the has?
var filters = ['PHILIPS', 'H4', 'Bulb']
var result = $('tr');
for(var i = 0; i < filters.length; i++){
var nchild = i+1;
result = result.has('td:nth-child('+nchild+'):contains("+'filters[i]'+")');
}
edit to your needs of course, but this way you can take user input, compile that into the needed array and then iterate whatever is in the array to filter down results.
You should wrap the $.has() into a separate function (I've just used jquery's easy extensions supports) which will expose the usage as a composite function chain via javascript's syntax...
$( document ).ready(function() {
$('tr')
.nthFilter('td:nth-child(1):contains("PHILIPS")')
.nthFilter('td:nth-child(2):contains("H4")')
.nthFilter('td:nth-child(3):contains("Bulb")')
.css("background-color", "red");
});
jQuery.fn.extend({
nthFilter: function(filter) {
return $(this).has(filter);
}
});
I've put together a small jsfiddle for you to fiddle with :)
You can supply your filter as a string:
var filter = ".philips, .h4";
$("tr").has("td").has(filter).map(function() { return this.id; });
// returns ["1", "2", "4"]
and if you want the elements then obviously leave the map off:
$("tr").has("td").has(filter);
// returns array of <tr>
Edit: Just noticed you want recursive filtering so change the filter to use sibling selector ~.
var filter = ".philips ~ .h4";
// returns ["1", "4"]
So if you want a third level then just:
var filter = ".philips ~ .h4 ~ .bulb";
// returns ["4"]

Multiply td values

I have a html table that looks like this...
<table>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</table>
<p>Total number is:MULTIPLICATION OF ALL CHANCE COLUMN TD</p>
all my rows are added dynamically,how do i multiply all chance column td values(numbers)?Do i have to put certain class on chance tds and then get all tds with that class,and loop through and multiply every value then?I'm kinda a newbie so any help would be appreciated.
You can either do something like this:
var tots = 1;
$('tr td:nth-child(4)').each(function(){
tots *= $(this).text();
});
the nth-child(4) is selecting the fourth td in each row, if you want another, just change that number.
or you can give the cells you want to multiple classes, like you said.
example here
If you're using jQuery, the :last-child selector could be helpful.
<p>Total number is: <span id="result"></span></p>
Javascript:
res = 1;
$("tr td:last-child").each(function() {
res *= parseFloat($(this).html());
});
$("#result").html(res);
Have a look to this JSFiddle.
You don't need jQuery to do this. querySelectorAll supports nth-child selector as well.
var derp = document.querySelectorAll("tr td:nth-child(4)");
var total = 1;
var results = [].reduce.call(derp, function (prev, next) {
return prev * ( + next.textContent );
});
Grab the element, and use native Array prototype methods ([]) to iterate the NodeList and return the parsed value of the element, then return the multiplied total.
Here is a fiddle for you.
$(function () {
var chanceTotals = 1;
$("tr td:nth-child(4)").each(function () {
chanceTotals *= parseFloat($(this).html());
});
$("#totals").html("Total number is: " + chanceTotals);
});
Using jQuery, this executes an anonymous function when the document is ready that will do the calculation for you.
You will need to add the id totals to your p element in order for this to work.
Look at this JSFiddle
You really do not need jquery at all to do this. Interacting with the DOM directly may make you write more (browser support), but it can be more efficient than using jQuery (Unnecessary overhead).
As you can see, I restructured your <table>. I could have just grabbed the <tbody> and looped over its children and skipped the whole if <TD> ? check.
DEMO
$(document).ready(function () {
var table = $('#myTable').get(0);
var multiplier = 1;
var col = 3;
for (var row = 0; row < 4; row++) {
var cell = table.rows[row].cells[col];
if (cell.nodeName == 'TD') {
var text = cell.innerText || cell.textContent;
multiplier *= parseFloat(text);
}
}
$('#multiplier').text(multiplier);
});
<table id="myTable">
<thead>
<tr>
<th>Date</th>
<th>Pair</th>
<th>Game</th>
<th>Chance</th>
</tr>
</thead>
<tbody>
<tr>
<td>2014-2-12</td>
<td>Milan-Udinese</td>
<td>1</td>
<td>1.6</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Juventus-Inter</td>
<td>x</td>
<td>2.5</td>
</tr>
<tr>
<td>2014-2-13</td>
<td>Arsenal-Liverpul</td>
<td>2</td>
<td>2.5</td>
</tr>
</tbody>
</table>
<p>Total number is:
<span id="multiplier">MULTIPLICATION OF ALL CHANCE COLUMN TD</span>
</p>

Categories