Javascript Calculator on PopUp problem with display value - javascript

I have an HTML calculator in a pop up. Everytime i open it the first time the calculations are correct. if i hide the pop up and open it again when i press 6 instead of 6 it shows 66. and if i close it again and open it if i press 5 it shows 555 and etc. Here is my code:
Snippet:
var calculator = document.querySelector('#calculator3');
var keys = calculator.querySelector('#calculator-keys3');
var num="";
keys.addEventListener('click', e => {
if (e.target.matches('button')) {
var key = e.target;
var action = key.dataset.action;
var keyContent = key.textContent;
if (!action) {
num = num + keyContent;
document.getElementById("displayPayment").innerHTML = "num";
}
if (action === 'backspace') {
num = num.slice(0, -1);
document.getElementById("displayPayment").innerHTML = "num";
}
if (action === 'decimal') {
num = num + ".";
}
}
});
<div class="calculator" id="calculator3">
<div class="calculator-keys" id="calculator-keys3">
<button type="button" value="1">1</button>
<button type="button" value="2">2</button>
<button type="button" value="3">3</button>
<button type="button" value="4">4</button>
<button type="button" value="5">5</button>
<button type="button" value="6">6</button>
<button type="button" value="7">7</button>
<button type="button" value="8">8</button>
<button type="button" value="9">9</button>
<button type="button" class="key--operator" data-action="add">+/-</button>
<button type="button" value="0">0</button>
<button type="button" data-action="decimal" value=",">,</button>
<button type="button" class="equal-sign" data-action="backspace" value="del"></button>
</div>
</div>

You need to unbind the event listener first removeEventListener() or check if it's already bound before adding the event listener.
var calculator = document.querySelector('#calculator3');
var keys = calculator.querySelector('#calculator-keys3');
var num="";
var eventListener = function(e) {
if (e.target.matches('button')) {
var key = e.target;
var action = key.dataset.action;
var keyContent = key.textContent;
if (!action) {
num = num + keyContent;
document.getElementById("displayPayment").innerHTML = "num";
}
if (action === 'backspace') {
num = num.slice(0, -1);
document.getElementById("displayPayment").innerHTML = "num";
}
if (action === 'decimal') {
num = num + ".";
}
}
}
keys.removeEventListener('click', eventListener);
keys.addEventListener('click', eventListener);
If you don't remove the first event, then a second event will be bound to the elements the second time you run this script.

you have to add another event when someone click on "closing the model button" and in this you have to clear all the previous values in html so next time someone open the model no previous value is present.

Related

i want to Set text-cursor to specific word(position given in below code) in a textarea?

My target is to click button and cursor will pop up on word assinged to given button. I have tried everything i can available online. but nothing worked. I'm in initial phase of learning javascript. I'm working on blog project and i need to insert extra code at this given postions thats why cursor need to set there. It will save time.
<script type="text/javascript">
function StringSearch(clicked_id)
{
if (clicked_id == 'top6-button-1') {
var SearchTerm = 'item-1-end' ;
// block of code to be executed if condition1 is true
} else if (clicked_id == 'top6-button-2') {
var SearchTerm = 'item-2-end' ;
// block of code to be executed if the condition1 is false and condition2 is true
} else if (clicked_id == 'top6-button-3') {
var SearchTerm = 'item-3-end' ;
// block of code to be executed if the condition1 is false and condition2 is false
} else if (clicked_id == 'top6-button-4') {
var SearchTerm = 'item-4-end' ;
} else if (clicked_id == 'top6-button-5') {
var SearchTerm = 'item-5-end' ;
} else if (clicked_id == 'top6-button-6') {
var SearchTerm = 'item-6-end' ;
} else {
var SearchTerm = 'comparing-list-end' ;
}
var TextSearch = document.getElementById("top6-initial-code").value;
if (SearchTerm.length > 0 && TextSearch.indexOf(SearchTerm) > -1) {
TextSearch.value = TextSearch.value + "\n";
TextSearch.setSelectionRange(TextSearch.value.length, TextSearch.value.length);
TextSearch.focus();
} else {
alert("No Data found in Text Area");
}
}
</script>
<textarea name="top6-initial-code" id="top6-initial-code" cols="165" rows="40" value="all words i want to put cursor there in textbox, its too big">
<button type="button" id="top6-button-1" onclick="StringSearch(this.id)">Item 1</button>
<button type="button" id="top6-button-2" onclick="StringSearch(this.id)">Item 2</button>
<button type="button" id="top6-button-3" onclick="StringSearch(this.id)">Item 3</button>
<button type="button" id="top6-button-4" onclick="StringSearch(this.id)">Item 4</button>
<button type="button" id="top6-button-5" onclick="StringSearch(this.id)">Item 5</button>
<button type="button" id="top6-button-6" onclick="StringSearch(this.id)">Item 6</button>
<button type="button" id="top6-button-7" onclick="StringSearch(this.id)">Comparison</button>

Calculator - click on a number the same number is displayed more than once

I'm doing a calculator project.
When I click on a number the same number is displayed more than once (only one click on each number).
for example, I click on 4, it displays the number 4 once because it was the first click, then I click on the number 1 then it displays the number 1 twice because it was the second number to be clicked.
The code: https://github.com/pittyh6/calculator
function calc() {
const calculator = document.querySelector(".calculator");
// All buttons is inside .calculator__keys.
const keys = document.querySelector(".calculator__keys");
const display = document.querySelector(".calculator__display");
// use an event delegation pattern to listen, since keys are all children of .calculator__keys.
keys.addEventListener("click", (e) => {
if (e.target.matches("button")) {
// use the data-action attribute to determine the type of key that is clicked.
const key = e.target;
const action = key.dataset.action;
// The number of the key that was clicked
const keyContent = key.textContent;
// The current displayed number
const displayedNum = display.textContent;
if (!action) {
console.log("number key!");
if (displayedNum === "0") {
display.textContent = keyContent;
console.log("key content " + keyContent);
} else {
display.textContent = displayedNum + keyContent;
console.log("key content " + keyContent);
}
} else if (
action === "add" ||
action === "subtract" ||
action === "multiply" ||
action === "divide"
) {
console.log("operator key");
// add the is-depressed class to the operator key
key.classList.add("is-depressed");
} else if (action === "decimal") {
console.log("decimal key");
display.textContent = displayedNum + ".";
} else if (action === "clear") {
console.log("clear key");
} else if (action === "calculate") {
console.log("equal key");
}
}
});
}
<body>
<div class="container">
<div class="calculator">
<div class="calculator__display">0</div>
<div class="calculator__keys" onclick="calc()">
<button class="key--operator" data-action="add">+</button>
<button class="key--operator" data-action="subtract">-</button>
<button class="key--operator" data-action="multiply">×</button>
<button class="key--operator" data-action="divide">÷</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>0</button>
<button data-action="decimal">.</button>
<button data-action="clear">AC</button>
<button class="key--equal" data-action="calculate">=</button>
</div>
</div>
</div>
</body>
Every time you click on one of the buttons, the calc function gets called, which adds an event listener to all the buttons. Therefore, with every click, you have one more listener on the button, thus calling the function multiple times. Choose whether you want to use onclick or an event listener.
One option would be to remove the onclick and move the code out of the function to fix your problem like so:
const calculator = document.querySelector(".calculator");
// All buttons is inside .calculator__keys.
const keys = document.querySelector(".calculator__keys");
const display = document.querySelector(".calculator__display");
// use an event delegation pattern to listen, since keys are all children of .calculator__keys.
keys.addEventListener("click", (e) => {
if (e.target.matches("button")) {
// use the data-action attribute to determine the type of key that is clicked.
const key = e.target;
const action = key.dataset.action;
// The number of the key that was clicked
const keyContent = key.textContent;
// The current displayed number
const displayedNum = display.textContent;
if (!action) {
console.log("number key!");
if (displayedNum === "0") {
display.textContent = keyContent;
console.log("key content " + keyContent);
} else {
display.textContent = displayedNum + keyContent;
console.log("key content " + keyContent);
}
} else if (
action === "add" ||
action === "subtract" ||
action === "multiply" ||
action === "divide"
) {
console.log("operator key");
// add the is-depressed class to the operator key
key.classList.add("is-depressed");
} else if (action === "decimal") {
console.log("decimal key");
display.textContent = displayedNum + ".";
} else if (action === "clear") {
console.log("clear key");
} else if (action === "calculate") {
console.log("equal key");
}
}
});
<body>
<div class="container">
<div class="calculator">
<div class="calculator__display">0</div>
<div class="calculator__keys">
<button class="key--operator" data-action="add">+</button>
<button class="key--operator" data-action="subtract">-</button>
<button class="key--operator" data-action="multiply">×</button>
<button class="key--operator" data-action="divide">÷</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>0</button>
<button data-action="decimal">.</button>
<button data-action="clear">AC</button>
<button class="key--equal" data-action="calculate">=</button>
</div>
</div>
</div>
</body>
You are adding an event listener Every time the buttons are clicked.
the event listener should be outside of function calc(). And remove the onclick since you are adding an event listener and don't need it.
const calculator = document.querySelector(".calculator");
// All buttons is inside .calculator__keys.
const keys = document.querySelector(".calculator__keys");
const display = document.querySelector(".calculator__display");
// use an event delegation pattern to listen, since keys are all children of .calculator__keys.
keys.addEventListener("click", (e) => {
if (e.target.matches("button")){
calc(e);
}
});
function calc(e){
// use the data-action attribute to determine the type of key that is clicked.
const key = e.target;
const action = key.dataset.action;
// The number of the key that was clicked
const keyContent = key.textContent;
// The current displayed number
const displayedNum = display.textContent;
if (!action) {
console.log("number key!");
if (displayedNum === "0") {
display.textContent = keyContent;
console.log("key content " + keyContent);
} else {
display.textContent = displayedNum + keyContent;
console.log("key content " + keyContent);
}
} else if (
action === "add" ||
action === "subtract" ||
action === "multiply" ||
action === "divide"
) {
console.log("operator key");
// add the is-depressed class to the operator key
key.classList.add("is-depressed");
} else if (action === "decimal") {
console.log("decimal key");
display.textContent = displayedNum + ".";
} else if (action === "clear") {
console.log("clear key");
} else if (action === "calculate") {
console.log("equal key");
}
}
<body>
<div class="container">
<div class="calculator">
<div class="calculator__display">0</div>
<div class="calculator__keys" onclick="">
<button class="key--operator" data-action="add">+</button>
<button class="key--operator" data-action="subtract">-</button>
<button class="key--operator" data-action="multiply">×</button>
<button class="key--operator" data-action="divide">÷</button>
<button>7</button>
<button>8</button>
<button>9</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>0</button>
<button data-action="decimal">.</button>
<button data-action="clear">AC</button>
<button class="key--equal" data-action="calculate">=</button>
</div>
</div>
</div>
</body>

Diable the button , enable button after another button clock

I want that until the Copy List To Below get clicked I want to disable to Save button.
Currently this is the Copy List To Below button
<button type="button" className={classes["copy-btn"] + " btn-cancel mt-3"} onClick={(event) => this.copyData(event)}>Copy List To Below {_.size(this.state.protestList) > 1 ? _.size(this.state.protestList) + " Groups" : 'Group'} </button>
And this is my Save button
<button type="submit" className={classes["save-btn"] + " btn-save"} onClick={(event) => this.saveData(event)}>Save</button>
And below is the respected functions
saveDate = (event, data) => {
if(event) {
//Do something
}
else {
//Return Error
}
}
copyData = (event, data) => {
if(event) {
//Do something
}
else {
//Return Error
}
}
As I said only if Copy is done then only save button should be able get clicked
Give two ids and add click event and toggle button disable property like this. Make it simple. Your buttons has unnecessary attributes, please remove those.
CORE JAVASCRIPT
<button type="button" id="coptBtn" class ="btn-cancel mt-3" >Copy List To Below</button>
<button id="saveBtn" type="submit" class="" >Save</button>
var coptBtn = document.getElementById('coptBtn');
var saveBtn = document.getElementById('saveBtn');
saveBtn.disabled = true;
coptBtn.addEventListener('click', (evt) => {
saveBtn.disabled = false;
});
REACT JS
var App = React.createClass({
getInitialState() {
return {isDisable: false}
},
handleClick(e) {
this.setState({isDisable: true})
},
render() {
return <div>
<button type="button" onClick={this.handleClick} >Copy List To Below</button>
<button type="button" disabled={!this.state.isDisable}>Save</button>
</div>
}
});
Try this code..
copyData() {
//your existing code
this.setState({copied: true})
}
<button type="submit" disable={!this.state.copied} className={classes["save-btn"] + " btn-save"} onClick={(event) => this.saveData(event)}>Save</button>

Retrieve unique value of a button

I have several buttons belonging to the same class. I want to retrieve the value of the button I click on.
Here is my code:
var battons = document.getElementsByClassName("converting_video");
var number_of_buttons = battons.length;
function actual_url() {
while (number_of_buttons > 0) {
for (i = 1; i <= number_of_buttons; i++) {
function getting_url() {
battons[i].addEventListener("click", video_url)
}
function video_url(url) {
alert(url);
}
}
}
}
var battons = document.getElementsByClassName("class_btns");
var number_of_buttons = battons.length;
function actual_url() {
while (number_of_buttons > 0) {
for (i = 1; i <= number_of_buttons; i++) {
function getting_url() {
battons[i].addEventListener("click", video_url)
}
function video_url(url) {
alert(url);
}
}
}
}
<button class="class_btns" value='1'> results </button>
<button class="class_btns" value='2'> results </button>
<button class="class_btns" value='3'> results </button>
<button class="class_btns" value='4'> results </button>
This will allow you to get the value of any of the buttons clicked. Using jQuery's .click() event handler and $(this).val() will allow the value of the clicked button to be the value in the alert. Not sure what you are actually looking for with video_url etc, but this should point you in the right direction. You can then use the value from the click to do pass to your function rather than jusrt alerting i eg: ... video_url(btnVal) ...
$(document).ready(function(){
$('.class_btns').click(function(){
var btnVal = $(this).val();
alert(btnVal);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="class_btns" value='1'>results</button>
<button class="class_btns" value='2'>results</button>
<button class="class_btns" value='3'>results</button>
<button class="class_btns" value='4'>results</button>

JS: click on different buttons should get printed different numbers on the screen, but it would print just one number

I 'm in the process of creating a calculator where I have a button for each number.
When a button is pressed, depending on the id, the number gets printed on the screen. Each button adds the number pressed to that area of the screen.
This is an example of two buttons:
<button class="btn btn-default" id="1" onclick="APP.agregarNumeros()">1</button>
<button class="btn btn-default" id="2" onclick="APP.agregarNumeros()">2</button>
<p id="resultado"></p>
<script>
var counterAPP = {
agregarNumeros:function(){
var resultado = "";
if ($("#1")) {
resultado += $("#resultado").text("1");
}
else if ($("#2")) {
resultado += $("#resultado").text("2");
}
}
};
window.APP = counterAPP;
Now, if I click on any of the two buttons, I get "1" printed on the screen. If I click the button (any of them) again, nothing happens.
Why is that? Any help would be greatly appreciated.
Pass the argument in inline-function. this.id will send value of current elements id attribute.
resultado will be key of the Object and it is initialized to 0, every time click takes place, this.resultado is incremented according to the value of the clicked element
parseInt will cast the string argument to integer
Try this:
var counterAPP = {
resultado: 0,
agregarNumeros: function(id) {
this.resultado += parseInt(id);
$("#resultado").text(this.resultado);
}
};
window.APP = counterAPP;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button class="btn btn-default" id="1" onclick="APP.agregarNumeros(this.id)">1</button>
<button class="btn btn-default" id="2" onclick="APP.agregarNumeros(this.id)">2</button>
<p id="resultado"></p>
Your HTML Should be
<button class="btn btn-default" id="1" onclick="APP.agregarNumeros(this)">1</button>
<button class="btn btn-default" id="2" onclick="APP.agregarNumeros(this)">2</button>
<p id="resultado"></p>
Your script should be
var resultado = 0;
var counterAPP = {
agregarNumeros:function(e){
var currValue = $(e).text();
resultado += parseInt(currValue);
$("#resultado").text(resultado);
}
};
window.APP = counterAPP;
variable resultado is a global variable initilized to 0.
once clicking button catch the value of the pressed value using the reference passed to the function and store it in currValue variable.
add the resultado to the currValue to get the new value.
append the resultado to the div.
Find the JS Fiddle here - https://jsfiddle.net/9ewwzmm1/

Categories

Resources