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

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.

Related

Change javascript variable with html button

I am implementing the IGV genome browser in a website.
I would like to link a table with chromosome positions to the genome browser, so when a user clicks to one position, the genome browser changes to that position automatically.
By now, I have the genome browser code in a separate javascript file, which uses the value of the button.
// Construct genome browser
document.addEventListener("DOMContentLoaded", function () {
// Obtain position
var position = $('#ins').val();
// Use the position
var options = {locus: position, ...};
var igvDiv = document.getElementById("igvDiv");
igv.createBrowser(igvDiv, options)
.then(function (browser) {
console.log("Created IGV browser");
})
};
And the table in html with buttons.
<table class='results-table'>
<tr>
<th class='text text--bold'>Chromosome</th>
<th class='text text--bold'>Start</th>
<th class='text text--bold'>End</th>
<th class='text text--bold'>Genome Browser</th>
</tr>
<tr>
<td class='text'>chr1</td>
<td class='text'>0</td>
<td class='text'>100</td>
<td><button class='editbtn' value='chr1:0-100' id='ins1'>chr1:0-100</button></td>
</tr>
<tr>
<td class='text'>chr2</td>
<td class='text'>200</td>
<td class='text'>400</td>
<td><button class='editbtn' value='chr2:200-400' id='ins2'>chr2:200-400</button></td>
</tr>
</table>
With this, the browser gets the first position but it does not change when I click the button.
I think I need some kind of onClick() action but I can't figure out how to change a javascript script.
Any help would be appreciated.
Thank you!
JĂșlia
edit:
I added more javascript code as I think that I was not able to illustrate my question properly. And also modified the ids from buttons, to make them different.
The question is how to use different ids in javascript depending on the button that was clicked.
You can change some things. I remove the id from your buttons because you will already have the context with the passing event. And instead of a value in the button, I would recommend you to use a data attribute. data-value for example.
function check(e) {
console.log(e.getAttribute('data-value'))
}
<button class='editbtn' onclick="check(this)" data-value='chr2:200-400' >chr2:200-400</button>
<button class='editbtn' onclick="check(this)" data-value='chr1:0-100' >chr1:0-100</button>
You can access the ID and value in a click event:
// Construct genome browser
document.querySelector('table.results-table').addEventListener('click', function ({ target }) {
if (!target.id) return;
const id = target.id;
const position = target.value;
console.log(id);
console.log(position);
});
<table class='results-table'>
<tr>
<th class='text text--bold'>Chromosome</th>
<th class='text text--bold'>Start</th>
<th class='text text--bold'>End</th>
<th class='text text--bold'>Genome Browser</th>
</tr>
<tr>
<td class='text'>chr1</td>
<td class='text'>0</td>
<td class='text'>100</td>
<td><button class='editbtn' value='chr1:0-100' id='ins1'>chr1:0-100</button></td>
</tr>
<tr>
<td class='text'>chr2</td>
<td class='text'>200</td>
<td class='text'>400</td>
<td><button class='editbtn' value='chr2:200-400' id='ins2'>chr2:200-400</button></td>
</tr>
</table>

Count unique values in html table

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...

how to get the id when a certain button is clicked using jquery

How can I get the id of tbody's input when #moveToAnTable is clicked using jQuery? Thanks.
<table id="yearSectionAdd2Table">
<thead>
<tr id="columnHeader">
<th>
<div>
<input id="moveToAnTable" type="button" value="<<">
</div>
</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<center>
<input id="moveToAnTableOne" type="button" value="<<">
</center>
</td>
</tr>
</tbody>
</table>
Use jQuery.closest to get the table of the button.
After that search for the input.
jQuery.attr will return the attribute of the first element in the match:
$("#moveToAnTable").click(function(){
var id = $(this).closest("table").find("tbody input").attr("id");
alert(id);
});
See the fiddle:
http://jsfiddle.net/URGVp/
You can also write it like this with the on method, and test out your results in a console window if that better suits you, rather than constant pop-ups.
$('#moveToAnTable').on("click",function(){
var mvalue = $(this).closest('table').find('tbody input').attr('id');
console.log('my value is: ' + mvalue);
});

getElemntById query for JavaScript

can you please tell me why this wouldnt work? been stuck at it all day.
I just wanna copy whatever is enetered in the first field, convert it to a variable and project it to the last field.
Thank you
ps: needless to say i only copied the relevant bits of the code...
<th bgcolor="#eeeee" width=12.5%>Monday</th>
<th bgcolor="#eeeee" width=12.5%><input id="test" value="09:15" size=15></td></th>
<th bgcolor="#eeeee" width=12.5%><input type=time id="Monday_Breakfast_LastSeating" value="11:45" size=15></td></th>
</form>
</table>
<form id="form2" id=other method=POST>
<tr>
<td bgcolor="#aaeeaa"align=center><button onclick="myFunction()">Calculate</button></td>
</tr>
</form>
<table width=40% border=0>
<th bgcolor="#eeaaaa" align=center width=33%>Goal</th>
</table>
<form id=result method=POST>
<table width=40% border=0>
<th style="border:black;" bgcolor="#eeaaaa" align=center><em></em> <p id="calculation2" size=15>N/A</p></th>
<th bgcolor="#eeaaaa" align=center><em></em> <p id="calculation3" size=15>N/A</p></th>
<th bgcolor="#eeaaaa" align=center><p id="calc" size=15>N/A</p></th>
</table>
</form>
<script type="text/javascript">
function myFunction() {
var test = getElementById("test").value;
document.getElementById("calc").innerHTML = test;
}
</script>
You forgot the document. before the first getElementById
function myFunction() {
var test = document.getElementById("test").value; // you forgot the document. here..
document.getElementById("calc").innerHTML = test;
}
Additionally, there is not size attribute for p elements. (perhaps you wanted to use input elements.. But for those you should use the value property instead of the innerHTML to set them..)
Change var test = getElementById("test").value; to var test = document.getElementById("test").value;
It should be:
document.getElementById('calc').innerHTML = document.getElementById('test').value;
getElementById() by itself is not a valid function

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