Issues with building out a Javascript Calculator - javascript

I'm trying to create a simple javascript calculator with divide, multiple, subtract, add, clear, equals, and decimal buttons.
I can't seem to figure out how to add a cell for divide/multiply and decimal.
Any help in trying to resolve this would be greatly appreciated.
function calculate(numEntered) {
if (numEntered == 'C') {
document.getElementById('answer').value = '';
} else if (numEntered == '=') {
document.getElementById('answer').value = eval(document.getElementById('answer').value);
} else {
document.getElementById('answeralue') += numEntered;
}
}
table,
td {
border: 1px solid #000000;
}
td {
cursor: pointer;
}
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
</head>
<body>
<table>
<tbody>
<tr>
<td colspan="3"><input type="text" id="answer" disabled=""></td>
<td onclick="calculate('C');">C</td>
</tr>
<tr>
<td onclick="calculate(1);">1</td>
<td>2</td>
<td>3</td>
<td onclick="calculate('+')">+</td>
</tr>
<tr>
<td onclick="calculate(4);">4</td>
<td>5</td>
<td>6</td>
<td onclick="calculate('-')" ;>-</td>
</tr>
<tr>
<td onclick="calculate(7);">7</td>
<td>8</td>
<td>9</td>
<td onclick="calculate('=')" ;>=</td>
</tr>
</tbody>
</table>
</body>
</html>

You just need to add a row with the rest of the operators * - multiplication, / - division, and decimal point - .
<tr>
<td onclick="calculate('*');">*</td>
<td onclick="calculate('/');">/</td>
<td onclick="calculate('.');">.</td>
</tr>
EDIT: This of course doesn't check if you've placed the operator in an appropriate place.
There's typo in your js code:
document.getElementById('answeralue') += numEntered; // should be ...('answer').value +=...
Also, be aware that eval may open your project for code injection and is really slow.

If you delegate, it is easier to handle the contents of each cell
I also fixed your error in
document.getElementById('answeralue') += numEntered;
which had the wrong ID and needed a .value
const nums = "1234567890";
const oper = "*/+-.";
const actions = "C";
document.getElementById("calc").addEventListener("click",function(e) {
const char = e.target.textContent;
if (char == 'C') {
document.getElementById('answer').value = '';
return;
}
// if (oper.includes(char)) { // for later
if (char === "=") {
document.getElementById('answer').value = eval(document.getElementById('answer').value);
return
}
else document.getElementById('answer').value += char.trim(); // the trim handles empty cells
});
table,
td {
border: 1px solid #000000;
}
td {
cursor: pointer;
min-width: 30px;
}
<table>
<tbody id="calc">
<tr>
<td colspan="3"><input type="text" id="answer" disabled=""></td>
<td>C</td>
<td> </td>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>+</td>
<td>-</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
<td>*</td>
<td>/</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
<td>=</td>
<td>.</td>
</tr>
</tbody>
</table>

Related

extend Javascript client-side html table search to use operators for OR (||) and AND (&&)

Unfortunately I have no experience with javascript and just copied the html table search from https://speedysense.com/filter-html-table-using-javascript/ to a local html file. The search works but I need to extend the code to support logical search operators like || and && to implement AND and OR search functionality. Has anybody the knowledge to let me know the required adaptions to the code:
<!DOCTYPE html>
<html lang="en-US">
<head>
<title>JavaScript Table Filter Search</title>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<style type="text/css">
h3 span {
font-size: 22px;
}
h3 input.search-input {
width: 300px;
margin-left: auto;
float: right
}
.mt32 {
margin-top: 32px;
}
</style>
</head>
<body class="mt32">
<div class="container">
<h3>
<span>JavaScript Filter Table Data</span>
<input type="search" placeholder="Search..." class="form-control search-input" data-table="customers-list"/>
</h3>
<table class="table table-striped mt32 customers-list">
<thead>
<tr>
<th>Customer ID</th>
<th>Name</th>
<th>Email</th>
<th>Postal Code</th>
<th>Country</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ana Trujillo</td>
<td>Ana.trujillo#gmail.com</td>
<td>050214</td>
<td>Germany</td>
</tr>
<tr>
<td>2</td>
<td>Antonio Moreno</td>
<td>antoniomoreno2#gmail.com</td>
<td>12209</td>
<td>Mexico</td>
</tr>
<tr>
<td>3</td>
<td>Maria Anders</td>
<td>mariaanders#yahoo.com</td>
<td>05021</td>
<td>Germany</td>
</tr>
<tr>
<td>4</td>
<td>Thomas Hardy</td>
<td>hardythomas.90#gmail.com</td>
<td>WA1 1DP</td>
<td>United Kingdom</td>
</tr>
<tr>
<td>5</td>
<td>Christina Berglund</td>
<td>christina#outlook.com</td>
<td>S-958 22</td>
<td>Sweden</td>
</tr>
<tr>
<td>6</td>
<td>Davolio Nancy</td>
<td>nancy.davolio#gmail.com</td>
<td>810025</td>
<td>India</td>
</tr>
<tr>
<td>7</td>
<td>Fuller Andrew</td>
<td>andrew.10#yahoo.com</td>
<td>W23 458</td>
<td>United State</td>
</tr>
<tr>
<td>8</td>
<td>Leverling Janet</td>
<td>leverling.j#gmail.com</td>
<td>T5A 0B5</td>
<td>Canada</td>
</tr>
</tbody>
</table>
</div>
<script>
(function(document) {
'use strict';
var TableFilter = (function(myArray) {
var search_input;
function _onInputSearch(e) {
search_input = e.target;
var tables = document.getElementsByClassName(search_input.getAttribute('data-table'));
myArray.forEach.call(tables, function(table) {
myArray.forEach.call(table.tBodies, function(tbody) {
myArray.forEach.call(tbody.rows, function(row) {
var text_content = row.textContent.toLowerCase();
var search_val = search_input.value.toLowerCase();
row.style.display = text_content.indexOf(search_val) > -1 ? '' : 'none';
});
});
});
}
return {
init: function() {
var inputs = document.getElementsByClassName('search-input');
myArray.forEach.call(inputs, function(input) {
input.oninput = _onInputSearch;
});
}
};
})(Array.prototype);
document.addEventListener('readystatechange', function() {
if (document.readyState === 'complete') {
TableFilter.init();
}
});
})(document);
</script>
</body>
</html>
Maybe with a little explanation how this works to gain more knowledge about the functionality of the code extension!?
Thank you for your support!
Best regards
Frank

Get a password validation from a table number

I want to create a password inut that get value (when the user click on the password input) from a table that display numbers from [0-9] using Javascript
This is what i want to do :
Any idea ?!?
Get all the td and attach click event to it, then get the content of the td & append the td value to the value of the input
[...document.querySelectorAll("#passwordTable td")].forEach(function(item) {
item.addEventListener('click', function() {
document.getElementById('pass').value += item.textContent.trim();
})
})
td {
cursor: pointer
}
td:hover {
background: blue;
zoom: 1.1;
color: #fff;
}
<input type='password' id='pass'>
<table border="2" id="passwordTable">
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</table>

JS Sortable Tables with linked rows?

Okay, I have a table. In this table I have a whole bunch of columns, and I would like to use a Sortable Tables javascript so that the user can sort the table as they wish. There are many such JS scripts available (ie: http://tablesorter.com/docs/)
However, the problem I have is that for each row of my table that I want sorted, there is a colspan="4" row right below it that I dont want sorted. In fact, I want these rows linked directly to the row above them so that when those rows get sorted, the 4-span row below it sticks with it.
Is something like this possible?
table {
border: 1px black solid;
width: 100%;
}
thead {
background-color: lightgrey;
text-align: left;
}
.notes {
text-align: right;
}
<table>
<thead>
<tr>
<th>Command</th>
<th>DMG</th>
<th>EXE</th>
<th>TOT</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jouho Touken</td>
<td>19</td>
<td>17</td>
<td>42</td>
</tr>
<tr>
<td colspan="4" class="notes">Opponent crouching (H: Stagger)</td>
</tr>
<tr>
<td>Chouyoushu</td>
<td>25</td>
<td>18</td>
<td>46</td>
</tr>
<tr>
<td colspan="4" class="notes">Damage varies due to distance (25-40)</td>
</tr>
<tr>
<td>Tetsuzankou</td>
<td>40</td>
<td>19</td>
<td>75</td>
</tr>
<tr>
<td colspan="4" class="notes">Super Replay; Damage varies due to distance: 40-80</td>
</tr>
</tbody>
</table>
Here is an example of how you could do this.
Make an array of all rows in the <tbody>.
Group it into pairs. [{data, note}, ...]
Sort by a given sorting function
Flatten back into an array of table rows.
empty the <tbody> tag
Insert into the <tbody> tag everything in the sorted table rows array.
var tableBody = document.querySelector('tbody')
var tableRows = Array
.from(document.querySelectorAll('tbody > tr'))
var notesAndData = []
/* Group elements into
[
{data: <tr>, note: <tr>},
...
]
*/
for(var i = 1; i < tableRows.length; i += 2) {
notesAndData.push({
data: tableRows[i-1],
note: tableRows[i]
})
}
function flatten(arr) {
return arr.reduce(function(acc, curr) {
acc.push(curr.data)
acc.push(curr.note)
return acc
}, [])
}
function repopulateTable(arr) {
tableBody.innerHTML = ''
arr.forEach(function(element) {
tableBody.appendChild(element)
})
}
function sortTable(sortingFunc) {
/* Spread the notesAndData into a new array in
order to not modify it. This syntax is es6 */
var sorted = [...notesAndData].sort(sortingFunc)
repopulateTable(flatten(sorted))
}
function sortByDmg(ascending) {
return function(a, b) {
var aDmg = parseInt(a.data.children[1].textContent)
var bDmg = parseInt(b.data.children[1].textContent)
if (aDmg < bDmg) return ascending ? 1 : -1
return ascending ? 1 : -1
}
}
document
.querySelector('.dmgSort')
.addEventListener('click', function() {
sortTable(sortByDmg(true))
})
table {
border: 1px black solid;
width: 100%;
}
thead {
background-color: lightgrey;
text-align: left;
}
.notes {
text-align: right;
}
<button class="dmgSort">Sort By DMG Ascending</button>
<table>
<thead>
<tr>
<th>Command</th>
<th>DMG</th>
<th>EXE</th>
<th>TOT</th>
</tr>
</thead>
<tbody>
<tr>
<td>Jouho Touken</td>
<td>19</td>
<td>17</td>
<td>42</td>
</tr>
<tr>
<td colspan="4" class="notes">Opponent crouching (H: Stagger)</td>
</tr>
<tr>
<td>Chouyoushu</td>
<td>25</td>
<td>18</td>
<td>46</td>
</tr>
<tr>
<td colspan="4" class="notes">Damage varies due to distance (25-40)</td>
</tr>
<tr>
<td>Tetsuzankou</td>
<td>40</td>
<td>19</td>
<td>75</td>
</tr>
<tr>
<td colspan="4" class="notes">Super Replay; Damage varies due to distance: 40-80</td>
</tr>
</tbody>
</table>

jquery find() equivalent for javascript

I have three tables and i want to check wheter they contain a specific element, e.g. a button with the value 'Previous'. I solved it by using the jquery function find and writing a function, but i need to solve this problem without jquery. Is this possible?
var t1 = document.getElementById("table_one");
var t2 = document.getElementById("table_two");
var t3 = document.getElementById("table_three");
has_prev_button(t1);
has_prev_button(t2);
has_prev_button(t3);
function has_prev_button(element)
{
var has_prev_button = false;
var check = $(element).find("input[type=button]");
for (i=0; i<=check.length-1; i++) {
if (check[i].getAttribute("value") == "Previous") {
has_prev_button = true;
}
}
if (has_prev_button) {
document.write("<p>The selected table has a Previous button</p>");
} else {
document.write("<strong><p style='color:red'>The selected table has NO Previous button</p></strong>");
}
}
table {
margin-bottom:40px;
border: 1px solid black;
}
td {
border: 2px solid #D8D8D8;
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_one">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_two">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_three">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
Use element.querySelectorAll:
var t1 = document.getElementById("table_one");
var t2 = document.getElementById("table_two");
var t3 = document.getElementById("table_three");
has_prev_button(t1);
has_prev_button(t2);
has_prev_button(t3);
function has_prev_button(element)
{
var has_prev_button = false;
var check = element.querySelectorAll("input[type=button]");
for (i=0; i<=check.length-1; i++)
{
if (check[i].value == "Previous")
{
has_prev_button = true;
}
}
if (has_prev_button)
{
document.write("<p>The selected table has a Previous button</p>");
}
else
{
document.write("<strong><p style='color:red'>The selected table has NO Previous button</p></strong>");
}
}
table {
margin-bottom:40px;
border: 1px solid black;
}
td {
border: 2px solid #D8D8D8;
width: 70px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_one">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_two">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
<table id="table_three">
<tr>
<td>Foo</td>
<td>Bar</td>
<tr>
<tr>
<td><input type="button" value="Previous"></td>
<td><input type="button" value="Next"></td>
</tr>
</table>
Simply use document.querySelectorAll along with the classes spaced apart.
For example, if I want to find the button in the 3rd section and change its background color:
jQuery
$('.my_sections').eq(2).find('.my_button').css('background', 'pink')
Vanilla JS
document.querySelectorAll('.my_sections .my_button')[2].style.background = 'pink'
Similarly, If I wanted to check how many buttons I had of the my_button class:
document.querySelectorAll('.my_sections .my_button').length

HTML JavaScript - changing info in cell by ID

I've got this problem:
I have a table in HTML, that I want to edit via Javascript.
The table info is of rooms with either value 0 or 1.
I have two buttons that can change a cell, that can set the value to 1 or 0, but I want a function connected to one button, that changes the value, as 1 gets to 0, and 0 gets to 1.
One solution I find is to give each cell an ID and change it, and the other one is to use row/cell from the table.
<table id="table1">
<table border="1" cellpadding="1" cellspacing="3">
<tr>
<td> Room </td>
<td> Status </td>
</tr>
<tr>
<td> r1 </td>
<td id="room1"> 0 </td>
</tr>
<tr>
<td> r2 </td>
<td> 0 </td>
</tr>
<tr>
<td> r3 </td>
<td> 1 </td>
</tr>
Currently I've tried:
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
<button type="button" onclick="metode2()">Room 1 => 0</button>
<script>
function metode1(){
if(document.getElementById("room1").innerHTML > 0) {
document.getElementById("room1").innerHTML = 0;
}
else {
document.getElementById("room1").innerHTML = 1;
}
}
function metode2(){
document.getElementById("table1").rows[1].cells[1].innerHTML = 0;
}
</script>
But neither of them work..
What can I do?
metode1 would work, but your initial text in the element has spaces on either side of the 0, so > can't implicitly convert it to a number. If you remove the spaces (in the markup, or by doing .innerHTML.trim() on a modern browser), the implicit conversion from string to number will work. You might consider converting explicitly, but you'll still have to trim.
Live Example with the spaces removed in the markup:
function metode1() {
if (document.getElementById("room1").innerHTML > 0) {
document.getElementById("room1").innerHTML = 0;
} else {
document.getElementById("room1").innerHTML = 1;
}
}
<table border="1" cellpadding="1" cellspacing="3">
<tr>
<td>Room</td>
<td>Status</td>
</tr>
<tr>
<td>r1</td>
<td id="room1">0</td>
</tr>
<tr>
<td>r2</td>
<td>0</td>
</tr>
<tr>
<td>r3</td>
<td>1</td>
</tr>
</table>
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
Live Example using trim:
function metode1() {
if (document.getElementById("room1").innerHTML.trim() > 0) {
document.getElementById("room1").innerHTML = 0;
} else {
document.getElementById("room1").innerHTML = 1;
}
}
<table border="1" cellpadding="1" cellspacing="3">
<tr>
<td>Room</td>
<td>Status</td>
</tr>
<tr>
<td>r1</td>
<td id="room1"> 0 </td>
</tr>
<tr>
<td>r2</td>
<td>0</td>
</tr>
<tr>
<td>r3</td>
<td>1</td>
</tr>
</table>
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
Note that trim was added in ECMAScript5 (2009) and so may not be on some older JavaScript engines. It's easily shimmed, though.
Try this-
<button type="button" onclick="metode1()">Room 1 => 0/1</button>
function metode1(){
if(document.getElementById("room1").innerHTML.trim() =="1") {
document.getElementById("room1").innerHTML = 0;
}
else {
document.getElementById("room1").innerHTML = 1;
}
}

Categories