I'm working on a simple JavaScript calculator. Everything seems fine and other buttons works as expected except for the equal button which returns an "undefined" when it is clicked. On clicking the equal button, "if" the value of the screen is empty, I want the value of the screen to be set to an empty string, else, the new screen.value should be the result of an eval();
I've gone over the code several times and can't find what the problem is. Pls help. Thanks.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div class="wrapper">
<form>
<input type="text" class="screen" placeholder="0" value="";>
</form>
<div class="buttons">
<button type="button" class="btn btn-yellow" data-num="*">*</button>
<button type="button" class="btn btn-yellow" data-num="/">/</button>
<button type="button" class="btn btn-yellow" data-num="-">-</button>
<button type="button" class="btn btn-yellow" data-num="+">+</button>
<button type="button" class="btn btn-grey" data-num="9">9</button>
<button type="button" class="btn btn-grey" data-num="8">8</button>
<button type="button" class="btn btn-grey" data-num="7">7</button>
<button type="button" class="btn btn-grey" data-num="6">6</button>
<button type="button" class="btn btn-grey" data-num="5">5</button>
<button type="button" class="btn btn-grey" data-num="4">4</button>
<button type="button" class="btn btn-grey" data-num="3">3</button>
<button type="button" class="btn btn-grey" data-num="2">2</button>
<button type="button" class="btn btn-grey" data-num="1">1</button>
<button type="button" class="btn btn-grey" data-num="0">0</button>
<button type="button" class="btn btn-grey" data-num=".">.</button>
<button type="button" class="btn btn-equal">=</button>
<button type="button" class="btn btn-clear">C</button>
</div>
</div>
<script type="text/javascript" src="calculator.js"></script>
</body>
</html>
JAVASCRIPT CODE HERE
(function(){
let screen = document.querySelector(".screen");
let buttons = document.querySelectorAll(".btn");
let equal = document.querySelector(".btn-equal");
let clear = document.querySelector(".btn-clear");
buttons.forEach(function(button) {
button.addEventListener("click", function(e){
let value = e.target.dataset.num;
screen.value += value;
})
});
equal.addEventListener("click", function(e){
if (screen.value === "") {
screen.value = "";
} else{
let answer = eval(screen.value);
screen.value = answer;
}
})
clear.addEventListener("click", function(){
screen.value = "";
})
})();
The issue because you give the "=" button a ".btn" class, which has the 'click' event listener, and because the "=" button doesn't have attribute data-num, the input will be concatenate with undefined, so any calculation you will do will be end with "undefined" which give Syntax error.
So just removing "btn" class from "=" button will solve the issue.
This works, please check.
(function(){
let screen = document.querySelector(".screen");
let buttons = document.querySelectorAll(".btn");
let equal = document.querySelector(".btn-equal");
let clear = document.querySelector(".btn-clear");
buttons.forEach(function(button) {
button.addEventListener("click", function(e){
let value = e.target.dataset.num;
console.log(value)
screen.value += value;
})
});
equal.addEventListener("click", function(e){
if (screen.value === "") {
screen.value = "";
} else{
console.log(screen.value)
let answer = eval(screen.value);
screen.value = answer;
}
})
clear.addEventListener("click", function(){
screen.value = "";
})
})();
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="calculator.css">
</head>
<body>
<div class="wrapper">
<form>
<input type="text" class="screen" placeholder="0" value="";>
</form>
<div class="buttons">
<button type="button" class="btn btn-yellow" data-num="*">*</button>
<button type="button" class="btn btn-yellow" data-num="/">/</button>
<button type="button" class="btn btn-yellow" data-num="-">-</button>
<button type="button" class="btn btn-yellow" data-num="+">+</button>
<button type="button" class="btn btn-grey" data-num="9">9</button>
<button type="button" class="btn btn-grey" data-num="8">8</button>
<button type="button" class="btn btn-grey" data-num="7">7</button>
<button type="button" class="btn btn-grey" data-num="6">6</button>
<button type="button" class="btn btn-grey" data-num="5">5</button>
<button type="button" class="btn btn-grey" data-num="4">4</button>
<button type="button" class="btn btn-grey" data-num="3">3</button>
<button type="button" class="btn btn-grey" data-num="2">2</button>
<button type="button" class="btn btn-grey" data-num="1">1</button>
<button type="button" class="btn btn-grey" data-num="0">0</button>
<button type="button" class="btn btn-grey" data-num=".">.</button>
<button type="button" class="btn-equal">=</button>
<button type="button" class="btn btn-clear">C</button>
</div>
</div>
</body>
</html>
Related
I am trying to enable buttons on a web page using a js funtion for a django project.
I am new this so please be cool :-)
function change(id) {
var elem = document.getElementById(id);
let editID = "edit_".concat(id);
let deleteID = "delete_".concat(id);
if (elem.value == "Undo") {
elem.value = "Modify";
editButtonElement = document.getElementsByName(editID);
editButtonElement.disabled = false;
deleteButtonElement = document.getElementsByName(deleteID);
deleteButtonElement.disabled = false;
} else {
elem.value = "Undo";
editButtonElement = document.getElementsByName(editID);
editButtonElement.disabled = true;
deleteButtonElement = document.getElementsByName(deleteID);
deleteButtonElement.disabled = true;
}
}
<input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button>
</div>
<br>
<input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_22">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_22">Delete</button>
</div>
<br>
What I would like to happen is for the name of the main button change from "Modify" to "Undo", which happens. But I'd also like for the two related Edit and Delete buttons to be enabled so as to press them.
Anyone can tell me what I am doing wrong?
Thanks!
You could assign an external event listener to process the buttons clicks using an array of possible states so that a simple toggle mechanism is created.
FYI: input elements are self-closing so you do not supply a </input> as with the majority of HTML tags.
To concatenate in Javascript you use + rather than . which is the default in PHP so you should change "edit_".concat(id) to "edit_" + id
const states=['Undo','Modify'];
document.querySelectorAll('input[type="button"]').forEach( bttn=>{
bttn.addEventListener('click', function(e){
this.value=states[ 1 - states.indexOf( this.value ) ];
let div=document.querySelector('div.btn-group[data-id="'+this.id+'"]');
div.querySelectorAll('button').forEach(bttn=>{
bttn.disabled = this.value==states[1];
});
});
})
<input type="button" value="Modify" id="11" class="btn btn-info" />
<div class="btn-group" role="group" aria-label="Basic example" data-id=11>
<button type="button" class="btn btn-secondary" disabled="false">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false">Delete</button>
</div>
<br /><br />
<input type="button" value="Modify" id="22" class="btn btn-info" />
<div class="btn-group" role="group" aria-label="Basic example" data-id=22>
<button type="button" class="btn btn-secondary" disabled="false">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false">Delete</button>
</div>
<br /><br />
You should use getElementById instead of getElementsByName
function change(id) {
var elem = document.getElementById(id);
let editID = "edit_".concat(id)
let deleteID = "delete_".concat(id)
if (elem.value == "Undo") {
elem.value = "Modify";
editButtonElement = document.getElementById(editID)
editButtonElement.disabled = false
deleteButtonElement = document.getElementById(deleteID)
deleteButtonElement.disabled = false
} else {
elem.value = "Undo";
editButtonElement = document.getElementById(editID)
editButtonElement.disabled = true
deleteButtonElement = document.getElementById(deleteID)
deleteButtonElement.disabled = true
}
}
<input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button>
</div>
<br></br>
<input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_22">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_22">Delete</button>
</div>
To avoid repeating yourself, you could toggle all buttons in one function. Also you could use a switch statement if you want to handle more than "Modify" and "Undo", for instance :
function toggleButtons(id, disabled) {
["edit", "delete"].forEach(action => window[`${action}_${id}`].disabled = disabled)
}
function change(id) {
const elem = window[id],
v = elem.value;
switch (v) {
case "Undo":
toggleButtons(id, true);
elem.value = "Modify";
break;
default:
toggleButtons(id, false);
elem.value = "Undo";
break;
}
}
<input onclick="change(id)" type="button" value="Modify" id="11" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_11">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_11">Delete</button>
</div>
<br><br>
<input onclick="change(id)" type="button" value="Modify" id="22" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_22">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_22">Delete</button>
</div>
I'm pretty sure this is going to work.
function change(id) {
var elem = document.getElementById(id);
console.log(elem);
let editID = "edit_".concat(id);
let deleteID = "delete_".concat(id);
if (elem.value == "Undo") {
elem.value = "Modify";
let editButtonElement = document.getElementById(editID);
editButtonElement.disabled = false;
let deleteButtonElement = document.getElementById(deleteID);
deleteButtonElement.disabled = false;
} else {
elem.value = "Undo";
let editButtonElement = document.getElementById(editID);
editButtonElement.disabled = true;
let deleteButtonElement = document.getElementById(deleteID);
deleteButtonElement.disabled = true;
}
}
<input onclick="change('eleven')" type="button" value="Modify" id="eleven" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_eleven">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_eleven">Delete</button>
</div>
<br></br>
<input onclick="change('twentyTwo')" type="button" value="Modify" id="twentyTwo" class="btn btn-info"></input>
<div class="btn-group" role="group" aria-label="Basic example">
<button type="button" class="btn btn-secondary" disabled="false" id="edit_twentyTwo">Edit</button>
<button type="button" class="btn btn-secondary" disabled="false" id="delete_twentyTwo">Delete</button>
</div>
you forgot to declare the variables using a keyword like "let" or "var" and used getElementsByName instead of getElementById. It is also a good practice to avoid using numbers as id and to use semicolons. Your code is very clean though
When I click on a button, the number isn't displayed on the current-output div. This is supposed to be a test if I hooked up the buttons right. Any possible fixes for this? Can it be the problem of using classes? I'm writing the code in vanilla JavaScript.
const numberButtons = Array.from(document.getElementsByClassName('number'));
const previousOutputText = Array.from(document.getElementsByClassName('previous-output'));
const currentOutputText = Array.from(document.getElementsByClassName('current-output'));
class Calculator {
constructor(previousOutputText, currentOutputText) {
this.previousOutputText = previousOutputText;
this.currentOutputText = currentOutputText;
}
addNumber(number) {
this.currentOutput = number;
}
updateDisplay() {
this.currentOutputText.innerHTML = this.currentOutput;
}
}
const calculator = new Calculator(previousOutputText, currentOutputText);
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.addNumber(button.innerHTML);
calculator.updateDisplay();
})
})
<div class="output">
<div data-previous-output class="previous-output"></div>
<div data-current-output class="current-output"></div>
</div>
<button class="span-two all-clear" data-all-clear>AC</button>
<button class="delete" data-delete>DEL</button>
<button class="operation" data-operation>/</button>
<button class="number" data-number>7</button>
<button class="number" data-number>8</button>
<button class="number" data-number>9</button>
<button class="operation" data-operation>*</button>
<button class="number" data-number>4</button>
<button class="number" data-number>5</button>
<button class="number" data-number>6</button>
<button class="operation" data-operation>-</button>
<button class="number" data-number>1</button>
<button class="number" data-number>2</button>
<button class="number" data-number>3</button>
<button class="operation" data-operation>+</button>
<button class="number" data-number>0</button>
<button class="number" data-number>.</button>
<button class="span-two equals" data-equals>=</button>
You didn't provide the script position, and it can be the problem.
Check with this lines that buttons are really found from DOM
console.log('Working on buttons', numberButtons);
numberButtons.forEach(button => {
If they are not presents, move the <script> right before </body>
Then just put some console.log into the click even handler and some of Calculator method will provide you a really simple debug.
Your two arrayFrom for the outputs are wrong
You should delegate
I am not entirely happy with the "this" in your code either
const previousOutputText = document.querySelector('.previous-output');
const currentOutputText = document.querySelector('.current-output');
class Calculator {
constructor(previousOutputText, currentOutputText) {
this.currentOutput = "";
this.previousOutputText = previousOutputText;
this.currentOutputText = currentOutputText;
}
addNumber(number) {
this.currentOutput = number;
}
updateDisplay() {
this.currentOutputText.innerHTML = this.currentOutput;
}
}
const calculator = new Calculator(previousOutputText, currentOutputText);
document.getElementById("container").addEventListener("click",function(e) {
e.preventDefault(); // or make all buttons type="button"
const tgt = e.target;
if (tgt.classList.contains("btn")) {
calculator.addNumber(tgt.innerHTML);
calculator.updateDisplay();
}
})
<div class="output">
<div data-previous-output class="previous-output">xxx</div>
<div data-current-output class="current-output">yyy</div>
</div>
<div id="container">
<button class="btn span-two all-clear" data-all-clear>AC</button>
<button class="btn delete" data-delete>DEL</button>
<button class="btn operation" data-operation>/</button>
<button class="btn number" data-number>7</button>
<button class="btn number" data-number>8</button>
<button class="btn number" data-number>9</button>
<button class="btn operation" data-operation>*</button>
<button class="btn number" data-number>4</button>
<button class="btn number" data-number>5</button>
<button class="btn number" data-number>6</button>
<button class="btn operation" data-operation>-</button>
<button class="btn number" data-number>1</button>
<button class="btn number" data-number>2</button>
<button class="btn number" data-number>3</button>
<button class="btn operation" data-operation>+</button>
<button class="btn number" data-number>0</button>
<button class="btn number" data-number>.</button>
<button class="btn span-two equals" data-equals>=</button></div>
For your output text, getElementsByClassName returns an HTMLCollection, The fix would be to get the first index of the output elements.
const numberButtons = Array.from(document.getElementsByClassName('number'));
const previousOutputText = document.getElementsByClassName('previous-output')[0];
const currentOutputText = document.getElementsByClassName('current-output')[0];
class Calculator {
constructor(previousOutputText, currentOutputText) {
this.previousOutputText = previousOutputText;
this.currentOutputText = currentOutputText;
}
addNumber(number) {
this.currentOutput = number;
}
updateDisplay() {
this.currentOutputText.innerHTML = this.currentOutput;
}
}
const calculator = new Calculator(previousOutputText, currentOutputText);
numberButtons.forEach(button => {
button.addEventListener('click', () => {
calculator.addNumber(button.innerHTML);
calculator.updateDisplay();
})
})
<div class="output">
<div data-previous-output class="previous-output"></div>
<div data-current-output class="current-output"></div>
</div>
<button class="span-two all-clear" data-all-clear>AC</button>
<button class="delete" data-delete>DEL</button>
<button class="operation" data-operation>/</button>
<button class="number" data-number>7</button>
<button class="number" data-number>8</button>
<button class="number" data-number>9</button>
<button class="operation" data-operation>*</button>
<button class="number" data-number>4</button>
<button class="number" data-number>5</button>
<button class="number" data-number>6</button>
<button class="operation" data-operation>-</button>
<button class="number" data-number>1</button>
<button class="number" data-number>2</button>
<button class="number" data-number>3</button>
<button class="operation" data-operation>+</button>
<button class="number" data-number>0</button>
<button class="number" data-number>.</button>
<button class="span-two equals" data-equals>=</button>
This question already has answers here:
call the same jQuery function in multiple buttons
(10 answers)
Using multiple buttons on same function that redirects to different functions
(5 answers)
Using the same function with multiple buttons
(3 answers)
Closed 3 years ago.
I want to write multiple buttons in one function using javascript/jquery. My problem is that
Everytime im writing a separate function for each button with separate onclick event like in the below code snippet
I want to write one function that includes multiple buttons
function todaySales() {
alert('button1');
}
function yesterdaySales() {
alert('button2');
}
function wtdsales() {
alert('button3');
}
function llsales() {
alert('button4');
}
function lastSevenDays() {
alert('button5');
}
function lastThirtyDays() {
alert('button6');
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<button id="but1" class="btn btn-outline-info" onclick="todaySales();">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="yesterdaySales();">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="wtdsales();">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="llsales();">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="lastSevenDays();">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="lastThirtyDays()">Last 30 Days</button>
You can give the same function name with different parameter value like
<button id="but1" class="btn btn-outline-info" onclick="salesAction(this, 'todaySales');">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="salesAction(this, 'yesterdaySales');">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="salesAction(this, 'wtdsales');">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="salesAction(this, 'llsales');">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="salesAction(this, 'lastSevenDays');">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="salesAction(this, 'lastThirtyDays')">Last 30 Days</button>
<script>
function salesAction(thisObj, $salesVal){
console.log($salesVal);
// use switch to write separate logic for each sales
}
</script>
example : https://codepen.io/kaslab/pen/rROyVr
function clickButton(buttonName){
alert(buttonName);
}
just need seed a params to function. It's easy.
You can use the same click handler function and just strip data out of your button's properties or you can pass data as parameters to that function.
function clickHandler(ev) {
var target = event.target
console.log(target.id, target.textContent) // or whatever property
}
<button id="but1" class="btn btn-outline-info" onclick="clickHandler();">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="clickHandler();">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="clickHandler();">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="clickHandler();">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="clickHandler();">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="clickHandler();">Last 30 Days</button>
Try it
$(document).ready(function(){
$(".btn").on('click',function() {
alert( $(this).text())
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<button id="but1" class="btn btn-outline-info">Today</button>
<button id="but2" class="btn btn-outline-info">Yesterday</button>
<button id="but3" class="btn btn-outline-info">WTD</button>
<button id="but4" class="btn btn-outline-info">MTD</button>
<button id="but5" class="btn btn-outline-info">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info">Last 30</button>
using jQuery is very simple: suppose your buttons are direct children of a div element having id=“buttonsArray”
$(‘#buttonsArray’).on(‘click’, ‘button’, function() {
alert($(this));
});
As you can see, this overload of the .on() method let you dynamically bind to the clicked element. You can use data attribute within every button to create a switch statement inside that function and then differentiate behavior of your function depending on what button was pressed
<button data-value=“oneValue”>
<button data-value=“otherValue”>
The switch statement:
var myValue = $(this).data()[“value”]
switch (myValue) {
case “oneValue”:
// do something
break;
case “otherValue”:
// do something else
break;
}
HTML
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" rel="stylesheet" />
<button id="but1" class="btn btn-outline-info" onclick="onefunction();">Today</button>
<button id="but2" class="btn btn-outline-info" onclick="onefunction();">Yesterday</button>
<button id="but3" class="btn btn-outline-info" onclick="onefunction();">WTD</button>
<button id="but4" class="btn btn-outline-info" onclick="onefunction();">MTD</button>
<button id="but5" class="btn btn-outline-info" onclick="onefunction();">Last 7 Days</button>
<button id="but6" class="btn btn-outline-info" onclick="onefunction()">Last 30 Days</button>
JS
function onefunction() {
if($(this).attr("id") == "but1"){
alert('button1');
}
else if($(this).attr("id") == "but2"){
alert('button2');
}
...
}
I've found that touchstart works better than the click event when working with my iPad, so I would like to use touchstart instead of 'click'.
Q: How do I refactor the JavaScript portion of the following? I used to have a single $(document).on('click','.number',pgm.number)
pgm = {}
pgm.number = function() {
console.log(this) // etc
}
btn1.addEventListener('touchstart', pgm.number, false)
btn2.addEventListener('touchstart', pgm.number, false)
btn3.addEventListener('touchstart', pgm.number, false)
btn4.addEventListener('touchstart', pgm.number, false)
btn5.addEventListener('touchstart', pgm.number, false)
btn6.addEventListener('touchstart', pgm.number, false)
btn7.addEventListener('touchstart', pgm.number, false)
btn8.addEventListener('touchstart', pgm.number, false)
btn9.addEventListener('touchstart', pgm.number, false)
btn0.addEventListener('touchstart', pgm.number, false)
<button id="btn1" class="number">1</button>
<button id="btn2" class="number">2</button>
<button id="btn3" class="number">3</button>
<button id="btn4" class="number">4</button>
<button id="btn5" class="number">5</button>
<button id="btn6" class="number">6</button>
<button id="btn7" class="number">7</button>
<button id="btn8" class="number">8</button>
<button id="btn9" class="number">9</button>
<button id="btn0" class="number">0</button>
You can get the buttons by class number and iterate over them using Array#forEach function and for each item add the event handler.
document.querySelectorAll('.number')
.forEach(btn => btn .addEventListener('touchstart', pgm.number, false))
See an example
function showId() {
console.log(this.id) ;
}
document.querySelectorAll('.number')
.forEach(btn => btn.addEventListener('click', showId, false))
<button id="btn1" class="number">1</button>
<button id="btn2" class="number">2</button>
<button id="btn3" class="number">3</button>
<button id="btn4" class="number">4</button>
<button id="btn5" class="number">5</button>
<button id="btn6" class="number">6</button>
<button id="btn7" class="number">7</button>
<button id="btn8" class="number">8</button>
<button id="btn9" class="number">9</button>
<button id="btn0" class="number">0</button>
Add the touchstart to the document and use the event target to check if the element has the className ".number". This is the closest to jQuery's event delegation:
pgm.number = function(e) {
var t = e.target; // get the taget of the event (the element that got touchstarted)
if(t.classList.contains("number")) { // if it has a class of .number
console.log(t); // log it (use it)
}
}
document.addEventListener("touchstart", pgm.number, false);
Example using click:
var pgm = {};
pgm.number = function(e) {
var t = e.target;
if (t.classList.contains("number")) {
console.log(t);
}
}
document.addEventListener("click", pgm.number, false);
<button id="btn1" class="number">1</button>
<button id="btn2" class="number">2</button>
<button id="btn3" class="number">3</button>
<button id="btn4" class="number">4</button>
<button id="btn5" class="number">5</button>
<button id="btn6" class="number">6</button>
<button id="btn7" class="number">7</button>
<button id="btn8" class="number">8</button>
<button id="btn9" class="number">9</button>
<button id="btn0" class="number">0</button>
var buttons = document.querySelectorAll('.number');
buttons.forEach((button)=>{
button.addEventListener('click',(e)=>{console.log(e.target)},false);
});
<button id="btn1" class="number">1</button>
<button id="btn2" class="number">2</button>
<button id="btn3" class="number">3</button>
<button id="btn4" class="number">4</button>
<button id="btn5" class="number">5</button>
<button id="btn6" class="number">6</button>
<button id="btn7" class="number">7</button>
<button id="btn8" class="number">8</button>
<button id="btn9" class="number">9</button>
<button id="btn0" class="number">0</button>
It's sample code.
I hope it help you.
I'm using the following JavaScript to add a decimal into an input field:
function addChar(input, character) {
if (input.value == null || input.value == "0"){
input.value = character}
else{
input.value += character}
};
$('#button-dot').click(function() {
addChar(this.form.display, '.');
});
with HTML markup:
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25"/>
<button TYPE="button" ID="button-1" VALUE="1">1</button>
<button TYPE="button" ID="button-2" VALUE="2">2</button>
<button TYPE="button" ID="button-3" VALUE="3">3</button>
<button TYPE="button" ID="button-4" VALUE="4">4</button>
<button TYPE="button" ID="button-5" VALUE="5">5</button>
<button TYPE="button" ID="button-6" VALUE="6">6</button>
<button TYPE="button" ID="button-7" VALUE="7">7</button>
<button TYPE="button" ID="button-8" VALUE="8">8</button>
<button TYPE="button" ID="button-9" VALUE="9">9</button>
<button TYPE="button" ID="button-0" VALUE="0">0</button>
<button TYPE="button" ID="button-dot" VALUE=".">.</button>
When the user presses the the #button-dot key prior to any number key, the decimal appears with no zero to the left of it and I would like for that to be the case. So is there a way to alter this code such that when the user inputs the decimal point as the first key, a zero will appear to the left of the decimal?
Try this handler:
$('#button-dot').click(function(){
var txt = disp.val().replace(/\./g, '');
if(!txt)
txt = '0';
txt += '.';
disp.val(txt);
});
$(function() {
var disp = $('#disp');
//all buttons except for last button `dot`
$('[id^=button-]').slice(0, -1).click(function() {
var txt = disp.val();
if('0' === txt) { //modified condition
txt = '';
}
disp.val(txt + this.value);
});
$('#button-dot').click(function() {
var txt = disp.val().replace(/\./g, ''); //replace all previous dots
if (!txt)
txt = '0';
disp.val(txt + '.');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<INPUT NAME="display" ID="disp" VALUE="0" SIZE="28" MAXLENGTH="25" />
<button TYPE="button" ID="button-1" VALUE="1">1</button>
<button TYPE="button" ID="button-2" VALUE="2">2</button>
<button TYPE="button" ID="button-3" VALUE="3">3</button>
<button TYPE="button" ID="button-4" VALUE="4">4</button>
<button TYPE="button" ID="button-5" VALUE="5">5</button>
<button TYPE="button" ID="button-6" VALUE="6">6</button>
<button TYPE="button" ID="button-7" VALUE="7">7</button>
<button TYPE="button" ID="button-8" VALUE="8">8</button>
<button TYPE="button" ID="button-9" VALUE="9">9</button>
<button TYPE="button" ID="button-0" VALUE="0">0</button>
<button TYPE="button" ID="button-dot" VALUE=".">.</button>
Not entirely sure what you want, but this code will replace a dot or a zero or an empty input with 0.:
function addChar(input, character) {
if (input.value == '' || input.value == '.' || input.value == "0"){
input.value = "0" + character}
else{
input.value += character}
};
$('#button-dot').click(function() {
addChar($('input').get(0), '.');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="i" />
<button id="button-dot">.</button>