JavaScript isn't working for calculator - javascript

I'm trying to write a calculator using HTML5, CSS and JavaScript. I've tested my HTML and CSS with several validators, but on adding the JavaScript functions, my buttons on the calculator aren't working. Nothing is displayed on the screen and none of the functions are being called. What am I doing wrong here? Any help would be appreciated.
Thank you
Here is my HTML code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<!-- Adding link to the .css page now -->
<script type="text/javascript" src = "calculator.js"></script>
<link rel="stylesheet" href="calculator.css">
<title>Calculator Front-End</title>
</head>
<body>
<form>
<input type = "text" id = "screenid" class = "screen" name = "calcscreen" value = "0">
<p>
</p>
<table>
<tr>
<td> </td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">7</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">8</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">9</button></td>
<td><button id = "add" class = "symbolbutton" onclick="addDisp(this)">&plus;</button></td>
</tr>
<tr>
<td></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">4</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">5</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">6</button></td>
<td><button id = "sub" class = "symbolbutton" onclick="addDisp(this)">−</button></td>
</tr>
<tr>
<td></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">1</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">2</button></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">3</button></td>
<td><button id = "prod" class = "symbolbutton" onclick="addDisp(this)">×</button></td>
</tr>
<tr>
<td></td>
<td></td>
<td><button class = "digitbutton" id = "digit" onclick="addDisp(this)">0</button></td>
<td><button id = "result" class = "symbolbutton" onclick="doCalc(this)">&equals;</button></td>
<td><button id = "div" class = "symbolbutton" onclick="addDisp(this)">÷</button></td>
</tr>
</table>
</form>
</body>
</html>
-------------------------------------------------------------------------
-------------------------------------------------------------------------
****And here's my calculator.js file:****
//Defining the variables and constants I need for my functions
var previousvalue = 0; //Last button pressed
var newvalue = 0; //Current button being pressed
var previousop = 'plus';
var previnputcn = 'symbolbutton' //Classname of the previous button
//Writing the function to display elements on screen
function addDisp(button)
{
//Assume if the button pressed is a digit:
if (button.classname == "digitbutton") //Suppose button pressed = 5
{
if (previnputcn == "symbolbutton") //Suppose previous button pressed was a symbol
{
newvalue = document.getElementById("digit").value; //New value becomes 5
}
else
{
newvalue = newvalue + document.getElementById("digit").value;
//Previous button pressed was a digit, so current display is appended
}
}
document.getElementById("screenid").value = document.getElementById("screenid").value + newvalue; //Print Everything on Screen
if (button.classname == "symbolbutton") //Suppose button pressed was a symbol
{
var calcResult = doCalc(previousvalue, newvalue, previousop);
if (calcResult <= 1000000 || calcResult == "ERROR")
{
newvalue = calcResult;
}
document.getElementById("screenid").value = document.getElementById("screenid").value +newvalue;
if (newvalue == "ERROR")
{
previousvalue = 0; //Re-initalize last value to 0 in case of an error
}
else
{
previousvalue = newvalue; //Re-update current value as last value to continue calculation
}
previousop = button.id; //Last operation gets id of the current operation button
}
previnputcn = button.className; //Last button classname stored for reference for future calculations
}
/*Writing the doCalc() function which handles all the calculations*/
function doCalc(newvalue, previousvalue, previousop)
{
var output = newvalue;
if (previousop == "plus")
{
output = parseInt(previousValue) + parseInt(newvalue);
}
else if (previousop == "minus")
{
output = parseInt(previousValue) - parseInt(newvalue);
}
else if (previousop == "times")
{
output = parseInt(previousValue) * parseInt(newvalue);
}
else if (previousop == "divide")
{
if (newvalue != 0)
{
output = parseInt(previousValue) / parseInt(newvalue);
output = parseInt(output);
}
else
{
output = "ERROR";
}
}
calcResult = output;
}

There are two issues with your code.
Specify the type of each button as type="button". The default type for button is "submit" which will cause the form to be submitted on clicking. Your page is getting refreshed everytime the buttons are clicked.
Most of your buttons have the same id. Id is supposed to be unique.
You are anyways passing the button element as argument to the addDisp function on click. Use it to fetch the value.

Related

Display data in a table from localStorage without repeating

I am making a shopping list in my web page where I add the items which I store in localStorage.The items are displayed in a table.The problem is that for each new item added it is showing also the data previously stored again.
My html is:
<form class="market">
<label>Nume produs</label>
<input type="text" id="np">
<label>Cantitate</label>
<input type="text" id="cp">
<input type="button" onclick="addItem();" id="adauga" value="Adaugă" />
</form>
<table>
<tbody id="shopping">
<tr>
<th>Nr.</th>
<th>Name</th>
<th>Quantity</th>
</tr>
And this is the function called on every button click
class Produs{
constructor(id, nume, cantitate){
this.id = id;
this.nume = nume;
this.cantitate = cantitate;
}
}
function addItem(){
let nume = document.getElementById("np").value;
let cantitate = document.getElementById("cp").value;
let produse = localStorage.getItem('produse');
if(produse == null){
produse = [];
}
else{
produse = JSON.parse(produse);
}
produse = produse.map((p) => {
return new Produs(p.id, p.nume, p.cantitate);
});
let lastId = localStorage.getItem('lastId');
if(lastId == null)
{
lastId=1;
}
else{
lastId = JSON.parse(lastId);
}
let id = lastId;
produse.push(new Produs(id, nume, cantitate));
localStorage.setItem('produse',JSON.stringify(produse));
localStorage.setItem('lastId',JSON.stringify(lastId+1));
var jsonData = JSON.parse(localStorage.getItem('produse'));
console.log(jsonData);
for(var i=0; i<jsonData.length; i++)
{
document.getElementById("shopping").innerHTML +="<tr><td>"+jsonData[i].id +"</td><td>" + jsonData[i].nume +"</td><td>"+jsonData[i].cantitate+"</td></tr>";
}
}

html class replacement in JS is not working

I am trying to change replace an html class based on value.For example if nsndatalength = 0 replace the class name with badge-success
function Awardstable(data) {
var container = document.getElementById('awardsTable');
data.forEach(function(awardsSnap) { // loop over all inventory
var Items = awardsSnap.val();
var nome = Items.Nomenclature;
var NSN = Items.NSN;
var AwardId = Items.Awardid;
var AwrdDate = Items.Awarddate;
var name = Items.Name;
// var quant = Items.Qty;
var cost = Items.Price;
var key = awardsSnap.key;
var NSNref = CatalogueDB.ref("NSNdata/" + NSN).orderByChild("NSN");
if (NSNref) {
// Attach an asynchronous callback to read the data at our posts reference
NSNref.on("value", function(nsnshot) {
if (nsnshot.val()) {
var nsndatalength = Object.keys(nsnshot.val()).length;
} else {
nsndatalength = 0;
}
console.log(nsndatalength)
console.log(nsnshot.val())
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty">${nsndatalength} Sellers</span>
</td>
<td><button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">
Buy
</button></td>
</tr>
`;
container.innerHTML += inventoryCard;
if (nsndatalength == 0){
var buybtn = document.getElementById('buymodalbtn')
var qtymarker = document.getElementById('sellerqty')
console.log("class",buybtn,qtymarker)
document.getElementById("buymodalbtn").className = document.getElementById("buymodalbtn").className.replace
( /(?:^|\s)btn-warning(?!\S)/g , 'btn-success' )
document.getElementById("sellerqty").className = document.getElementById("sellerqty").className.replace
( /(?:^|\s)badge-primary(?!\S)/g , 'badge-success' )
}
})
} else {
nsndatalength = 0;
console.log("No Awards Available")
}
});
}
The problem is that the code is not working for all inventoryCard. This is the output of the html. The last item 0 sellers and buy button should also change color. What am I doing wrong from the code above?
We can use classList.toggle to toggle a class on/off, with the second parameter we can force it to be on/off.
Here we give the item a unique id:
<span class="badge badge-primary" id="sellerqty-${AwardId}">
then select it with:
document.getElementById(`sellerqty-${AwardId}`)
In your code it would look something like this by giving the item a unique id:
var inventoryCard = `
<tr>
<th scope="row">${NSN}</th>
<td>${nome}</td>
<td>${AwardId}</td>
<td>${AwrdDate}</td>
<td class="color-danger">${cost}</td>
<td>
<span class="badge badge-primary" id="sellerqty-${AwardId}">${nsndatalength} Sellers</span>
</td>
<td>
<button type="button" class="btn btn-warning mb-1" id="buymodalbtn" data-toggle="modal" data-target="#buyModal" onclick="buyModal('${NSN}')">Buy</button>
</td>
</tr>`;
// Add it before we call getElementById
container.innerHTML += inventoryCard;
document.getElementById(`sellerqty-${AwardId}`).classList.toggle('badge-success', nsndatalength == 0)

Clickable html table cells

I'm making a tic-tac-toe game. I've made my table cells clickable and once they are clicked they run a function called playPVPGame. To start, O and X are chosen randomly to go first. I have text in the corner of the page to indicate whose turn it is. Initially the text will be either "O goes first" or "X goes first". Afterwards it will change to "X is next" or "O is next" depending on the turn. The problem is after the initial text, the turn doesn't go back and forth like i want it to.
var $ = function(id) {
return document.getElementById(id);
};
var newGameAction = function()
{
//clear table
$("c1").innerHTML = "";
$("c2").innerHTML = "";
$("c3").innerHTML = "";
$("c4").innerHTML = "";
$("c5").innerHTML = "";
$("c6").innerHTML = "";
$("c7").innerHTML = "";
$("c8").innerHTML = "";
$("c9").innerHTML = "";
};
var pVpAction = function(elem)
{
var outputTect;
var turnCounter = 0;
var first_Turn = Math.floor(Math.random() * 2);
$("firstTurn").innerHTML = first_Turn;
first_turn = $("firstTurn").innerHTML;
if(first_turn == 0)
{
message = "O goes first";
}
if(first_turn == 1)
{
message = "X goes first";
}
$("goNext").innerHTML = message;
};
var playPVPGame = function(elem)
{
var turn = $("goNext").innerHTML;
var message;
if(turn == "O goes first")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
turn = "X is next";
$("goNext").innerHTML = turn;
}
if(turn == "X goes first")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
turn = "O is next";
$("goNext").innerHTML = turn;
}
//does not work
/*if($("goNext").innerHTML = "X is next")
{
$("newGame").disabled = true;
}*/
message = $("goNext").innerHTML;
if(message == "X is next")
{
elem.style.backgroundColor = "blue";
elem.innerHTML = "X";
message = "O is next";
$("goNext").innerHTML = message;
}
if(message == "O is next")
{
elem.style.backgroundColor = "red";
elem.innerHTML = "O";
message = "X is next";
$("goNext").innerHTML = message;
}
};
window.onload = function() {
$("newGame").onclick = newGameAction;
$("playerVplayer").onclick = pVpAction;
};
table {width:100%}
table tr td{border:1px solid #000;height:50px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span id="firstTurn"> </span>
<span id= "goNext"> </span>
<table class = "board">
<tr>
<td id = "c1" onclick="playPVPGame(this)" > . </td>
<td id = "c2" onclick="playPVPGame(this)"> . </td>
<td id = "c3" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c4" onclick="playPVPGame(this)"> . </td>
<td id = "c5" onclick="playPVPGame(this)"> . </td>
<td id = "c6" onclick="playPVPGame(this)"> . </td>
</tr>
<tr>
<td id = "c7" onclick="playPVPGame(this)"> . </td>
<td id = "c8" onclick="playPVPGame(this)">. </td>
<td id = "c9" onclick="playPVPGame(this)"> .</td>
</tr>
</table>
<input type="button"
id= "newGame"
value="New Game"/>
<input type="radio"
id= "playerVplayer"
value="Player vs Player"/>
<input type="radio"
id= "playerVcpu"
value="Player vs CPU"/>
Store the current player ('X' or 'O') in a variable instead of reading it from your GUI.
Reading from the GUI is bad practice and you having to ask this question shows why that's the case.
Here you have simplified minimal working example: https://jsfiddle.net/smajl/nr21zd9e/1/
I highly suggest you store the game state in some handy object like:
{
nextTurn: 'X',
isFirstTurn: true,
...
}
You are also ending </body> too soon in your HTML and have many other small or big issues in your code.

How to disable X's an O's in Javascript Tic Tac Toe game

For short, I know the question doesn't make that sense, let me clear things up, if i click on the O's it changes to X and vise versa how can i fix this?
Like I don't know how to disable them to stay put and also do you guys know how can I reset the game with a for loop instead of doing it manually
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Tic Tac Toe</title>
<script text="javascript" src="tic.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<center>
<body>
<h1 style="font-family:arial;">Tic-Tac-Toe</h1>
<table>
<tr>
<td id = "case1" onclick="display_input('case1')"></td>
<td id = "case2" onclick="display_input('case2')"></td>
<td id = "case3" onclick="display_input('case3')"></td>
</tr>
<tr>
<td id = "case4" onclick="display_input('case4')"></td>
<td id = "case5" onclick="display_input('case5')"></td>
<td id = "case6" onclick="display_input('case6')"></td>
</tr>
<tr>
<td id = "case7" onclick="display_input('case7')"></td>
<td id = "case8" onclick="display_input('case8')"></td>
<td id = "case9" onclick="display_input('case9')"></td>
</tr>
</table>
<footer>
<p>Copyright© 2014</p>
</footer>
</body>
</center>
</html>
Javascript:
var player_one = 1;
function display_input(square){
if ( player_one == 1 ){
document.getElementById(square).innerHTML = "X";
player_one = 0;
} else {
document.getElementById(square).innerHTML = "O";
player_one = 1;
}
}
function reset() {
document.getElementById("case1").innerHTML = "";
document.getElementById("case2").innerHTML = "";
document.getElementById("case3").innerHTML = "";
document.getElementById("case4").innerHTML = "";
document.getElementById("case5").innerHTML = "";
document.getElementById("case6").innerHTML = "";
document.getElementById("case7").innerHTML = "";
document.getElementById("case8").innerHTML = "";
document.getElementById("case9").innerHTML = "";
}
You can always check that the square element is empty, and if it is not, then don't perform any action:
function display_input(square) {
//We get the associated DOM element
var element = document.getElementById(square);
//If the element already contains something, then don't change it
if(element.innerHTML != "") return;
if(player_one == 1) {
element.innerHTML = "X";
player_one = 0;
} else {
element.innerHTML = "O";
player_one = 1;
}
}
Overwrite the onclick function of the square by adding the following to display_input(square)
document.getElementById(square).onclick = function() {return};

Javascript double click text transform into textbox

What is the javascipt code that will edit a text on double click. The process is I have a text and if I double click it, a text box will appear, and if I press enter the word will change depends on what you've type.
Sample
This is sample text. $nbsp;$nbsp; --> if I double click it a textbox will appear.
<input type="text" value="This is sample text." name="" />
Sorry for asking this. I am a newbie in javascript
Here is a great example.
I'm going to paste in the script from that example so that it's preserved in case that link goes away, but you should follow the link -- the article does a great job of breaking the script down line by line and explaining what it does. A great learning opportunity for javascript.
var editing = false;
if (document.getElementById && document.createElement) {
var butt = document.createElement('BUTTON');
var buttext = document.createTextNode('Ready!');
butt.appendChild(buttext);
butt.onclick = saveEdit;
}
function catchIt(e) {
if (editing) return;
if (!document.getElementById || !document.createElement) return;
if (!e) var obj = window.event.srcElement;
else var obj = e.target;
while (obj.nodeType != 1) {
obj = obj.parentNode;
}
if (obj.tagName == 'TEXTAREA' || obj.tagName == 'A') return;
while (obj.nodeName != 'P' && obj.nodeName != 'HTML') {
obj = obj.parentNode;
}
if (obj.nodeName == 'HTML') return;
var x = obj.innerHTML;
var y = document.createElement('TEXTAREA');
var z = obj.parentNode;
z.insertBefore(y,obj);
z.insertBefore(butt,obj);
z.removeChild(obj);
y.value = x;
y.focus();
editing = true;
}
function saveEdit() {
var area = document.getElementsByTagName('TEXTAREA')[0];
var y = document.createElement('P');
var z = area.parentNode;
y.innerHTML = area.value;
z.insertBefore(y,area);
z.removeChild(area);
z.removeChild(document.getElementsByTagName('button')[0]);
editing = false;
}
document.onclick = catchIt;
I wanted to know how it works as I have seen it on many websites. And I build it using jQuery
$(document).dblclick(function(event) {
var id = event.target.id; //id
// var id = $(this).attr('id');
if (id == "") {
console.log("nope");
} else {
id = "#" + id + "";
console.log(typeof(id)); //concatenated with #
text = $(id).text().trim();
console.log(text); //asscociated text
$(id).html('<textarea name="" id="tex" cols="10" rows="1" onkeypress="myFunction(event)">' + text + '</textarea>');
// alert(id);
}
})
function myFunction(event) {
var x = event.code;
var id = $(this).attr('id');
parentId = event.path[1].id;
parentId = "#" + parentId + "";
if (x == 'Enter') {
name = $('#tex').val();
$(parentId).text(name);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container mt-3">
<h2>Striped Rows</h2>
<p>The .table-striped class adds zebra-stripes to a table:</p>
<table class="table table-striped">
<thead>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr>
<td id="name1" class="name">
john
</td>
<td id="sirname1">Doe</td>
<td id="email1">john#example.chdm som</td>
</tr>
<tr>
<td id="name2" class="name">Mary</td>
<td id="sirname2">Moe</td>
<td id="email2">mary#example.com</td>
</tr>
<tr>
<td id="name3" class="name">July</td>
<td id="sirname3">Dooley</td>
<td id="email3">july#example.com</td>
</tr>
</tbody>
</table>
</div>

Categories