getElemntById query for JavaScript - 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

Related

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 a number value from an input field?

I have some issues with calculating some stuff with JS and getting the right values out of the input fields (number). When I use this code it doesn't show anything. So what is wrong with my JS? Do I need to include a jQuery file?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
</head>
<body>
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td><input type="number" name="TotalProductionTime" placeholder=""> hours</td>
</tr>
<tr>
<td>Breaks</td>
<td><input type="number" name="Breaks" placeholder=""> minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td><input type="number" name="Malfunctions" placeholder=""> minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td><p id="test"></p></td>
</tr>
</table>
<input type="button" onclick="Calculate()" name="Calculate" value="calculate">
<script>
function Calculate()
{
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
</script>
</body>
</html>
You had some mistakes in your HTML, but here is a working JSFiddle: Fiddle
You you are trying to get elements by their ID, but you don't give them an ID you give them a Name. Also, stop using inline JavaScript calls; it is bad practice.
function Calculate() {
var TotalProductionTime = document.getElementById("TotalProductionTime").value;
var TotalProductionTimeInMinutes = TotalProductionTime * 60;
var Breaks = document.getElementById("Breaks").value;
var Malfunctions = document.getElementById("Malfunctions").value;
var TheoreticalProductionTime = TotalProductionTimeInMinutes - Breaks - Malfunctions;
document.getElementById("test").innerHTML = TheoreticalProductionTime;
}
<form id="frm1" action="Calculate.html">
<table width="350px" border="1px">
<tr>
<th colspan="2">Availability</th>
</tr>
<tr>
<td>Total Production Time</td>
<td>
<input type="number" id="TotalProductionTime" placeholder="">hours</td>
</tr>
<tr>
<td>Breaks</td>
<td>
<input type="number" id="Breaks" placeholder="">minutes</td>
</tr>
<tr>
<td>Malfunctions</td>
<td>
<input type="number" id="Malfunctions" placeholder="">minutes</td>
</tr>
<tr>
<td>Theoretical production time:</td>
<td>
<p id="test"></p>
</td>
</tr>
</table>
<input type="button" onclick="Calculate()" value="calculate">
</form>
Every id must be converted to integer. Example
var Malfunctions = parseInt(document.getElementById("Malfunctions").value);
then your ready to go
With HTMLInputElement you can use property .valueAsNumber which returns a numeric property if possible:
const str = document.querySelector("input").value;
const num = document.querySelector("input").valueAsNumber;
console.log(typeof str, str, str + 2);
console.log(typeof num, num, num + 2);
<input type="number" value="40" disabled />
You've got two problems here. One obvious is that you try to get a reference to the form inputs by id, but didn't give them any (you gave them a name). To fix, either change the name attribute to an id, or use the form-specific way to reference them, e.g.:
var TotalProductionTime = document.forms.frm1.TotalProductionTime
Second problem is more vicious and has to do with the scope of execution of what you put in onclick attributes. You see, your button is named "Calculate" just like your function, and in the context of the onclick attribute, its parent form is used to resolve identifiers before the global scope. So instead of calling the function named Calculate, you're trying to call the button itself. Fix that by giving them different names, referencing window.Calculate explicitly, or much better, define your event handler in JavaScript instead of using the HTML attribute:
document.forms.frm1.Calculate.onclick=Calculate

Clone full table and submit as form value

How to correctly copy/clone a html table with javascript and submit it to php, where it will be converted to PDF and XLS documents?
So far I have a html something like this:
<table class="planning-table">
<thead>
<tr>
<td>blah blah</td>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
</tr>
</tbody>
</table>
<form id="exportPDFform" method="post">
Eksport
<input id="table_data" type="hidden" name="table" value="" />
</form>
and jquery:
$("#exportPDF").on("click", function (){
var value = $('.planning-table').clone();
$("#table_data").val( escape( value ) );
$("#exportPDFform").submit();
return false;
});
Now, the cloning works, but, when put inside input field, it gives me:
[object-Object]
How do I correctly do this?
PS: the form gets changed/created dinamically when selecting different filters, so it would be much easier to use the final product then to recreate it on PHP side.
Presumably escape() takes a string whereas you are providing a jQuery object. When you try and cast an object to a string javascript gives you "[object Object]". Instead, you need to retrieve the HTML value of the table, like this:
var value = $('.planning-table').clone().wrap('<div />').parent().html();
I do not think you want to use the Clone() function, instead I think you want to get the HTML content of an element, but using the .html() function on an element above the table.
<div id="table-container">
<table class="planning-table">
<thead>
<tr>
<td>blah blah</td>
</tr>
</thead>
<tbody>
<tr>
<td>blah blah</td>
</tr>
</tbody>
</table>
</div>
<form id="exportPDFform" method="post">
Eksport
<input id="table_data" type="hidden" name="table" value="" />
</form>
and
$("#exportPDF").on("click", function (){
var value = $('#table-container').html();
$("#table_data").val( escape( value ) );
$("#exportPDFform").submit();
return false;
});

How do you rearange text in elements using javascript and jquery

I am trying to select all the elements with class "name" and when I click on one radio button it flips the last and first name around, so: Hanks, Tom || Tom, Hanks. Here is what I have so far:
HTML:
<h1>Address Book</h1>
<p>Show Names as:</p>
<input name="lastfirst" value="last" type="radio">First, Last
<input name="firstfirst" value="first" type="radio">Last, First
<div>
<table <thead="">
<tbody>
<tr>
<th>ID</th>
<th>Name</th>
<th>Email</th>
</tr>
</tbody>
<tbody>
<tr>
<td>9001</td>
<td class="name">Tom Hanks,</td>
<td>tomhanks#moviestars.com</td>
</tr>
<tr>
<td>9002</td>
<td class="name">Bruce Willis,</td>
<td>brucewillis#moviestars.com</td>
</tr>
<tr>
<td>9003</td>
<td class="name">Jim Carrey,</td>
<td>jimcarrey#moviestars.com</td>
</tr>
<tr>
<td>9004</td>
<td class="name">Tom Cruise,</td>
<td>tomcruise#moviestars.com</td>
</tr>
<script>
</script>
</tbody>
</table>
</div>
<meta charset="utf-8">
<title>Test</title>
<link rel="stylesheet" href="./webassets/style.css" media="screen" type="text/css">
<h1>Company Staff List</h1>
<div>
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>9001</td>
<td>Tom Hanks,</td>
</tr>
<tr>
<td>9002</td>
<td>Bruce Willis,</td>
</tr>
<tr>
<td>9003</td>
<td>Jim Carrey,</td>
</tr>
<tr>
<td>9004</td>
<td>Tom Cruise,</td>
</tr>
</tbody>
</table>
</div>
Here is my jquery. I used a filler of .hide() because other than selecting the elements I am not sure how to do this. Just some hints would help. I am not sure how to separate the first and last name. If I could figure out how to simply swap the first and last name into a variable I could definitely figure out the rest.
$(document).ready(function(){
$("input[name='lastfirst']").click(function(){
$(".name").hide();
});
$("input[name='firstfirst']").click(function(){
$(".name").hide();
});
});
DEMO
$(document).ready(function () {
$("input[name='change_last_first']:nth(0)").prop('checked', true)
$("input[name='change_last_first']").change(function () {
$(".name").text(function (_, old_txt) {
var new_txt = old_txt.split(' ').reverse();
return new_txt.toString().replace(',,', ' ') + ',';
});
});
});
HTML changed
<input name="change_last_first" value="last" type="radio">First, Last
<input name="change_last_first" value="first" type="radio">Last, First
References
.text()
.change()
.replace()
.split()
.toString()
.reverse()
Split it first using.
var splStr = input.split(/[ ,]+/);
now concatinate using input=splStr[1]+splStr[0];
you can separate the text using split function input.split(/[ ,]+/); along with a regular expression to separate each "word" within the input.
you could then assign each value to a new variable
ex:
var a = array[0], b = array[1]
From there you could concatenate the array values into any order you choose.

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);
});

Categories