javascript programming with jinja values - javascript

I have a block of HTML code
<td>{{stock.C4}}</td>
<td>{{stock.C5}}</td>
<td>{{stock.C6}}</td>
<td>{{stock.C7}}</td>
<td>{{stock.C8}}</td>
{{stock.C4}} has an output of None in the html cell.
I want (maybe javascript?) code that basically says
if {{stock.C4}} == 'None'
element.style.backgroundColor = "red"
code that makes the cell a color based on the html/jinja value

If the content of the cell il really empty, you can add the rule
td:empty {
background-color: red;
}
to your css (adapt the selector and the styles to your needs).
the :empty pseudoclass is supported since ie9 (no need to say that other browser support it from day zero).
Also mobile support seems quite good.

Use document.querySelectorAll to get all the td of a specific table, the use array#forEach to check if it is empty using innerHTML, if so use classList.add to add a css class to it
var getAllTD = document.querySelectorAll("#demoTable td");
getAllTD.forEach(function(item) {
if (item.innerHTML === '') {
item.classList.add('empty')
}
})
.empty {
background: green;
}
<table border="1" id="demoTable">
<tr>
<td>1</td>
<td>2</td>
</tr>
<tr>
<td></td>
<td>4</td>
</tr>
<tr>
<td>5</td>
<td></td>
</tr>
</table>

Here is a possible solution using Mustache (that requires to change your data structure) :
var stocks = [
["A1", "A2", "None"],
["None", "B2", "B3"],
["C1", "None", "C3"]
];
var view = {
stocks: stocks,
isNone: function () {
return this == "None";
}
};
var template = ""
+ "{{#stocks}}"
+ "<tr>"
+ "{{#.}}"
+ "{{#isNone}}<td class=\"none\">{{.}}</td>{{/isNone}}"
+ "{{^isNone}}<td>{{.}}</td>{{/isNone}}"
+ "{{/.}}"
+ "</tr>"
+ "{{/stocks}}"
;
var table = document.getElementById("table");
table.innerHTML = Mustache.render(template, view);
table,td{border:1px solid black;border-collapse:collapse;}
td.none{background:#ffa7b7}
td{padding:.25em}
<script src="https://cdnjs.cloudflare.com/ajax/libs/mustache.js/2.3.0/mustache.min.js"></script>
<table id="table"></table>

Related

How can I fix jquery when i change table elements to div style in body section?

<body>
<input type="text" id="search"/>
<table id="boxdata">
<tr>
<td class="namebox1">jQuery</td>
</tr>
<tr>
<td class="namebox2">javascript</td>
</tr>
<tr>
<td class="namebox3">php</td>
</tr>
<tr>
<td class="namebox4">sql</td>
</tr>
<tr>
<td class="namebox5">XML</td>
</tr>
<tr>
<td class="namebox6">ASP</td>
</tr>
</table>
</body>
<script>
$(document).ready(function(){
$('#search').keyup(function(){
searchBox($(this).val());
});
});
function searchBox(inputVal) {
$('#boxdata').find('tr').each(function(index, row){
var names = $(row).find('td');
var found = false;
if(names.length > 0) {
names.each(function(index, td) {
var regExp = new RegExp(inputVal, 'i');
if(regExp.test($(td).text()) & inputVal != ''){
found = true;
return false;
}
});
if(found == true)
$(row).addClass("red");
else
$(row).removeClass("red");
}
});
}
</script>
there's a textfield for searching words and there are 6 words in the each 6 boxes below textfield.(I omitted css codes. but, it wouldnt matter to solve the problem.). if i type a letter 's' then the words that including letter 's' like 'javascript', 'sql', 'ASP' these font-color will be changed black to red. And i made it by using table elements in html but i'd like to change all elements into div style to put some data fluidly later. i have difficulty to fix especially jquery. how can i fix it?
You can simplify this a little bit.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal, 'i');
$('#boxdata').find('tr').removeClass('red').filter(function() {
return $(this).find('td').filter(function() {
return regExp.test( $(this).text() );
}).length && $.trim(inputVal).length;
}).addClass('red');
}
So remove the red class from all <tr>'s first, then filter them, test the text of each <td>, if it matches, return the <tr> and then add the class red again.
Here's a fiddle
As for changing from a table to div, the jQuery would depend on how you structure your markup, but the principle would remain the same.
Here's another fiddle
You can make javascript code HTML agnostic by using css classes instead of element names. Demo.
function searchBox(inputVal) {
var regExp = new RegExp(inputVal = $.trim(inputVal), 'i'),
highlight = 'red';
$('#wrapper').find('.word') //instead of tr/td/div
.removeClass(highlight)
.each(function(){
var $this = $(this);
inputVal && regExp.test($this.text()) &&
$this.addClass(highlight);
});
}

Using Jquery and $(this).text() to replace th text

I'm trying append a two digit year to a column header that is autogenerated for me. It seems like a simple problem. I have this table
<table border="1" id="Datatable1">
<tr>
<th>Jan-</th>
<th>Feb-</th>
</tr>
<tr>
<td>January's data</td>
<td>February's data</td>
</tr>
</table>
and this jquery
$(document).ready(
function () {
var TwoDigitYear = '14';
$('#DataTable1 th').each(function () {
var curtext = $(this).text();
if (curtext != "") {
var newtext = curtext + TwoDigitYear;
$(this).text(newtext);
}
});
}
);
For some reason, I can see the value changed if I put a console.log in the code, but the web page doesn't change.
Here's a jsfiddle: http://jsfiddle.net/PasadenaJacket/Ztnvr/#base
Instead of DataTable1 you need to do Datatable1 then it should work.
See UPDATED FIDDLE HERE

How to load the customers data to a table with border in javascript [duplicate]

This question already has answers here:
How to dynamically load the data from customers to a table in javascript within html [closed]
(3 answers)
Closed 9 years ago.
I need to load the data name, customerId, rentCost of customers into each cell of a table in a row. I am not sure which JavaScript code to use to accomplish that. I also need to style the table with css file with border = 1.
*I need to be able to add more data to the table using a html form later.
Thanks for your help in advance.
<html>
<head>
</head>
<script>
script>
var customers= [
{
name: "Kim Knudson",
customerID:"541",
rentCost:"$221",
},
{
name: "Henry Lewis",
customerID:"321",
rentCost:"$555",
}
];
</script>
<body>
<table>
<tr>
<td>Name</td>
<td>Customer ID</td>
<td>Rent</td>
</tr>
</table>
</body>
</html>
Use for loop to go through all records in customers:
for (var i = 0; i < customers.length; i++) {
console.log(customers[i]['name']);
}
With this it's up to you, how you will display them in table (see insertRow() method, it should be what you want).
check JSFiddle for working example. change your html like this:
<div id = "myDiv">
<table>
<tr>
<td>Name</td>
<td>Customer ID</td>
<td>Rent</td>
</tr>
</table>
</div>
change your javascript like this and put it to run on load. also this will add border t your table.
window.onload=function() {
var customers= [
{
name: "Kim Knudson",
customerID:"541",
rentCost:"$221",
},
{
name: "Henry Lewis",
customerID:"321",
rentCost:"$555",
}
];
var tableData = "<table style='border: 1px solid black;'><tr><td>Name</td><td>Customer ID</td><td>Rent</td></tr>";
for(i=0;i<customers.length;i++)
{
tableData += "<tr><td>" + customers[i].name + "</td><td>" + customers[i].customerID + "</td><td>" + customers[i].rentCost + "</td></tr>"
}
document.getElementById('myDiv').innerHTML = tableData + "</table>";
};
and your html table is recreated with the data in your json object.
you can use JavaScript insertRow and insertCell DOM functions for tables:
var customers = [{
name: "Kim Knudson",
customerID: "541",
rentCost: "$221"
}, {
name: "Henry Lewis",
customerID: "321",
rentCost: "$555"
}];
var tbl = document.querySelector("body>table");
for (var i = 0; i < customers.length; i++) {
var customer = customers[i];
var row = tbl.insertRow(i + 1);
var nameCell = row.insertCell(0);
nameCell.innerText = customer.name;
var idCell = row.insertCell(1);
idCell.innerText = customer.customerID;
var rentCell = row.insertCell(2);
rentCell.innerText = customer.rentCost;
}
Hi I recommend to use jQuery for this, you can use the following code as a guideline:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<style>
#table tr td {
border: 1px solid #000;
}
</style>
<script>
var customers= [
{
name: "Kim Knudson",
customerID:"541",
rentCost:"$221",
},
{
name: "Henry Lewis",
customerID:"321",
rentCost:"$555",
}
];
// this function will executed after the dom is loaded
$( document ).ready(function() {
// loop over each element in the customers array
$.each( customers, function(key, value ) {
// append the new row to the table
$('#table tr:last').after('<tr><td>' + value.name + '</td><td>' + value.customerID + '</td><td>' + value.rentCost + '</td></tr>');
});
});
</script>
</head>
<body>
<table id="table">
<tr>
<td>Name</td>
<td>Customer ID</td>
<td>Rent</td>
</tr>
</table>
</body>
</html>
Some things I also recommend:
I added the CSS style on the head for simplicity but you should move it to a css file (same thing with the javascript code)
Inside the "each" loop I adding the "
Hope that helps.

Show/hide rows based on class in HTML

Imagine I have a table of data in HTML and each of the rows have, say, one of three possible classes: RowA, RowB, and RowC; which represent the information in the rows. (For example, Small, Medium, and Large cars).
Above the table, I have 3 checkboxes: "Show Small Cars", "Show Medium Cars", "Show Large Cars".
If the user deselects "Show Small Cars", then the rows containing small cars should disappear.
This is how I would do it:
function showHideRows(classToShowOrHide, checkBoxSender)
{
var tableObj = document.getElementById("myDataTable");
for (i = 0; i < tableObj.childNodes.length; i++)
if (tableObj.childNodes[i].className == classToShowOrHide)
tableObj.childNodes[i].style.display = checkBoxSender.checked ? "visible" : "none";
}
Is there a better way? For example, can I modify the css class using javascript to include/exclude a display: none?
I'm not using jQuery.
If you define your markup/styles as this:
<table class="showSmallCars showMediumCars">
<tr class="smallCar">...<tr>
<tr class="mediumCar">...<tr>
</table>
CSS:
table tr { display:none; }
table.showSmallCars tr.smallCar { display:table-row; }
table.showMediumCars tr.mediumCar { display:table-row; }
then it is enough for you to modify class attribute on table to present records of groups you need:
Thus <table class="showSmallCars showMediumCars"> will show smalls an mediums
and <table class="showSmallCars showMediumCars showLargeCars"> will show all of them.
And no need to scan all rows in script.
jQuery is a cleaner way to do it; go to http://www.jquery.com and follow the instructions there to start using it, then your function becaomse
function showHideRows(classToShowOrHide, checkBoxSender)
{
$('.' + classToShowOrHide, '#myDataTable').each(function(){
$(this).css('display', ((checkBoxSender.checked) ? 'visible' : 'none'));
});
}
If you want to do it in vanilla JS, something like this should be about right. Probably a gremlin in the following code somewhere, I don't do much vanilla JS any more :) jQuery is that good.
window.onload=function(){
if (document.getElementsByClassName == undefined) {
document.getElementsByClassName = function(className)
{
var hasClassName = new RegExp("(?:^|\\s)" + className + "(?:$|\\s)");
var allElements = document.getElementsByTagName("*");
var results = [];
var element;
for (var i = 0; (element = allElements[i]) != null; i++) {
var elementClass = element.className;
if (elementClass && elementClass.indexOf(className) != -1 && hasClassName.test(elementClass))
results.push(element);
}
return results;
}
}
}
function showHideRows(classToShowOrHide, checkBoxSender)
{
for (i = 0; i < document.getElementsByClassName(classToShowOrHide); i++)
document.getElementsByClassName(classToShowOrHide)[i].style.display = checkBoxSender.checked ? "visible" : "none";
}
Really, the basics of showing and hiding rows can be done very cleanly in CSS. Javascript is only required to tell the surrounding table what type it should show - and that's just a matter of setting a class name.
If this is your HTML:
<table>
<thead>
<tr>
<td>Name</td>
<td>Type</td>
<td>Price</td>
</tr>
<tbody>
<tr class="rowA">
<td>Falcon</td>
<td>Large</td>
<td>$160.00</td>
</tr>
<tr class="rowA">
<td>Commodore</td>
<td>Large</td>
<td>$160.00</td>
</tr>
<tr class="rowB">
<td>Camry</td>
<td>Medium</td>
<td>$110.00</td>
</tr>
<tr class="rowB">
<td>Lancer</td>
<td>Medium</td>
<td>$105.00</td>
</tr>
<tr class="rowC">
<td>Prius</td>
<td>Small</td>
<td>$75.00</td>
</tr>
<tr class="rowC">
<td>Civic</td>
<td>Small</td>
<td>$80.00</td>
</tr>
</tbody>
</thead>
</table>
Use this CSS:
/* The rows to show */
table.showTypeA .rowA,
table.showTypeB .rowB,
table.showTypeC .rowC {
display: table-row;
}
/* Then, hide the other types */
table.showTypeA .rowB,
table.showTypeA .rowC,
table.showTypeB .rowA,
table.showTypeB .rowC,
table.showTypeC .rowA,
table.showTypeC .rowB {
display: none;
}
All you need to do with javascript is set a class on the table of 'showTypeA', 'showTypeB', 'showTypeC', and the browser will take care of the rest.
I know you asked for JavaScript, but you could do it failry easy with jQuery.
Like:
http://jsfiddle.net/XJRVt/17/
You would proberbly also need to do a check on page load :)

How to append a row in table using javascript

I want to append a new row in my table using Javascript but the new row should be like my previous rows.
I am using CSS to format my rows.
If you are using jQuery it will be something like this:
$(document).ready(function() {
$("table tr:last").clone().appendTo("table");
})
Replacing table with the id or class of your table (unless you only plan to have one table).
Using good old Node.cloneNode(deep) along with HTMLTableElement.rows:
HTML:
<table id="foo">
<tbody id="bar">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
</tbody>
</table>
JS:
var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var rows = foo.rows;
var lastRow = rows[rows.length-1];
var newRow = cloneRow(lastRow, true, bar);
function cloneRow(row, append, parent)
{
var newRow = row.cloneNode(true);
if(append)
{
if(parent)
{
parent.appendChild(newRow);
}
}
return newRow;
}
For comparison's sake, here's my code juxtaposed against the jQuery answer: http://jsperf.com/dom-methods-vs-jquery-with-tables
Let's say that your row has a css style of .row
So you could just use DOM methods to create a new tr, add the class="row" then add the appropriate amount of td
Here is a solution that avoids the use of the cloneNode method, and that do not copy the content, data or events of the previous last row, just its CSS attributes and class names.
The new row will have the same number of cell as the previous last row.
var lastRow = myTable.rows[myTable.rows.length-1];
var newRow = myTable.insertRow();
newRow.className = lastRow.className;
newRow.style.cssText = lastRow.style.cssText;
for (var i = 0; i < lastRow.cells.length; i++) {
var newCell = newRow.insertCell(i);
newCell.className = lastRow.cells[i].className;
newCell.style.cssText = lastRow.cells[i].style.cssText;
}

Categories

Resources