Count unique values in html table - javascript

I'd like to count unique values in a html table.(RGB color)
I'm using a third-party website, which using PHP to write values in the table. I don't have access to the PHP script.
The PHP writes here "{colorcode}" a rgb-to-hex which I defined. I've 5 hex values:
fire: #FF8C00
medical help: #FD0202
hazardous materials: #19070B
other: #4876FF
technical assistance: #0000FF
My goal is, that I can count each color individually and write it in an other table.
Here's my website which shows the table: https://www.feuerwehr-forstern.de/einsaetze/
Table which I want to count.
<table>
<tr style="font-size:16px; background-color:#670200; color:#FFFFFF;">
<th><b>Nr.</b></th>
<th><b>Missionstart</b></th>
<th><b>Title</b></th>
<th><b>Kind of mission</b></th>
<th><b>Place</b></th>
<th></th>
</tr>{liststart}
<tr>
<td style="color:#FFFFFF;" bgcolor={colorcode}><b>{missionnr}</b></td>
<td>{startdate} {starttime}</td>
<td>{missiontitle}</td>
<td>{kind of mission}</td>
<td>{missionplace}</td>
<td><u>{linkreport}</u></td>
</tr>{listend}
</table>
Other table, where I want to write the result of counting after " : ".
<table>
<tr style="font-size:16px; color:#FFFFFF;">
<th style="background-color:#FF8C00;"><b>fire:</b></th>
<th style="background-color:#FD0202;"><b>medical help:</b></th>
<th style="background-color:#19070B;"><b>hazardous materials:</b></th>
<th style="background-color:#4876FF;"><b>other:</b></th>
<th style="background-color:#0000FF;"><b>technical assistance:</b></th>
</tr>
</table>

you can try this : var blue_count = $('[bgcolor=#0000FF]').length to get the count of the td elements that have the bgcolor attribute with the value of #0000FF . then you can append the count value where ever you want.
but this is just the idea for you to solve it... not the best way...
good luck

Here's the new Code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var orange_count = $('[bgcolor=#ff8c00]').size()
$(".important1").text("Brand: " + orange_count);
});
</script>
<script type="text/javascript">
$(function() {
var red_count = $('[bgcolor=#fd0202]').size()
$(".important2").text("First Responder: " + red_count);
});
</script>
<script type="text/javascript">
$(function() {
var black_count = $('[bgcolor=#19070b]').size()
$(".important3").text("Gefahrstoffe: " + black_count);
});
</script>
<script type="text/javascript">
$(function() {
var royalblue_count = $('[bgcolor=#4876ff]').size()
$(".important4").text("Sonstige: " + royalblue_count);
});
</script>
<script type="text/javascript">
$(function() {
var blue_count = $('[bgcolor=#0000FF]').size()
$(".important5").text("Technische Hilfeleistung: " + blue_count);
});
</script>
<table>
<tr style="font-size: 16px; color: #ffffff;">
<th style="background-color: #ff8c00;"><b class="important1">Brand</b></th>
<th style="background-color: #fd0202;"><b class="important2">First Responder</b></th>
<th style="background-color: #19070b;"><b class="important3">Gefahrstoffe</b></th>
<th style="background-color: #4876ff;"><b class="important4">Sonstige</b></th>
<th style="background-color: #0000ff;"><b class="important5">Technische Hilfeleistung</b></th>
</tr>
</table>

I've looked at your code and the link you provided in your question at top,
and in the link the color codes were all Uppercase like this : bgcolor="#4876FF"
so you can't get them with lowercase selectors like this: $('[bgcolor=#4876ff]').size()
you should fix that at first. and then, in every page you only need to check for the document.ready event once. so one of these will do the work :
$(function() {
});
just write your code in one of these blocks.
wish you luck...

Related

Split one big table into multiple tables based on content of acolumn in each row

I looked at previous similar questions and only found one answer with the following code splitting the data into 2 tables:
// ==UserScript==
// #name TABLE SPLITTER
// #namespace http://www.w3schools.com/
// #description DESCRIPTION!!!
// #include http://www.w3schools.com/css/css_table.asp
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// #require https://raw.github.com/tomgrohl/jQuery-plugins/master/jcookie/script/jquery.jcookie.min.js
// #version 1
// ==/UserScript==
$(function(){
// YOUR JAVASCRIPT CODE HERE
// YOU HAVE JQUERY INCLUDED
setTimeout(function(){
var mainTable = $("table");
var splitBy = 3;
var rows = mainTable.find ( "tr" ).slice( splitBy );
var secondTable = $("<table id='secondTable' style='background:pink;'><tbody></tbody></table>").insertAfter("table");
secondTable.find("tbody").append(rows);
console.log(secondTable);
mainTable.find ( "tr" ).slice( splitBy ).remove();
}, 3000);
});
I am looking for something like this that will split the information to tables base on the amount of different options i have.
ultimately i would like something like:
Goal
Or even better remove the type from the output and have it show before each of the new tables like this: option 2
Not sure if that even possible and would love some help.
This is not the optimal solution, you can get the idea and improve it.
Read JS comments.
var dynamicData = $('#dynamicData'); // To identify the parent that we will append data to.
$(document).ready(function(){
$('.types').each(function(){ // loop on each type and check if that type not appended inside '#dynamicData' as 'h5', if no,t append it and append a table related to it
var name = $.trim($(this).text());
var check = $('h5#i_' + name , dynamicData).length;
if (check === 0){
$(dynamicData).append('<h5 id="i_' + name + '">' + name + '</h5>');
$(dynamicData).append('<table id="t_' + name + '" class="table table-hover table-striped table-bordered"></table>');
$('table#t_' + name).append('<thead>'+
'<tr>'+
'<th>Product</th>'+
'<th>Price</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'</tbody>');
}
});
$('#allContent > tr').each(function(){ // loop on each row in '#allContent' and read '.types' class, then clone this row and remove the type then append it inside the target table using id
var name = $.trim($('.types',this).text());
$(this).clone().find('.types').remove().end().appendTo('table#t_' + name + ' > tbody');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<h4 class="text-center text-danger">Before:</h4>
<table class="table table-hover table-striped table-bordered">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Type</th>
</tr>
</thead>
<tbody id="allContent">
<tr>
<td>TV</td>
<td>250$</td>
<td class="types">Product</td>
</tr>
<tr>
<td>Channel</td>
<td>1$</td>
<td class="types">Service</td>
</tr>
<tr>
<td>Channel</td>
<td>1$</td>
<td class="types">Service</td>
</tr>
<tr>
<td>DVD</td>
<td>14$</td>
<td class="types">Product</td>
</tr>
<tr>
<td>Support</td>
<td>15$</td>
<td class="types">Team</td>
</tr>
</tbody>
</table>
<h4 class="text-center text-danger">After:</h4>
<div id="dynamicData"></div>
My first thought is make a unique list of the types. Then loop over that list, cloning the original table for each. Then loop through the cloned table and remove everything that you don't want there. Definitely not the most efficient, but it's simple and it works.
let types = [... new Set($('table.original tr td:last-of-type')
.get().map(type => type.textContent))];
//create a container for the cloned tables
$('table.original').after(`<h4>After:</h4><div class="cloned-tables"></div>`)
//loop over types, clone tables, modify accordingly
$.each(types, function(index, type) {
$(`<p class="type">${type}</p>${$('table.original')[0].outerHTML}`)
.appendTo('.cloned-tables')
.find('tr td:last-of-type').each(function() {
if (this.textContent !== type) { this.parentElement.remove(); }
this.remove();
});
});
//remove all type header cells
$(`.cloned-tables table th:last-of-type`).remove();
h4{color: red;}
.type{color: blue;}
<h4>Before:</h4>
<table class="original">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
<th>Type</th>
</tr>
</thead>
<tbody>
<tr>
<td>TV</td>
<td>$250</td>
<td>Product</td>
</tr>
<tr>
<td>Channel</td>
<td>$1</td>
<td>Service</td>
</tr>
<tr>
<td>Channel</td>
<td>$1</td>
<td>Service</td>
</tr>
<tr>
<td>DVD</td>
<td>$14</td>
<td>Product</td>
</tr>
<tr>
<td>Support</td>
<td>$15</td>
<td>Team</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Another thought on using greasemonkey, make sure that the table exist and is populated before you try and do anything with it. Greasemonkey is in a different scope than the original code, so document.ready() is inaccurate. Sometimes things load very asychronously, which will make valid code seem broken. I tend to do something like this:
let loading = setInterval(function() {
if ($('table.original').length) {
clearInterval(loading);
//greasmonkey code here
}
}, 1000);

How to get td id val of table after change in php codeigniter

The problem is whenever im drag & drop and replace td first place to another
i have receiving that the replacement id in jquery.
but the problem is how i can get that replacement td id value in php codeigniter.
i just need if any of td of table has been exchange then i should knw which one is is replaced and get that id into my controller class of php codeigniter.
thanks in advance.
$(document).ready(function () {
$('tbody').addClass("DragMe");
$('.DragMe').sortable({
disabled: false,
axis: 'y',
items: "> tr:not(:first)",
forceHelperSize: true,
update: function (event, ui) {
var Newpos = ui.item.index();
var RefID = $('tr').find('td:first').html();
//alert("Position " + Newpos + "..... RefID: " + RefID);
$("#GridView1 tr:has(td)").each(function () {
var RefID = $(this).find("td:eq(0)").html();
var NewPosition = $("tr").index(this);
alert(RefID + " " + NewPosition);
$("#getpos").val(NewPosition);
$("#ref").val(RefID);
});
}
}).disableSelection();
});
<style type="text/css">
.DragMe:Hover {
cursor: move;
}
</style>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- here is my view form -->
<form method="post" action="<?php echo base_url(); ?>index.php/dragcon/drag/dragfun">
<table class="EU_DataTable" cellspacing="0" rules="all" border="1" id="GridView1" style="border-collapse:collapse;">
<tbody>
<tr>
<th scope="col">Ref ID</th>
<th scope="col">Issue relates to</th>
</tr>
<tr class="ui-sortable-handle">
<td id="ref">9392</td>
<td id="getpos">CRM</td>
</tr>
<tr class="ui-sortable-handle">
<td id="ref">9394</td>
<td id="getpos">CRM</td>
</tr>
<tr class="ui-sortable-handle">
<td id="ref">9308</td>
<td id="getpos">eMail</td>
</tr>
<tr class="ui-sortable-handle">
<td id="ref">9342</td>
<td id="getpos">Other</td>
</tr>
<tr class="ui-sortable-handle">
<td id="ref">9365</td>
<td id="getpos">CRM</td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
As you seen where i can drag and drop td to td of table and also receiving in alert but i just want to get each of td value after change in the controller of php codeigniter
thanks in advance.
You need to look at the difference between client side and server side code. The action you perform in Javascript can not be passed to the original Codeigniter script as that script was already executed.
In order to call back Codeigniter you want to use Ajax and in particular the Ajax functions of jQuery since you seem to be using that.
It's a complex topic and you should study it in details to be sure you grasp the difference between server-side and client-side, when they happen and how they interact. If you want a more quick & dirty approach, this article from IBM seems perfect as it talks about Ajax, jQuery and CodeIgniter.

jQuery Collapser hide or show content inside the DIV

My question is related with "jQuery – Collapser plugin" ( http://www.aakashweb.com/jquery-plugins/collapser/ ):-
I am using the following script to hide or show content inside the DIV with CLASS name 'shrink'. It works fine.
<script type="text/javascript">
$(document).ready(function() {
$('.shrink').collapser({
mode: 'words',
truncate: 80,
ellipsis: ' ... '
});
});
</script>
But, In the BODY I use a javascript to print some content inside DIV with a table to hide or show content inside <tr><td><div class="shrink"></div></td></tr>. Now, hide or show content does not works. (sample script is given below, Note: There is no line break. It is just for explanation only.)
<script type="text/javascript">
var dataTable = document.getElementById('Result');
var content = "<table class='tablesorter'>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td><div class='shrink'>Some long content....</div></td>
</tr>
</tbody>
</table>";
dataTable.innerHTML = content;
</script>
<div id="Result"></div>
Also, I tried with a simple statement as below. It does not works.
var content = "<div class='shrink'>Some long content....</div>";
you have to be careful with line breaks in javascript strings. note how syntax highlighting stops on the second line. you have to either escape them or concat them.
escaping..
var content = "<table class='tablesorter'>\
<thead>\
<tr>\
....
</table>";
Note that if you escape thelinebreaks, there can't be any trailing spaces after the \.
concatting..
var content = "<table class='tablesorter'>"+
"<thead>"+
"<tr>"+
....
"</table>";
<script type="text/javascript">
function shrink() {
$('.shrink').collapser({
mode: 'words',
truncate: 80,
ellipsis: ' ... '
});
}
function display () {
var dataTable = document.getElementById('Result');
var content = "<table class='tablesorter'>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td><div class='shrink'>Some long content....</div></td>
</tr>
</tbody>
</table>";
dataTable.innerHTML = content;
}
setTimeout(function(){ display(); shrink(); }, 1000);
</script>
<div id="Result"></div>

Print something from JavaScript to a table in HTML/PHP page

I want to print out the result of a JavaScript function to a table in my HTML/PHP page. I tried using " document.write(player1Name);"
but it didn't work.
So when i input something into this text field
I want that result to be printed in this table
This is the code in my Hangman Home Page :
<form id="Player1" class="Player1">
<input type="text" id="playerOneName"/>
</form>
<form id="Player2" class="Player2">
<input type="text" id="playerTwoName"/>
</form>
<button id="Enter" class="Enter" type="button" onclick="navigateToDifficultyForMultiPlayer()">
<a>Enter</a>
</button>
This is the code in my Multi-player page for the table:
<TABLE BORDER="5" WIDTH="20%" CELLPADDING="5" CELLSPACING="2" id="Score-Board">
<TR>
<caption id="table-title">Score Board</caption>
</TH>
</TR>
<TR ALIGN="CENTER">
<TH colspan="2"> <script> document.write(player1Name);</script> </TH>
<TH colspan="2"><script> var player2Name </script></TH>
</TR>
<TR ALIGN="CENTER">
<TH colspan="2">score</TH>
<TH colspan="2">score</TH>
</TR>
</TABLE>
This is my JavaScript code I created to do what I want it to do (I think I have done it right):
function navigateToDifficultyForMultiPlayer() {
//set player names in session
setPlayerNames();
//navigate to DifficultyForMultiPlayer page
location.href = "DifficultyForMultiPlayer.html";
}
function setPlayerNames() {
var firstPlayerName = document.getElementById("playerOneName").value;
var secondPlayerName = document.getElementById("playerTwoName").value;
console.log(firstPlayerName + " " + secondPlayerName);
sessionStorage.setItem("Player1Name", firstPlayerName);
sessionStorage.setItem("Player2Name", secondPlayerName);
}
function getPlayerNames(){
player1Name = sessionStorage.getItem("Player1Name");
player2Name = sessionStorage.getItem("Player2Name");
console.log(player1Name + " " + player2Name);
}
And this is the JavaScript that's being called globally :
var player1Name;
var player2Name;
I hope everyone can understand what I am trying to ask. Please don't hesitate to tell me if there is something wrong with my question. I tried my best to ask the question properly, FYI English isn't my first language
What you want to do is in this html:
<TR ALIGN="CENTER">
<TH colspan="2"> <script> document.write(player1Name);</script> </TH>
<TH colspan="2"><script> var player2Name </script></TH>
</TR>
add an ID to your th elements:
<TH colspan="2" id="player1"> // and remove the script
Then, in your javascript, possibly in your getPlayerNames function:
document.getElementById("player1").text(player1Name);
And then do the same for player2.
You can give your <th> tags for the players ids like player1 and player2. Then at the end of your <body> for the Multi-player page you can put a <script> tag that does something like:
<script>
(function() {
document.getElementById("player1").innerHTML = player1Name;
document.getElementById("player2").innerHTML = player2Name;
})();
</script>
The document.getElementById grabs the DOM element that you want and then .innerHTML changes what is within that tag. Putting this right before end of the body tag will make sure the html elements are loaded first before trying to access them.

How to get html <td> values using javascript?

Im very new to html and javascript.
I want to get the content of element whenever the user click on a table row using javascript.
test.html
<html>
<head>
<script text="text/javascript">
function dispTblContents() {
var pName = document.getElementById("pName").value;
var pAddress = document.getElementById("pAddress").value;
var pEmail = document.getElementById("pEmail").value;
alert(pName + " " + pAddress + " " + pEmail);
}
</script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
<th>Address </th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr onclick="dispTblContents();" >
<td id="pName">Ricardo Lucero</td>
<td id="pAddress">Mexico City, Mexico</td>
<td id="pEmail">rlucero#test.com</td>
</tr>
</tbody>
</table>
</body>
</html>
Whenever I click the row it displays undefined undefined undefined. I know my code is wrong but I really don't how to fix this. Can somebody please help me. Im very new to this thing. Thanks in advance.
You need innerHTML not value here, value is used for form elements.
<script text="text/javascript">
function dispTblContents() {
var pName = document.getElementById("pName").innerHTML;
var pAddress = document.getElementById("pAddress").innerHTML;
var pEmail = document.getElementById("pEmail").innerHTML;
alert(pName + " " + pAddress + " " + pEmail);
}
</script>
You might also want to look into jQuery if you're not using it yet, it makes selecting and manipulating HTML with Javascript a lot easier.
Try change value to innerHTML
Try to change value to innerHTML or innerText
document.forms[0].getElementsByTagId("pName").innerText;
A <td> tag doesn't have a value.
Use document.getElementById("pName").innerHTML instead.
I searched a lot for it too. Finally I get to see teaches's solution. This is an example that works:
...........
<head>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<% ArrayList<Student> students = StudentsManager.getInstance().getStudents(); %>
<body>
Choose a student <br>
<table>
<tr>
<td>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Student st : students){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=<%=st.getStudentId()%>');">
<td name = "title" align = "center"><%= st.getStudentId() %></td>
</tr>
<%}%>
...............
students is an ArrayList that contains objects of type Student(studentId, name).
The table displays all the students. Befor you click on a cell, click view source. You'll see:
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundC.jsp?studentId=1');">
<td name = "title" align = "center">1</td>
</tr>
Well in my case was "1". I didn't make the destination page yet.

Categories