Can't get the numeric value from HTML using parseInt or Number in my js function - javascript

So I'm trying to complete this simple html page for a friend's project, the goal is to get 2 user entries, minutes and seconds, that will be compared to the data already in the table and if the minutes and seconds entered are greater than one of the time in the table, it will be replaced by the entry.
I've never worked with js except to make some simple prompt or alert so I don't know what I'm supposed to do.
Here is the html, js and css :
function timeEntry() {
var min1 = Number(document.getElementById('firstTimeMin'));
var sec1 = Number(document.getElementById('firstTimeSec'));
var min2 = Number(document.getElementById('secondTimeMin'));
var sec2 = Number(document.getElementById('secondTimeSec'));
var min3 = Number(document.getElementById('thirdTimeMin'));
var sec3 = Number(document.getElementById('thirdTimeSec'));
var entryMin = Number(prompt('What is the time in minutes ?'));
var newTimeMin = entryMin;
var entrySec = Number(prompt('What is the time in seconds'));
var newTimeSec = entrySec;
for (var i = 0; i < 3; i++) {
if (entryMin > min1 && entrySec > sec1) {
document.getElementById('firstTimeMin').innerHTML = newTimeMin;
document.getElementById('firstTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min2 && entrySec > sec2) {
document.getElementById('secondTimeMin').innerHTML = newTimeMin;
document.getElementById('secondTimeSec').innerHTML = newTimeSec;
break;
} else if (entryMin > min3 && entrySec > sec3) {
document.getElementById('thirdTimeMin').innerHTML = newTimeMin;
document.getElementById('thirdTimeSec').innerHTML = newTimeSec;
break;
}
};
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
}
section {
width: 100%;
height: 100%;
}
table,
td {
width: 40%;
text-align: center;
border: 1px solid black;
border-collapse: collapse;
}
button {
cursor: pointer;
font-weight: 700;
}
<!DOCTYPE html>
<html>
<head>
<title>Table of best times</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script type="text/javascript" src="javascript/besttime.js"></script>
</head>
<body>
<section>
<table>
<tbody>
<caption>The best times</caption>
<tr>
<td id="firstTimeMin">1</td>
<td id="firstTimeSec">2</td>
</tr>
<tr>
<td id="secondTimeMin">3</td>
<td id="secondTimeSec">4</td>
</tr>
<tr>
<td id="thirdTimeMin">5</td>
<td id="thirdTimeSec">6</td>
</tr>
</tbody>
</table>
<button onclick="timeEntry()">
Enter a new time
</button>
</section>
</body>
</html>
My idea was to simply get the data already in the table using Number or parseInt to get the number value, but either way from the test I've been doing, when I try to get the element from html, it tells me that I get a number type but when I try to use it in an operation it returns NaN. Maybe I'm just stupid, but I've been reading and looking for a day for a way to get the data from the cells as numbers, but aside from Number or parseInt or using a form, I haven't seen a way to do this and it feels like the more I search the less I understand why it doesn't work.
Any help or clue on how to get this done, even it means start back from scratch would be really appreciated.

document.getElementById('firstTimeMin') only get the DOM Element, you should do document.getElementById('firstTimeMin').innerHTML to get the content of the HTML so you'll be able to get the number using parseInt() or Number.
Do the same with every elements.

Related

How to insert something in textarea at the location indicated by the mouse

I created a script that inserts emojis inside a textarea. The problem is that I use innerHTML to insert the emoji and that way it only inserts at the beginning or end of the content of the textarea. I would like to be able to insert this in any location indicated by the user so that if you have already written what you want you can return to a certain part of the text and simply insert your emoji. Does anyone know how to help me?
Sorry it's not really pretty but I feel like this example has everthing to explain it, you can save the snippet in an html page, load it and examine the code :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insertion test</title>
<style>
.classic-button {
width: 140px;
height: 60px;
font-weight: bold;
font-size: 20px;
border: 4px solid black;
background-color: lightgray;
}
table {
border-collapse: collapse;
}
td {
border: 4px solid black;
}
.fs-24-b {
font-size: 24px;
font-weight: bold;
}
.fs-32-b {
font-size: 32px;
font-weight: bold;
}
.tBoxFill {
width: 100%;
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box; /* Opera/IE 8+ */
font-size: 32px;
}
.td-button {
padding: 20px;
}
</style>
<script>
let insertIn = (str1, str2, at) => {
return str1.slice(0,at) + str2 + str1.slice(at);
}
function doGetCaretPosition (oField) {
var iCaretPos = 0;
// IE Support
if (document.selection) {
// Set focus on the element
oField.focus();
// To get cursor position, get empty selection range
var oSel = document.selection.createRange();
// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);
// The caret position is selection length
iCaretPos = oSel.text.length;
}
// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionDirection=='backward' ? oField.selectionStart : oField.selectionEnd;
// Return results
return iCaretPos;
}
function getprintLastPost() {
document.getElementById('printLastPost')
.innerText = 'Last position : '
+ doGetCaretPosition(document.getElementById('TBtoFill'));
}
function insertInTBox(tBoxDOM, text) {
let insStr = text;
let oldCaretPos = doGetCaretPosition(tBoxDOM);
let newCaretPos = oldCaretPos + insStr.length;
tBoxDOM.value = insertIn(tBoxDOM.value, insStr, oldCaretPos);
tBoxDOM.selectionEnd = newCaretPos;
}
function insertStuff() {
let toBox = document.getElementById("TBtoFill");
let inBox = document.getElementById("TBtoInsert");
insertInTBox(toBox, inBox.value);
}
</script>
</head>
<body>
<center>
<table>
<tr>
<td colspan="5">
<textarea class="fs-24-b" id="TBtoFill" cols="70" rows="10">
</textarea>
</td>
</tr>
<tr>
<td colspan="5" class="td-button">
<button class="classic-button" onclick="getprintLastPost()">
Get last pos
</button>
<span class="fs-32-b"> :
</span>
<span id="printLastPost" class="fs-32-b">Last position : ?</span>
</td>
</tr>
<tr>
<td colspan="1" class="td-button">
<button class="classic-button" onclick="insertStuff()">
Insert
</button>
<span class="fs-32-b"> : </span>
</td>
<td style="width: 80%">
<textarea class="tBoxFill fs-32-b" id="TBtoInsert"></textarea>
</td>
</tr>
</table>
</center>
</body>
</html>
Basically, you just take the utf8 or unicode value of the emoji and then you keep the function doGetCaretPosition() to use insertInTBox(). You slice the textbox string in two based on the last position of the caret which the function will tell you, then concatenate left-part->emoji->right part.

Save content editable HTML table in multiple fields

I need to develop a HTML table where one of the table column is editable on its row and the table row is dynamic in term of the row number.
I come across a problem where when I automate the saveEdits() function, the code is not working.
Here is my code, where the 'cnt' is a dynamic numeric number. Example cnt=50
<!DOCTYPE html>
<html>
<head>
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
table ,tr td{
border:1px solid #dddddd;
padding: 8px;
}
tbody {
display:block;
height:600px;
overflow:auto;
}
thead, tbody tr {
display:table;
width:100%;
table-layout:fixed;
}
thead {
width: calc( 100% - 1em )
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<script type="text/javascript">
function saveEdits(cnt) {
//get the editable elements.
var str_out = ''
while (cnt>0){
str1 = '\'edit' + cnt + '\': document.getElementById(\'edit' + cnt + '\').innerHTML,\n'
str_out = str_out.concat(' ', str1);
cnt--;
};
var editElems= { str_out };
alert(editElems)
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
function checkEdits(){
//find out if the user has previously saved edits
var userEdits = localStorage.getItem('userEdits');
alert(userEdits) // suppose to print {"edit1":" rpeyy7<br>","edit2":" tpruiiy<br>","edit3":" opty<br>"}
if(userEdits){
userEdits = JSON.parse(userEdits);
for(var elementId in userEdits){
document.getElementById(elementId).innerHTML = userEdits[elementId];
}
}
}
</script>
</head>
<body onload="checkEdits()">
<table id="myTable">
<thead>
<tr>
<td style="background-color:#A9A9A9" > Field#1 </td>
<td style="background-color:#A9A9A9" > Field#2 </td>
<td style="background-color:#A9A9A9" > Field#3- Each Row Under field#3 is content EditableByUser </td>
</tr>
</thead>
<tbody>
// Here is the python code that loop through a diectionary content
cnt = 0
for c in sorted(data_dict.keys()) :
cnt += 1
<tr>
<td> {0} </td> //Field#1
<td> {0} </td> //Field#2
...
...
<td id="edit{0}" contenteditable="true" onKeyUp="saveEdits({0});"> {1} </td>\n'.format(cnt,comment)]
</tr>
</table>
</body>
I'm not sure where goes wrong as when I automate the saveEdits() function with 'cnt' in while loop, the above code doesn't works for me. But when I defined each row clearly like below, the data the keyed-in are properly saved to each column.
function saveEdits(cnt) {
//get the editable elements.
var editElems = {
'edit1': document.getElementById('edit1').innerHTML,
'edit2': document.getElementById('edit2').innerHTML,
'edit3': document.getElementById('edit3').innerHTML,
};
alert(editElems) //print [object Object]
//save the content to local storage. Stringify object as localstorage can only support string values
localStorage.setItem('userEdits', JSON.stringify(editElems));
}
I would be much appreciate if someone can point out my mistake. The error is very much likely on saveEdits(cnt) function but I'm not sure how to fix that cause it I define each count 1 by 1, each update that being keyed-in is actually saved properly and able to retrieve when rerun. Thanks you!

Please assist to change ${average} output from decimal to whole number

My javascript calculation output showing decimal number, can someone assist me on how to change it to whole number. For an example, output for ${average} is 30.333333333333332 so I wants it to be 30. Can someone assist on this?
Code
<div id="demo" align="center"></div>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script type="text/javascript">
var selectedcount = '';
var average = '';
function myFunction() {
document.getElementById("demo").innerHTML = `
<table class="table table-striped table-dark" style="width:600px; float: right; margin-right: 330px;">
<tr>
<td style="text-align: center; color: #000000; text-align: left;">Predicted average for next semester:</td>
<td style="text-align: center; font-weight: bold; color: #000000; text-align: left;">Approximately ${average} students</td>
</tr>
</table>`
}
$(document).ready(function(){
$("#prg").change( function(){
selectedcount = $('#prg option:selected').data('prgcount');
if(selectedcount > 30){
average = selectedcount / 3 + 5;
} else{
average = selectedcount / 3 - 5;
}
});
});
</script>
P/S: I've removed some unrelated codes from this, I hope it helps.
Output
have you tried this Math.floor?
probably this should work:
${Math.floor(average)}
it will Round the number downward to its nearest integer
You can use toFixed function to get a rounded string by a number passed into that function e.g.:
selectedcount = 29;
// result without round 14,666...
average = (selectedcount / 3 + 5).toFixed(2); // to fixed 2 we get '14,66'
Here you get average string rounded by 2, for example selectedcount. Hope this helps!!

Javascript table is not rendering using CSS

I created a table using JavaScript, but it doesn't render using my css. so how can I make it work? actually i need more help, my idea is to create a screen that has one button and once you click on it a menu which is a table of one column starting at the top of the screen and end at the end of the screen should be showing. the table would be scrollable and each row has text (url text) with no url line under the text, so when you click on it the page open in all of the screen behind the table and the button. the button should be always showing (but it disappears when i click on it).
the main.js file is
function makeTableHTML() {
var x = document.createElement("TABLE");
x.setAttribute("id", "myTable");
var myArray = [ [ "Name, http://www.google.com" ],
[ "Name, http://www.google.com" ] ];
var result = '<table width = "300">';
for (var i = 0; i < myArray.length; i++) {
result += "<tr><td>";
if (i < 10) {
result += "0" + i + " ";
} else {
result += i + " ";
}
result += '<a href="' + myArray[i][0] + '">';
result += myArray[i][1] + "</a>";
result += "<td></tr>";
}
result += "</table>";
document.write(result);
document.getElementById("channelsmenu").classList.toggle(result);
}
function hideTableHTML() {
var x = document.getElementById('channelsmenu');
x.style.display = 'none';
}
and my html is
<!DOCTYPE html>
<html>
<head>
<title>5Star-IPTV</title>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/main.js"></script>
</head>
<body>
<div>
<table>
<tr>
<td>
<div id="channelsmenu" class="dropdown-content"></div>
</td>
<td class="buttons-col"><input type="image"
src="channels-menu.png" class="buttons" alt="channels menue"
onMouseOver="this.src='channels-menu-1.png'"
onMouseOut="this.src='channels-menu.png'" onclick="makeTableHTML()" /></td>
<td class="buttons-col"><input type="image"
src="return-button.png" alt="return button" class="buttons"
onMouseOver="this.src='return-button-1.png'"
onMouseOut="this.src='return-button.png'" onclick="hideTableHTML()" /></td>
</tr>
</table>
</div>
</body>
</html>
and this is the css
table {
width: 100%;
border: 1px solid black;
background-color: #808080;
}
tr {
width: 100%;
align: right;
}
th, td {
text-align: right;
} background-color: #808080;
}
.buttons-col {
text-align: center;
width: 90px;
padding-top: 5px;
}
in HTML you open "th" and close it as "tr". Secondly, please learn to write/format your code properly - it'll be easier to read your code and to help you.
Besides, use the < script > tag at the end of the HTML or run your JS in the function on event DOMContentLoaded

Using JavaScript to change text on the page every half-second

So, what I'm hoping to do is change the text inside a set of <p> tags every half-second. The set of tags in question is in this block of code in my body:
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
Right below the above code I have the JavaScript that should call a function every half-second:
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
I have the function changeMatrixText defined inside my head:
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
As you see, that's supposed to set the text to a random string of 0's and 1's. But it's not working. Any idea why?
Just in case you need to see my entire code .....
<html>
<head>
<title>Simple encrypt/decrypt</title>
<style type="text/css">
body
{
background-color: #A9F5F2;
width: 900px;
padding: 0px;
}
.outerdiv
{
margin: 5px;
border: 2px solid #FF8000;
background-color: #FFFFFF;
}
.outerdiv > p
{
margin: 5px;
word-wrap:break-word
}
.outerdiv > h1
{
margin: 5px;
}
#col1
{
width: 500x;
height: 800px;
float: left;
}
#col2
{
width: 295px;
height: 1500px;
float: right;
font-family: Courier New;
overflow: hidden;
}
#title1div
{
font-family: Arial;
width: 100%;
}
#insctdiv
{
font-family: Arial;
width: 100%;
}
#iptdiv
{
height: 400px;
width: 100%;
}
#buttonsdiv
{
text-align: center;
width: 100%;
}
#inputText
{
width: 100%;
height: 100%;
resize: none;
}
</style>
<script type="text/javascript">
function encrypt()
{
var text = document.getElementById("inputText").value;
newstring = "";
/* Make newstring a string of the bit representations of
the ASCII values of its thisCharacters in order.
*/
for (var i = 0, j = text.length; i < j; i++)
{
bits = text.charCodeAt(i).toString(2);
newstring += new Array(8-bits.length+1).join('0') + bits;
}
/* Compress newstring by taking each substring of 3, 4, ..., 9
consecutive 1's or 0's and it by the number of such consecutive
thisCharacters followed by the thisCharacter.
EXAMPLES:
"10101000010111" --> "10101401031"
"001100011111111111111" --> "0011319151"
*/
newstring = newstring.replace(/([01])\1{2,8}/g, function($0, $1) { return ($0.length + $1);});
document.getElementById("inputText").value = newstring;
}
function decrypt()
{
var text = document.getElementById("inputText").value;
text = text.trim();
text.replace(/([2-9])([01])/g,
function (all, replacementCount, bit) {
return Array(+replacementCount + 1).join(bit);
}).split(/(.{8})/g).reduce(function (str, byte) {
return str + String.fromCharCode(parseInt(byte, 2));
}, "");
document.getElementById("inputText").value = text;
}
function changeMatrixText()
{
var newtext = "";
for (var i = 0; i < 1000; i++)
newtext += Math.floor((Math.random()*10)+1) % 2 ? "0" : "1";
document.getElementById("matrixText").value = newtext;
}
</script>
</head>
<body>
<div id="col1">
<div class="outerdiv" id="title1div">
<h1>Reversible text encryption algorithm</h1>
</div>
<div class="outerdiv" id="insctdiv">
<p>Type in or paste text below, then click <b>Encrypt</b> or <b>Decrypt</b></p>
</div>
<div class="outerdiv" id="iptdiv">
<textarea id="inputText" scrolling="yes"></textarea>
</div>
<div class="outerdiv" id="buttonsdiv">
<button onclick="encrypt()"><b>Encrypt</b></button>
<button onclick="decrypt()"><b>Decrypt</b></button>
</div>
</div>
<div class="outerdiv" id="col2">
<p id="matrixText"></p>
</div>
<script type="text/javascript">
setInterval("changeMatrixText()", 500);
</script>
</body>
</html>
In essence, I'm trying to make the right column of my page keep printing inside a new string of 0's and 1's every half-second, kinda like on the computer screen on the movie The Matrix, if you catch my drift.
According to MDN, the elements with a value attribute include <button>, <option>, <input>, <li>, <meter>, <progress>, and <param>. You'll need to set the innerHTML instead.
document.getElementById("matrixText").value = newtext;
to
document.getElementById("matrixText").innerHTML = newtext;
and
setInterval("changeMatrixText()", 500);
to
setInterval(changeMatrixText, 500);
Working Demo
document.getElementById("matrixText").value = newtext;
.value is used for form fields instead use
document.getElementById("matrixText").innerHTML = newtext;
in your changeMatrixText function
Here's an example of how you can do this:
http://jsfiddle.net/35W4Z/
The main difference is that a <p> element doesn't have a .value attribute. Instead, use the innerHTML attribute (as shown in the JSFiddle example)
Hope this helps!
Well for fun, I stuck this in a fiddle: http://jsfiddle.net/jdmA5/1/
So two things, mostly:
1) You can't set the "value" of a div element. You have to set the .innerHTML:
document.getElementById("matrixText").innerHTML = newtext;
2) This could be due to the fact I built this out in fiddle, but setInterval is notorious for not running like you expect unless you give each iteration its own memory space. I did this by wrapping the call to changeMatrix in a anonymous function:
setInterval(function() {changeMatrixText();}, 500);
Check out the jsfiddle link to see it in action.
Have you tried changing the setInterval method to accept the first argument as the function itself (the name, minus the parentheses), rather than a string...
As you are not passing any parameters explicitly, you can invoke the function as follows:
setInterval(changeMatrixText, 500);
Should you have needed to supply some parameters, then the following would work:
setInterval(function() {
changeMatrixText(myParam1, myParam2); // etc, etc
}, 500);

Categories