storing string addition in a variable for calculator function - javascript

I am trying to do a Calculator in JavaScript, so I started with addition operation.
I tried to convert addition operator into a string to add into a variable so that I can add the values from function. I found out it is not possible is there any better way to solve this issue.
Codepen
var store = '';
var totalvalue;
function one() {
store += "1";
totalvalue = Number(store);
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
function two() {
store += "2";
totalvalue = Number(store)
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
function add()
{
store = '+';
totalvalue = parseInt(store);
//THIS IS WHERE ITS NOT WORKING I CAME TO KNOW THAT I CANT STORE A OPERATOR
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
function equalsto() {
console.log(totalvalue);
document.querySelector('.total').textContent = totalvalue;
}
<button class="addition" onclick="add()">+</button><br>
<button class="one" onclick="one()">1</button><br>
<button class="two" onclick="two()">2</button><br>
<button class="output" onclick="equalsto()">=</button>
<p class="exit"></p>
<h1 class="total">total</h1>

You're doing it all wrong , in store variable , you should add up the string of all the commands and numbers pressed and use eval to get result whereas you are only replacing store vaiable with current clicked value opreraton like add
You shoudl first add + sign to store and then parse it:
function add()
{
store+ = '+';
totalvalue = parseInt(store);
console.log(totalvalue);
document.querySelector('.exit').textContent = store;
}
A better way would be to design the buttons and get their text in complete string to a final variable.To evaluate result on '=' , you can just use
ans=eval(string_of_variable)
#e {
background-color: red;
}
button:nth-child(4n+2) {
display: block;
}
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>0</button>
<button>+</button>
<button>-</button>
<button>/</button>
<button>*</button>
<p id="e">= (Click to evaluate)</p>
<br>
<p id="ex"></p>
<script>
var main = "";
$("button").click(function() {
main += ($(this)[0].innerText);
$("#ex")[0].innerText = main;
});
$("#e").click(function() {
alert("Answer of " + main + " is: " + eval(main));
main = "";
});
</script>
</html>

Related

JavaScript/HTML - Passing onclick button parameter to JavaScript function

I'm very new to JavaScript so I apologize if this question has an extremely obvious answer. What I'm trying to do is pass the name of a text box in HTML to a function in Javascript via an onclick button. The goal of the function is to test a given string and highlight it based on certain parameters (for my testing, it is simply length).
There are multiple weird odds and ends within the functions that I'm aware of and working on, I know the functions work as when I remove the parameters and call the code text box directly, it prints exactly what I expect it to. But I want to be able to pass multiple text boxes without needing a specific function per box.
The code I have is as follows. I've included all of it in case the mistake was made somewhere I didn't expect it to be.
<!DOCTYPE html>
<html>
<head>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<label for="wordOne">Word One</label><br>
<input type="text" id="wordOne" name="wordOne"><br>
// Pass the value for the wordOne textbox to verify function
<button type="button" onclick="verify(wordOne,this)">Check</button><br><br>
<label for="wordTwo">Word Two</label><br>
<input type="text" id="wordTwo" name="wordTwo"><br>
// Pass the value for the wordTwo textbox to verify function
<button type="button" onclick="verify(wordTwo,this)">Check</button><br><br>
<p id="test"></p><br>
<p id="error"></p>
<script>
// Highlights any code in a given line.
function highlight(text,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
function verify(button,el){
var begin=1;
var end=1
var id="test";
var string = document.getElementById(button).value;
var len=string.length;
if(len>5)
{
document.getElementById(id).innerHTML = string +" "+len;
highlight(string,id,begin,end);
}
else
{
document.getElementById(id).innerHTML = string;
}
}
</script>
</body>
</html>
I apologize again if this is extremely obvious but I'm honestly not sure what I'm doing wrong. Thanks in advance for any help!
You can get the name of the textbox by the attribute
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
And then use it in your function as
var x = document.getElementsByTagName("INPUT")[0].getAttribute("name");
function highlight(x,id,begin,end) {
// document.getElementById("error").innerHTML = "TEST";
var inputText = document.getElementById(id);
var innerHTML = inputText.innerHTML;
var index = innerHTML.indexOf(text)+begin;
if (index >= 0) {
innerHTML = innerHTML.substring(0,index) + "<span class='highlight'>" + innerHTML.substring(index,index+text.length) + "</span>" + innerHTML.substring(index + text.length-end);
inputText.innerHTML = innerHTML;
return string;
}
}
NOTE : By [0] it means the first one that is the first textbox.

How to make elements appear only when button is clicked in javascript

I'm trying to get answer to display when I press the Show Button but I can't get it to work. Could someone help me understand what I am doing wrong. I can get the first part to work where I generate a random integer. But the second part does not execute (JSFiddle).
<!DOCTYPE html>
<html>
<body>
<button class="button" onclick="disp()">Generate</button>
<button class="button" onclick="show_ans()">Show</button>
<script>
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
var j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}
}
</script>
<p> Random Integer:
<span id="Goal"></span>
</p>
<p> Computed Answer:
<span id="answer"></span>
</p>
</body>
</html>
show_ans only exists within the scope of the disp function, so anything outside that scope (such as the rest of the page) can't invoke it.
Move it outside that function:
function disp() {
//...
}
function show_ans() {
//...
}
Of course, since show_ans also relies on j, that too will need to exist in a scope where both functions can access it:
var j;
function disp() {
var i = Math.floor((Math.random() * 51) + 1);
j = 2 * i;
document.getElementById("Goal").innerHTML = [i];
}
function show_ans() {
document.getElementById("answer").innerHTML = [j];
}

Taking user input to create a unique object

I have been learning javascript for the past couple weeks and up until now I have been utilizing procedural programming to create my documents. I'm currently learning object-oriented programming, and while I know some java, it's been a while and I'm having trouble with these finicky objects. I want to take user input for a face value and suit of a card and use that data to instantiate an object from a constructor function. I know there are easier ways to do this but that would defeat the purpose of the lesson I'm trying to learn. Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>Card Constructor</title>
<h1 style="text-align:center">Create a playing card!</h1>
<script>
function Card(){
this.face=" ";
this.suit=" ";
this.info="You made a "+face+" of "+suit"!";
this.showInfo=function(){
alert(this.info);
}
this.setFace=function(newFace){
this.face=newFace;
}
this.setSuit=function(newSuit){
this.suit=newSuit;
}
}
function userCard(){
var goodCard=new Card();
goodCard.setFace=document.getElementById('faceInput').value=this.face;
goodCard.setSuit= document.getElementById('suitInput').value=this.suit;
goodCard.showInfo();
document.getElementById('faceInput').value=" ";
document.getElementById('suitInput').value=" ";
}
</script>
</head>
<body style="text-align: center">
<p>Please enter a face</p>
<input type="text" id="faceInput" name="face" value=" "/>
<p>And now a suit</p>
<input type="text" id="suitInput" name="suit" value=" "/></br>
</br><input type="button" value="Go!" onClick="userCard()"/>
</body>
Now, the problem is that my button doesn't work. If change my onClcik to onClick=alert('you clicked') I get a response. So I know I must have screwed something up in my script. Can anyone help a noob out?
For anyone curious on how I ended up getting this to work, or if you have an assignment in your textbook that calls for creating objects with set methods and you're stuck, this is how I ended up doing mine. Note: I have two set methods that modify my one info method.
<html>
<head>
<title>Card Constructor</title>
<h1 style="text-align:center">Create a playing card!</h1>
<script>
function Card(face, suit){
this.face="";
this.suit="";
this.info=face+" "+suit;
this.setFace=function(newFace){
this.face=newFace;
}
this.setSuit=function(newSuit){
this.suit=newSuit;
}
this.showInfo=function(){
this.info="You made a "+this.face+" of "+this.suit+"!";
alert(this.info);
}
}
function userCard(){
var goodCard=new Card();
goodCard.setFace(document.getElementById('faceInput').value);
goodCard.setSuit(document.getElementById('suitInput').value);
goodCard.showInfo();
document.getElementById('faceInput').value="";
document.getElementById('suitInput').value="";
}
</script>
</head>
<body style="text-align: center">
<p>Please enter a face</p>
<input type="text" id="faceInput" name="face" value=""/>
<p>And now a suit</p>
<input type="text" id="suitInput" name="suit" value=""/></br>
</br><input type="button" value="Go!" onClick="userCard()"/>
</body>
</html>
replace your javascript code:
UPDATED:
1.There is your code has optimized.
Your this.face and this.suit is public variable, so there are this.setFace and `this.setSuit' unnecessary methods.
You just write goodCard.face = ... and goodCard.suit = ... instead of addressing to method
function Card(faceVal, suitVal) {
this.face = faceVal;
this.suit = suitVal;
this.info = "";
this.showInfo = function () {
this.info = "You made a " + this.face + " of " + this.suit + "!";
alert(this.info);
}
}
function userCard() {
var goodCard = new Card(document.getElementById('faceInput').value, document.getElementById('suitInput').value);
goodCard.showInfo();
document.getElementById('faceInput').value = "";
document.getElementById('suitInput').value = "";
}
2.Also, I suggest other way to declare Card function.
There are private variables, getter/setter(also, you can use only setters or getters) as well as other public methods(like java class).
function Card(faceVal, suitVal) {
//private variables
var _face = faceVal || "",
_suit = suitVal || "",
_info = "";
Object.defineProperties(this, {
//region <Getter & Setter>
face: {
get: function () {
return _face;
},
set: function (val) {
_face = val;
},
enumerable: true
},
suit: {
get: function () {
return _suit;
},
set: function (val) {
_suit = val;
},
enumerable: true
},
info: {
get: function () {
return _info;
},
set: function (val) {
_info = val;
},
enumerable: true
}
});
//other public methods
this.showInfo = function () {
_info = "You made a " + _face + " of " + _suit + "!";
alert(_info);//or alert(this.info)
}
}
var goodCard = new Card();//you can define object outside without params
function userCard() {
goodCard.face = document.getElementById('faceInput').value;
goodCard.suit = document.getElementById('suitInput').value;
goodCard.showInfo();
document.getElementById('faceInput').value = "";
document.getElementById('suitInput').value = "";
}

JavaScript: Can I declare a variable by querying which function is called? (Newbie)

I'm working with an existing JavaScript-powered cart module that I am trying to modify. I do not know JS and for various reasons need to work with what is already in place.
The text that appears for my quantity box is defined within an existing function:
function writeitems() {
var i;
for (i=0; i<items.length; i++) {
var item=items[i];
var placeholder=document.getElementById("itembuttons" + i);
var s="<p>";
// options, if any
if (item.options) {
s=s+"<select id='options"+i+"'>";
var j;
for (j=0; j<item.options.length; j++) {
s=s+"<option value='"+item.options[j].name+"'>"+item.options[j].name+"</option>";
}
s=s+"</select> ";
}
// add to cart
s=s+"Quantity: <input id='quantity"+i+"' value='1' size='3'/> ";
s=s+"<input type='submit' value='Add to Cart' onclick='addtocart("+i+"); return false;'/></p>";
}
placeholder.innerHTML=s;
}
refreshcart(false);
}
I have two different types of quantity input boxes; one (donations) needs to be prefaced with a dollar sign, and one (items) should be blank.
I've taken the existing additem function, copied it, and renamed it so that there are two identical functions, one for items and one for donations. The additem function is below:
function additem(name,cost,quantityincrement) {
if (!quantityincrement) quantityincrement=1;
var index=items.length;
items[index]=new Object;
items[index].name=name;
items[index].cost=cost;
items[index].quantityincrement=quantityincrement;
document.write("<span id='itembuttons" + index + "'></span>");
return index;
}
Is there a way to declare a global variable based on which function (additem or adddonation) is called so that I can add that into the writeitems function so display or hide the dollar sign as needed? Or is there a better solution?
I can't use HTML in the body of the cart page because of the way it is currently coded, so I'm depending on the JS to take care of it.
Any help for a newbie is welcome. Thanks!
UPDATE 3/22:
Ok, I've edited the .js file as such:
var items=new Array;
var cart=new Array;
var isDonation=false;
function additem(name,cost,quantityincrement) {
var isDonation=false;
if (!quantityincrement) quantityincrement=1;
var index=items.length;
items[index]=new Object;
items[index].name=name;
items[index].cost=cost;
items[index].quantityincrement=quantityincrement;
document.write("<span id='itembuttons" + index + "'></span>");
return index;
}
function adddonation(name,cost,quantityincrement) {
var isDonation=true;
if (!quantityincrement) quantityincrement=1;
var index=items.length;
items[index]=new Object;
items[index].name=name;
items[index].cost=cost;
items[index].quantityincrement=quantityincrement;
document.write("<span id='itembuttons" + index + "'></span>");
return index;
}
...
function writeitems() {
var i;
for (i=0; i<items.length; i++) {
var item=items[i];
var placeholder=document.getElementById("itembuttons" + i);
var s="";
// options, if any
if (item.options) {
s=s+"<select id='options"+i+"'>";
var j;
for (j=0; j<item.options.length; j++) {
s=s+"<option value='"+item.options[j].name+"'>"+item.options[j].name+"</option>";
}
s=s+"</select> ";
}
// add to cart
if (!isDonation) {
s=s+"<input id='quantity"+i+"' size='3' type='hidden'/>";
s=s+"<input type='submit' value='Add to Cart' onclick='addtocart("+i+"); return false;'/><br /><br />";
}
else {
s=s+"$<input id='quantity"+i+"' size='3'/>.00 ";
s=s+"<input type='submit' value='Add to Cart' onclick='addtocart("+i+"); return false;'/><br /><br />";
}
placeholder.innerHTML=s;
}
refreshcart(false);
}
The resulting page isn't differentiating between the additem and adddonation functions is the output. Changing if/else statement to isDonation=true changes all output universally, and isDonation=false changes likewise, but also universally.
I'm at a complete loss.
It's pretty ugly, but you could solve this by having a global variable isDonation. Set this at the beginning of your additem to false, and to true in adddonation. Then in the writeitems function you can check the value and use it to condition your output.

variables in javascript

I have two arrays sd[16][16] and gd[16][16] in javascript. I need to compare the values of the arrays.
var score=0;
document.write("<table>");
for(c1=0; c1<16; c1++)
{ document.write("<tr>");
for(c2=0; c2<16; c2++)
document.write("<td onClick='changeColor(this);'>" + gd[c1][c2] + "</td>");
document.write("</tr>");
}
document.write("</table>");
function changeColor(tdd)
{
if(tdd.bgColor=='white')
{
tdd.bgColor='red';
if (gd[c1][c2] == sd[c1][c2])
score+=5;
else
score-=2;
}
else
{
tdd.bgColor='white';
}
}
However, when I try to display the score later, the score is not displayed.
function scc()
{
document.getElementById('scf').innerHTML = score;
}
</script>
<br><br><center><button type='button' onclick='scc()'> Click to see current score</button> <p id="scf">0</p> </center>
<br><br> <center><input type="submit" value="Get Solution"/></center>
Could someone please tell me what I am doing wrong?
It's a little more work but you could use a closure to keep the score variable isolated.
var score = (function () {
var currentScore = 0;
return {
getScore: function() { return currentScore; },
updateScore: function(change) { currentScore += change; }
}
})()
and then you can get/set the score like this: score.getScore(); and score.updateScore(5); score.updateScore(-4)
This way you don't have to worry about stepping on your score accidentally.
You have forgotten to initialize the score-variable. Now you have the problem your score is only available in the changeColor-function. You can define a score-variable outside all the functions, so that it's available everywhere:
<script type="text/javascript">
var score = 0;
document.write ...
</script>

Categories