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.
Related
let plus_btns = document.querySelectorAll('#plus-button');
let minus_btns = document.querySelectorAll('#minus-button');
let qty_inputs = document.querySelectorAll('#quantity');
plus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
qty_inputs.forEach(qty=>{
qty.value++
})
})
})
minus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
qty_inputs.forEach(qty=>{
if(qty.value > 1){
qty.value--
}
else{
qty.value=0;
}
})
})
})
<div class="cart-totals">
<input type="button" value="-" id="minus-button" for="quantity">
<input type="number" id="quantity" value="1" min="0">
<input type="button" value="+" id="plus-button" for="quantity">
<input type="button" value="-" id="minus-button" for="quantity">
<input type="number" id="quantity" value="1" min="0">
<input type="button" value="+" id="plus-button" for="quantity">
</div>
How I can change value of specific quantity input ???
In my case click event triggers all inputs and change the value of each input.
Please guide me thanks.
This should do the trick.
let plus_btns = document.querySelectorAll('#plus-button');
let minus_btns = document.querySelectorAll('#minus-button');
let qty_inputs = document.querySelectorAll('#quantity');
plus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
btn.previousElementSibling.value++;
})
})
minus_btns.forEach(btn=>{
btn.addEventListener('click', ()=>{
btn.nextElementSibling.value = (btn.nextElementSibling.value == 0) ? 0 : btn.nextElementSibling.value - 1;
})
})
Use event delegation for a single generic document wide handler. Afaik for is not a valid attribute for input type 'button', so use a data-attribute. Furthermore: element id must be unique. Fixed all that in this demo snippet:
document.addEventListener("click", handle);
function handle(evt) {
if (evt.target.type === "button") {
return handleBtn(evt.target);
}
}
function handleBtn(btn) {
const elem = document.querySelector(`#${btn.dataset.for}`);
const nwValue = +elem.value + (btn.value === "-" ? -1 : 1);
elem.value = nwValue >= +elem.min ? nwValue : elem.min;
}
<div class="cart-totals">
<input type="button" value="-" data-for="quantity1">
<input type="number" id="quantity1" value="1" min="0">
<input type="button" value="+" data-for="quantity1">
<input type="button" value="-" data-for="quantity2">
<input type="number" id="quantity2" value="1" min="1">
<input type="button" value="+" data-for="quantity2">
</div>
Using a single event handler:
var cart = document.querySelector('.cart-totals');
cart.addEventListener('click', function(ev) {
var tgt = ev.target;
if (tgt.matches('input[type="button"]')) {
var input = document.getElementById(tgt.dataset.for);
var currentValue = +input.value;
var minValue = +input.min;
if (tgt.value === '+') {
input.value = currentValue + 1;
}
else if (currentValue > minValue) {
input.value = currentValue - 1;
}
}
});
<div class="cart-totals">
<input type="button" value="-" data-for="quantity1">
<input type="number" id="quantity1" value="1" min="0">
<input type="button" value="+" data-for="quantity1">
<input type="button" value="-" data-for="quantity2">
<input type="number" id="quantity2" value="5" min="2">
<input type="button" value="+" data-for="quantity2">
</div>
I am trying to read the value from an input text, and make all the math operations at once
I have gotten to calculate one operation such as 25+67 but I cannot make to read and split more complex operations such as 50+5*5, I do not know how to get the different values and make operations one by one, I have tried creating a loop using split everytime it finds something different than a number but it is not working
Where screen is the id of the input where you can write down all the numbers and operations you like
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="js/data.js"></script>
<title>Calculator</title>
</head>
<body>
<div class="mycalc">
<form name="calculator" id="calculator" class="cuerpo">
<h2 class="casio">CASIO</h2>
<input type="text" name="screen" id="screen" readonly>
<div>
<input type="button" id="one" value="1" onclick="takeValue(1)">
<input type="button" id="two" value="2" onclick="takeValue(2)">
<input type="button" id="three" value="3" onclick="takeValue(3)">
<input type="button" id="add" value="+" onclick="takeValue('+')">
</div>
<div>
<input type="button" id="four" value="4" onclick="takeValue(4)">
<input type="button" id="five" value="5" onclick="takeValue(5)">
<input type="button" id="six" value="6" onclick="takeValue(6)">
<input type="button" id="sus" value="-" onclick="takeValue('-')">
</div>
<div>
<input type="button" id="seven" value="7" onclick="takeValue(7)">
<input type="button" id="eight" value="8" onclick="takeValue(8)">
<input type="button" id="nine" value="9" onclick="takeValue(9)">
<input type="button" id="mul" value="*" onclick="takeValue('*')">
</div>
<div>
<input type="button" id="zero" value="0" onclick="takeValue(0)">
<button type="button" id="clear" value="" onclick="clearInput()">AC</button>
<input type="button" id="zero" value="="onclick="prueba()">
<input type="button" id="div" value="/" onclick="takeValue('/')">
</div>
</form>
</div>
</body>
</html>
function checkOperation(num1,num2, oper){
let res;
switch(oper){
case "+":
res = parseInt(num1) + parseInt(num2);
break;
case "-":
res = parseInt(num) + parseInt(num2);
break;
case "*":
res = parseInt(num1) + parseInt(num2);
break;
case "/":
res = parseInt(num1) + parseInt(num2);
break;
}
return res;
}
function prueba(){
let actual = document.getElementById('screen').value;
let arr = [];
let res = 0;
let res1 = 0;
let temp;
for(let i = 0; i < actual.length; i++){
if(isNaN(actual[i])){
let oper1 = actual[i];
arr = actual.split(oper1);
temp = arr[1];
for(let j = 0; j < temp.length; j++){
if(isNaN(temp[j])){
let oper2 = temp[j];
let num1 = temp[0];
let num2 = temp[1];
res = checkOperation(num1, num2, oper2)
}
}
res1 = checkOperation(parseInt(temp), res, oper1)
}
}
document.getElementById('screen').value = res1;
}
You can try using JavaScript's eval() function.
const a = eval('25+67');
const b = eval('50+5*5');
console.log(a);
console.log(b);
However, do note that there are various security risks involved when using that function, hence you should be careful when it comes to using it on production code.
function addData (n1, n2) {
alert(fn+ln);
}
<body>
<input Type="text" name="n1">
<input Type="text" name="n2">
<button onClick="addData(n1.value,n2.value)">click</button>
</body>
its give me the following error:
ReferenceError: n1 is not defined.
You cannot get the value of the input by using n1.value You need to obtain the DOM element using document.getElementById and use its value to obtain the string value and parse it as Integer before you add them.
See this:
function addData (n1, n2) {
n1Val = parseInt(n1.value);
n2Val = parseInt(n2.value);
alert(n1Val+n2Val);
}
<body>
<input Type="text" id="n1">
<input Type="text" id="n2">
<button onClick="addData(document.getElementById('n1'), document.getElementById('n2'))">click</button>
</body>
If you want to merely concatenate the data and not add it, just remove the parseInt call and add the strings like in the following example:
function addData (n1, n2) {
n1Val = n1.value;
n2Val = n2.value;
alert(n1Val+n2Val);
}
<body>
<input Type="text" id="n1">
<input Type="text" id="n2">
<button onClick="addData(document.getElementById('n1'), document.getElementById('n2'))">click</button>
</body>
Hope it helps!!
Do like this way:
function addData (e) {
var rec = 0;
var t = document.getElementsByTagName('input');
for(var i=0;i<t.length;i++){
rec=rec+parseInt(t[i].value);
}
console.log(rec);
}
<script>
</script>
<body>
<input Type="text" name="n1">
<input Type="text" name="n2">
<button onClick="addData(this)">click</button>
</body>
<html>
<head>
<title>Input tutorial</title>
<script language="javascript">
function addNumbers()
{
var val1 = parseInt(document.getElementById("value1").value);
var val2 = parseInt(document.getElementById("value2").value);
var ansD = document.getElementById("answer");
var final = val1 + val2;
alert(final);
}
</script>
</head>
<body>
value1 = <input type="text" id="value1" name="value1" value="1" /> value2 = <input type="text" id="value2" name="value2" value="2" />
<input type="button" name="Sumbit" value="Click here" onclick="javascript:addNumbers()" />
</body>
</html>
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.
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>