Javascript Calculator Memory function - javascript

Here is my HTML
<script type="text/javascript" src="./The Desktop Calculator_files/calc.js"></script>
<style type="text/css"></style>
</head>
<body onLoad="checkBrowser()">
<form id="calcForm">
<div id="calc">
<input type='hidden' id='param1' value='0' />
<input type='hidden' id='operator' value='' />
<div id="display">
<input type="text" name="disp" id="disp" class="disp" size="36" value="0">
</div>
<div id="buttons">
<div class="row">
<input type="button" value="7" onclick="isNum();appendMe(this.value)">
<input type="button" value="8" onclick="isNum();appendMe(this.value)">
<input type="button" value="9" onclick="isNum();appendMe(this.value)">
<input type="button" value="/" onClick="isNum();setOp(this.value)">
<input type="button" value="CE">
</div>
<div class="row">
<input type="button" value="4" onclick="isNum();appendMe(this.value)">
<input type="button" value="5" onclick="isNum();appendMe(this.value)">
<input type="button" value="6" onclick="isNum();appendMe(this.value)">
<input type="button" value="*" onClick="isNum();setOp(this.value)">
<input type="button" value="C" onclick="clearAll()">
</div>
<div class="row">
<input type="button" value="1" onclick="isNum();appendMe(this.value)">
<input type="button" value="2" onclick="isNum();appendMe(this.value)">
<input type="button" value="3" onclick="isNum();appendMe(this.value)">
<input type="button" value="-" onClick="isNum();setOp(this.value)">
<input type="button" value="M" onClick="isNum();set_getMem()">
</div>
<div class="row">
<input type="button" value="0" onclick="isNum();appendMe(this.value)">
<input type="button" value="+/-" onclick="isNum();plusMinus()">
<input type="button" value="." onclick="isNum();appendMe(this.value)">
<input type="button" value="+" onClick="isNum();setOp(this.value)">
<input type="button" value="=" onClick="isNum();calcMe()">
</div>
</div>
<div id='warning'>Your Browser Can't Handle The Truth!</div>
</div>
</form>
</body></html>
Here is my JavaScript
function appendMe(val)
{
//alert(val);
//document.getElementById("disp").value+=val;
//alert(val);
if(document.getElementById("disp").value=='0')
{
document.getElementById("disp").value=val;
}
else if(val=='.' && document.getElementById("disp").value.indexOf('.')>-1) //do nothing, because we already have a decimal point
{
}
else //in any other case, we just append
{
document.getElementById("disp").value+=val;
}
}
function clearAll()
{
//alert(val);
document.getElementById("disp").value=0;
}
function checkBrowser()
{
alert("checking");
document.getElementById("warning").style.display="none";
}
function plusMinus()
{
document.getElementById("disp").value=(document.getElementById("disp").value*-1);
}
function setOp(val)
{
//first, set aside the initial value as entered
document.getElementById("param1").value=document.getElementById("disp").value;
//next, clear out that first number entered
document.getElementById("disp").value=0;
//finally, store the operation
document.getElementById("operator").value=val;
}
function calcMe()
{
var param1 = document.getElementById("param1").value;
var operator = document.getElementById("operator").value;
var param2 = document.getElementById("disp").value;
document.getElementById("disp").value = eval(param1+operator+param2);
}
function isNum()
{
//start as true
var isN = true;
if(isNaN(document.getElementById("disp").value))
{
isN=false;
alert("Non-numeric Data!");
}
return isN;
}
function set_getMem()
{
var memvalue;
//{
//isNum()
//}
if(memvalue == null ) //nothing in there, so set it
{
memvalue = document.getElementById("disp").value;
}
else //something in there, so display it
{
document.getElementById("disp").value = memvalue;
}
}
The part I am having problems with is getting the M button to function properly. What I want to happen is that I can click M and it will save whatever is in the display except when there is already a number stored I want it to display that number.
Currently I click the M button and it doesn't appear to save a number or display a number.
Edited: Based on feedback I got the Memory function to work but now I need a function that can clear the value of the global variable.
function clear_All()
{
var memvalue=0;
document.getElementById("disp").value=0;
var param1=0;
var param2=0;
}
When I put the memvalue to 0 in the function it doesnt clear it from memvalue. When I put it outside the function it just breaks the storing capabilities of the memvalue.

Here might be the problem:
function set_getMem()
{
var memvalue;
You define memvalue as a local variable inside set_memGet(), therefore this variable is gone once the function returns.
Define this variable out of the function.

Related

How can I delete an element in an object?

I have a checkbox which add an id of his value in array when checked and I want to delete this value when I uncheck it
I tried to remove my id with and indexOf() + splice() but I can't use indexOf() because I'm using an object
Some one have an idea to how can I delete my id when I uncheck my checkbox,
or if there is a trick to use indexOf with an object?
there is my script :
$(document).ready(function() {
const formInputIds = $('form#export input[name="ids"]');
$('.exportCheckbox:checkbox').on('change', function() {
const announceId = $(this).data('id');
if (this.checked) {
formInputIds.push(announceId);
console.log(formInputIds);
} else {
const index = formInputIds.val().indexOf(announceId);
if (index > -1) {
formInputIds.val().splice(index, 1);
}
console.log(formInputIds);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<some data of product displayed>
<input type="checkbox" data-id="{{annonce._id}}" class="exportCheckbox"/>
there is the console.log of formInputIds with 3 ids :
Consider the following.
$(function() {
var formInputIds;
function getChecked(target) {
var results = [];
$("input[type='checkbox']", target).each(function(i, elem) {
if ($(elem).is(":checked")) {
results.push($(elem).data("id"));
}
});
return results;
}
$('.exportCheckbox').on('change', function(event) {
formInputIds = getChecked($(this).parent());
console.log(formInputIds);
});
$("#export").submit(function(event) {
event.preventDefault();
console.log(formInputIds);
$("[name='ids']", this).val("[" + formInputIds.toString() + "]");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="export" action="exportAnnounces">
<input type="hidden" name="ids" value="[]" />
<button type="submit" class="btn btn-primary">Download</button>
</form>
<div class="some content">
<input type="checkbox" data-id="1001" class="exportCheckbox" />
<input type="checkbox" data-id="1002" class="exportCheckbox" />
<input type="checkbox" data-id="1003" class="exportCheckbox" />
<input type="checkbox" data-id="1004" class="exportCheckbox" />
<input type="checkbox" data-id="1005" class="exportCheckbox" />
<input type="checkbox" data-id="1006" class="exportCheckbox" />
</div>
This way, you build the Array based on just the checked items. No need to find and slice the exact item.

How to apply click event on respective div containing same child and class name

Two div having class name container containing same elements with same class name. Apply Jquery when that respective children are clicked.
HTML CODE
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
I have written Some scripts, which will hide negative input and display None when value is 0, positive input will increase a value
$(document).ready(function() {
var counter = 1;
if ($('.qty').val() === 0 || $('.qty').val() === '') {
$('.qty').hide();
$('.txt').show();
$('.negative').hide();
} else {
$('.txt').hide();
$('.qty').show();
$('.negative').show();
}
$('.positive').click(function() {
$('.negative').show();
$('.qty').show();
$('.txt').hide();
const qty = $('.qty').val();
$('.qty').val(counter);
counter++;
});
$('.negative').click(function() {
const qty = $('.qty').val();
if (qty > 1) {
counter--;
$('.qty').val(counter);
} else {
counter = 1;
$('.negative').hide();
$('.txt').show();
$('.qty').hide();
}
});
});
I am not sure how to use $(this) in above code.
I am beginner in JS and I know this code is not efficient.
If possible make it efficient.
Thank you!!!
I'm doing this in the code below by using .parent().find(). This can be brittle though if you rearrange your layout, so just be careful with it. You'd be better off giving a data attribute to the elements and modifying them that way.
$(document).ready(function() {
$("input").click(function() {
let clickAction = $(this).val();
console.log($(this).val());
let displayElement = $(this).parent().find("input.qty");
let currentval = +$(displayElement).val();
//you could use eval to make this look cleaner, but eval is often frowned upon
if (clickAction == "+") {
currentval++;
} else if (clickAction == "-") {
currentval--
}
$(displayElement).val(currentval);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="0">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>
<div class="container">
<input type="button" class="negative" value="-">
<input type="button" class="qty" value="0">
<span class="txt">None</span>
<input type="button" class="positive" value="+">
</div>

How can I make this calculator work

I am having trouble, as you can see in code, for the result3 as id i have op1, what I would like to have there so that it works is that id changes depending on the button pressed, how can I do that? because now every button is like a +.
<!DOCTYPE html>
<html>
<head>
<title>Hello!</title>
</head>
<script>
function getResult()
{
var result1 = document.getElementById("number1").value;
var result3 = document.getElementById ("op1").value;
var result2 = document.getElementById("number2").value;
calculate (result1,result3,result2);
}
function calculate(num1,operator,num2)
{
if (operator== '+')
{
var res1 = parseFloat(num1)+parseFloat(num2);
alert(res1);
}
else if (operator== '-')
{
var res2 = parseFloat(num1)-parseFloat(num2);
alert(res2);
}
else if (operator== '*')
{
var res3 = parseFloat(num1)*parseFloat(num2);
alert(res3);
}
else if (operator== '/')
{
var res4 = parseFloat(num1)/parseFloat(num2);
alert(res4);
}
else
{
alert("Nothing from above!");
}
}
</script>
<body>
<form action="get" method="#">
<input type="text" name="text1" value="" id="number1" /> <br/>
<input type="text" name="text2" value="" id="number2" /> <br/>
<input type="button" name="o1" value="+" id="op1" onclick="getResult();"/>
<input type="button" name="o2" value="-" id="op2" onclick="getResult();"/>
<input type="button" name="o3" value="*" id="op3" onclick="getResult();"/>
<input type="button" name="o4" value="/" id="op4" onclick="getResult();"/>
<input type="button" name="calc" value="Calculate" onclick="getResult();"/>
</form>
</body>
</html>
You are always calling the value of input with id="op1", which is + in your case. Why not pass the value?
getResult(id) {
var result1 = document.getElementById("number1").value;
var result3 = document.getElementById (id).value;
var result2 = document.getElementById("number2").value;
calculate (result1,result3,result2);}
The id is passed when calling the function:
<input type="button" name="o1" value="+" id="op1" onclick="getResult(id);"/>
<input type="button" name="o2" value="-" id="op2" onclick="getResult(id);"/>
<input type="button" name="o3" value="*" id="op3" onclick="getResult(id);"/>
<input type="button" name="o4" value="/" id="op4" onclick="getResult(id);"/>
Calculate button won't work this way, but this is a quick fix with your setup. Good luck.

PHP code not working in a Form which is used for javascript

I am working with a form which uses Javascript for a process. When i try to read the textbox value in form with PHP, It's not showing output.
My code is
HTMLCode is
<form class="form-inline" method="POST" action="staff.php" onSubmit=" return questiontable()" >
<div class="form-group">
<label for="qscount">Number of Questions: </label>
<input type="number" name="qscount" class="form-control" id="qscount" style="width:150px;" placeholder="No of questions"> <br>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary" id="gobtn" onClick="return disable()" >Go</button> <br>
<p id="btnhide"> </p>
</div>
</form>
Javascript is
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
return false;
}
</script>
PHP Code is
<?php
if (isset($_POST['qscount'])){
echo $_POST['qscount'];
}
?>
I want to use this qscount value in another php page. How to get this textbox value in PHP and use it in another page ?
Javascript function() should return true, since you are using return function() in onclick attribute of button type=submit
<script type="text/javascript">
function questiontable()
{
var qs = document.getElementById("qscount").value;
var count;
for(count=1; count<=qs; count++)
{
document.getElementById("demo").innerHTML += '<br><font style="font-size: 20px">'+ count+'. <input class="textboxtest" style="width:850px;" type="text" name=" q'+ count +' " placeholder="Question "><br>' ;
document.getElementById("demo").innerHTML +='<br><input style="margin-left: 25px;" type="radio" name="a'+count+'" value="c1"> <input class="testbox" type="text" name="o'+count+'1" placeholder="Option 1">';
}
return true;
}
</script>
This will continue the form posting onclick of the button
If you are trying to create the number of questions on click dynamically using javascript,
then use syntax to call questionTable
<button type="button" class="btn btn-primary" id="gobtn" onClick="javascript:return questiontable()" >Create Questions</button>
Remove
onSubmit=" return questiontable()"
from the form
Now when the question table is rendered, please show the button type="submit"
<button type=submit value="Go" name="cmdGo">Go</button>
to trigger form submission
Hope it helps!

JavaScript: How to disable buttons after clicking

Hi I have a question how can I upgrade my script that it can disable remaining buttons after you pressed five of them? Now it only count them.
My code:
<input type="Button" onclick="window.increment(event)" value="2"/>
<input type="Button" onclick="window.increment(event)" value="3"/>
<input type="Button" onclick="window.increment(event)" value="4"/>
<input type="Button" onclick="window.increment(event)" value="5"/>
<input type="Button" onclick="window.increment(event)" value="6"/>
<input type="Button" onclick="window.increment(event)" value="7"/>
<input type="Button" onclick="window.increment(event)" value="8"/>
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
Link to js:
https://jsfiddle.net/57js0ps7/6/
Here's as little as possible edited code that works but isn't that readable.
https://jsfiddle.net/90yw1buf/
HTML
<input type="Button" class="bt" onclick="window.increment(event)" value="1"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="2"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="3"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="4"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="5"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="6"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="7"/>
<input type="Button" class="bt" onclick="window.increment(event)" value="8"/>
<div>
<p>You've choose <a id="clicks">0</a> slot/s.</p>
</div>
JS
window.increment = function(event) {
var btn = event.target;
btn.clicks = ((btn.clicks || 0) + 1) % 2;
window.clicks = (window.clicks || 0) + btn.clicks * 2 - 1;
document.getElementById("clicks").innerText = window.clicks;
var buttons = document.getElementsByClassName("bt");
var i;
if(window.clicks > 4) {
for (i = 0; i < buttons.length; i++) {
if(buttons[i].clicks != 1) {
buttons[i].disabled = true;
} else {
buttons[i].disabled = false;
}
}
} else {
for (i = 0; i < buttons.length; i++) {
buttons[i].disabled = false;
}
}
}
Try not to pollute the global scope (window) because it's a space that all the scripts on your page share, and you should keep shared space clean because you don't know what other scripts might assign a global variable called "click". Read up on closures and scope for some good ideas on how to avoid putting things in the global scope.
You should use classes instead of IDs because IDs must be unique, but classes don't have to be.
It's better to use addEventListener to put event listeners on your elements because an element can only have a single "onclick" function but they can have as many event listeners as they need.
Finally, don't use an anchor (<a>) tag unless it's intended to be clickable, and if it is, you need to include an href attribute`.
(function(){
var clicks = 0;
var buttons = Array.from(document.getElementsByClassName("bt"));
buttons.forEach(btn=>{
btn.addEventListener("click", ()=>{
clicks++;
document.getElementById("clicks").innerText = clicks;
btn.disabled = true;
if(5 === clicks) buttons.forEach(b=>b.disabled = true);
}, false)
});
})();
<input type="Button" class="bt" value="2"/>
<input type="Button" class="bt" value="3"/>
<input type="Button" class="bt" value="4"/>
<input type="Button" class="bt" value="5"/>
<input type="Button" class="bt" value="6"/>
<input type="Button" class="bt" value="7"/>
<input type="Button" class="bt" value="8"/>
<div>
<p>You've choose <span id="clicks">0</span> slot/s.</p>
</div>
I think this is what you are looking for?
var clickedCount = 0;
var arr = [0,0,0,0,0,0,0,0];
function count (buttonNo) {
if (arr[buttonNo-1] == 0) {
clickedCount ++;
arr[buttonNo-1] = 1
}
if (clickedCount >=5) {
var buttons = document.getElementsByTagName('button');
for (var i=0; i < buttons.length; i++) {
if(arr[i]==0){
buttons[i].disabled = 'disabled';
}
}
}
}
<div>
<button onclick="count(1)">button1</button>
<button onclick="count(2)">button2</button>
<button onclick="count(3)">button3</button>
<button onclick="count(4)">button4</button>
<button onclick="count(5)">button5</button>
<button onclick="count(6)">button6</button>
<button onclick="count(7)">button7</button>
<button onclick="count(8)">button8</button>
</div>

Categories

Resources