How to get value of clicked button in calculator - javascript

I have multiple buttons containing different values
<button data-action="digit" class="button" id="1">1</button>
<button data-action="digit" class="button" id="2">2</button>
<button data-action="digit" class="button" id="3">3</button>
And I want to get these buttons to display on my calculator using this in javascript:
function digit_pressed(digit) {
console.log("digit pressed: " + digit);
}
But I am unsure what to add to my function. Any help would be greatly appreciated :)

You can use querySelectorAll for select all button then use addEventListener for add click event and last step use textContent for number of digit and call function.
document.querySelectorAll('button').forEach(el =>{
el.addEventListener('click', () =>{
digit_pressed(el.textContent);
});
});
function digit_pressed(digit) {
console.log("digit pressed: " + digit);
}
<button data-action="digit" class="button" id="1">1</button>
<button data-action="digit" class="button" id="2">2</button>
<button data-action="digit" class="button" id="3">3</button>
Reference:
querySelectorAll
addEventListener
textContent

Related

A single js function to create 9 different alerts on buttons

I am creating a button in a div so when we click it show us detailed information of the person given in API. But now I am confused about how to do this like I have 9 divs and every div has its own button, I am using onClick() on button it works well for the single button but to show information of 9 people if I use 9 different onClick() function it will create redundancy in code so how a single function can handle all this?
HTML
<button type="button" class="button" onclick="show" name="button">Details</button>
You can leverage event bubbling and addEventListener API to do that with only one event listener and only one handler.
const root = document.getElementById('root');
const handler = (e) => {
// target IS THE CLICKED BUTTON.
const {target} = e;
if (target.tagName === 'BUTTON') {
alert(`${target.name} has been pressed.`);
}
};
root.addEventListener('click', handler);
<div id='root'>
<div>
<button type="button" class="button" name="Button 1">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 2">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 3">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 4">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 5">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 6">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 7">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 8">Details</button>
</div>
<div>
<button type="button" class="button" name="Button 9">Details</button>
</div>
</div>
You could try something like this. Don't forget to defer execution when importing into your html file:
const alert = (e) => {
window.alert(e.target.innerHTML);
}
const buttons = document.getElementsByClassName("button");
for (const btn of buttons) {
btn.addEventListener("click", alert);
}
You can use querySelectorAll(). That means you select all of
the buttons. What you must pass in the braces is a CSS selector like
this: const button = document.querySelectorAll('button').
After that you must use forEach(). That is a callback function and that will apply the command/event on every single button. e.g. what you're gonna do if x button gets clicked.
Using querySelectorAll & forEach together is the most recommended for these use cases.
const button = document.querySelectorAll('.button');
button.forEach(e => {
// e here means every single button, doesn't matter which one
e.addEventListener('click', () => {
document.querySelector('h1').textContent += 1;
}
)}
)
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<button type="button" class="button" name="button">Details</button>
<h1>Result here: </h1>
if every div have its on button so you can find its id on button click
<button type="button" id="btn1" class="button" onclick="show(this)" name="button">Details</button>
here is javascript function
function show(btn){
const id = btn.getAttribute("id"); // here you will get "btn1"
if(id == "btn1"){
}
}

The card clicked should be flip [duplicate]

This question already has answers here:
Adding click event listener to elements with the same class
(5 answers)
Closed 8 months ago.
I'd like to perform the logic in the "onClick" through the event listener in jS but it only seems to run once? I have the class in all four but I can't figure out why it seems to only work for the first?
HTML:
<button id='btn-1' type="button" name="first" class="breakdown main-text" onclick="enableButton('btn-2');disableButton('btn-1');show('btn-1')"> Breakdown Start </button>
<button id='btn-2' type="button" name="second" class="breakdown main-text" onclick="enableButton('btn-3');disableButton('btn-2');show('btn-2')" disabled> Repair Start </button>
<button id='btn-3' type="button" name="third" class="breakdown main-text" onclick="enableButton('btn-4');disableButton('btn-3');show('btn-3')" disabled> Repair End </button>
<button id='btn-4' type="button" name="fourth" class="breakdown main-text" onclick="show('btn-4')" disabled> Breakdown Ended </button>
JS:
let button1 = document.querySelector('#btn-1')
let button2 = document.querySelector('#btn-2');
let button3 = document.querySelector('#btn-3');
let button4 = document.querySelector('#btn-4');
const breakdownButton = document.querySelector('.breakdown');
breakdownButton.addEventListener('click', function() {
console.log(this.innerHTML);
});
You need to use querySelectorAll which will return a collection.Now use spread operator (three dots) to convert it to array and use forEach .Inside forEach callback add the event listener to it
[...document.querySelectorAll('.breakdown')].forEach(function(item) {
item.addEventListener('click', function() {
console.log(item.innerHTML);
});
});
<button id='btn-1' type="button" name="first" class="breakdown main-text"> Breakdown Start </button>
<button id='btn-2' type="button" name="second" class="breakdown main-text" disabled> Repair Start </button>
<button id='btn-3' type="button" name="third" class="breakdown main-text" disabled> Repair End </button>
<button id='btn-4' type="button" name="fourth" class="breakdown main-text" disabled> Breakdown Ended </button>
In your snippet you have also attached inline event handler,that may not be necessary.
If the objective is to enable the next button then a function to enable it can be called from the callback function of the event handler
Need to use querySelectorAll instead of querySelector. And iterate over the list like this.
const breakdownButton = document.querySelectorAll('.breakdown');
// It add event listeners for the first button element.
// you can use forloop or map function to iterate over the list elements
// and here i used breakdownButton[0] as an example.
breakdownButton[0].addEventListener('click', function() {
console.log(this.innerHTML);
});
Use iterate functions like forEach or map. I used forEach
const breakdownButton = document.querySelectorAll('.breakdown');
breakdownButton.forEach(function(btn) {
btn.addEventListener('click', function() {
console.log();
});
});
Look at the documentation for querySelector:
querySelector() returns the first Element within the document that matches the specified selector, or group of selectors.
If you want to match more than one element, you'll need to use querySelectorAll and, because it doesn't return a single element loop over the result.
Alternatively, you could use event delegation.

How could I avoid WYSIWYG buttons to follow the link

I am trying to build an editor. Once I click an any button ( bold, or italic,...) it follows the link. Here is what I have tried out.
function execCmd(command) {
document.execCommand(command, false, null);
}
function execCommandWithArg(command, arg) {
document.execCommand(command, false, arg);
}
<form>
<div id="text_section">
<button onclick="execCmd('bold');"><i class="fas fa-bold"></i></button>
<button onclick="execCmd('italic');"><i class="fas fa-italic"></i></button>
<button onclick="execCommandWithArg('createLink', prompt('Enter a RUL','http://'));"><i class="fas fa-link"></i></button>
<button onclick="execCmd('unlink');"><i class="fas fa-unlink"></i></button>
<div class="p-2" contenteditable="true" id="content_text" style="border:solid; width:200px; heigth:100px;"></div>
</div>
<div class="form-group">
<input type="button" name="submit" value="Post text" id="submit" class="btn py-3 px-4 btn-primary">
</div>
</form>
How could I use e.preventDefault(); function on it ?
This code lines seem to work as expected, but the problem is not solved in my programm.
I think e.preventDefault(); might solve the problem.
Thank you for taking the time to answer my question.
Your callback needs to return false.
Try
<button onclick="execCmd('bold'); return false;">
Or
<button onclick="return execCmd('bold');">
function execCmd(command)
{
document.execCommand(command, false, null);
return false;
}
When button element is inside a form element it acts as submit unless it's type attribute say different (etc: reset, button).
So a quick fix will be to set type="button to your editing buttons:
<button type="button" onclick="execCmd('bold');">
<i class="fas fa-bold"></i>
</button>
Enjoy code!

store value from button in variable using javaScript

I have two buttons and I want to store the value attribute of the button pressed into a variable called amount. The code below is clearly wrong I have two identical id's for both buttons. What should I be doing in the function to save the value attribute to the variable amount onclick?
<button type="button" id='btn' onclick='storeVar' value='1'>1</button>
<button type="button" id='btn' onclick='storeVar' value='2'>2</button>
<script>
function storeVar() {
var amount = document.getElementById('btn').getAttribute('value');
console.log(amount);
}
</script>
The attribute id must be unique in a document, use class instead. Also pass this to the function so that you can refer the current button inside the function:
function storeVar(el) {
var amount = el.getAttribute('value');
// OR: simply
// var amount = el.value;
console.log(amount);
}
<button type="button" class='btn' onclick='storeVar(this)' value='1'>1</button>
<button type="button" class='btn' onclick='storeVar(this)' value='2'>2</button>
Make sure to have unique Id's.
<button type="button" id='btn-one' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>
<script>
function storeVar(value){
let amount = value;
console.log(amount);
}
</script>
Either give a unique id for each button or completely remove id attribute. After fixing your html try the following code.
<button type="button" id='btn' onclick='storeVar(this.value)' value='1'>1</button>
<button type="button" id='btn-two' onclick='storeVar(this.value)' value='2'>2</button>
<script>
function storeVar(v){
let amount = v;
console.log(amount);
}
</script>

Angular: using single variable for multiple buttons action

I want to use single varible for multiple buttons to enable and disable, individually.
<button class="button" [disabled]="btnState" (click)="function('val1')"> button 1</button>
<button class="button" [disabled]="btnState" (click)="function('val2')"> button 2</button>
<button class="button" [disabled]="btnState" (click)="function('val3')"> button 3</button>
<button class="button" [disabled]="btnState" (click)="function('val4')"> button 4</button>
How do I enable or disable the above buttons individually based on selection? I tried only with a result of disabling all of them or enabling all of them.
You can keep track state of the buttons:
<button class="button" [disabled]="buttonStates['button1']" (click)="onToggle('button1')"> button 1</button>
<button class="button" [disabled]="buttonStates['button2']" (click)="onToggle('button2')"> button 2</button>
<button class="button" [disabled]="buttonStates['button3']" (click)="onToggle('button3')"> button 3</button>
<button class="button" [disabled]="buttonStates['button4']" (click)="onToggle('button4')"> button 4</button>
export class YourComponent {
buttonStates: any = {
button1: true,
button2: false,
button3: false,
button4: true
};
onToggle(button) {
this.buttonStates[button] = !this.buttonStates[button];
}
}
You can use an array, since it's technically a single variable
HTML
<button class="button" [disabled]="btnState[0]" (click)="foo('val1')"> button 1</button>
<button class="button" [disabled]="btnState[1]" (click)="foo('val2')"> button 2</button>
<button class="button" [disabled]="btnState[2]" (click)="foo('val3')"> button 3</button>
<button class="button" [disabled]="btnState[3]" (click)="foo('val4')"> button 4</button>
app.component.ts
btnState = [false, false, true, true];
Stackblitz
Or, you can even use an object
HTML
<button class="button" [disabled]="btnState.btn1" (click)="foo('val1')"> button 1</button>
<button class="button" [disabled]="btnState.btn2" (click)="foo('val2')"> button 2</button>
<button class="button" [disabled]="btnState.btn3" (click)="foo('val3')"> button 3</button>
<button class="button" [disabled]="btnState.btn4" (click)="foo('val4')"> button 4</button>
app.component.ts
btnState = {
btn1: true,
btn2: false,
btn3: true,
btn4: false,
};
Stackblitz
Why do you want a single variable? If you do, I would use a map for it.
<button class="button" [disabled]="btnState['val1']" (click)="btnClickFunction('val1')"> button 1</button>
<button class="button" [disabled]="btnState['val2']" (click)="btnClickFunction('val2')"> button 2</button>
<button class="button" [disabled]="btnState['val3']" (click)="btnClickFunction('val3')"> button 3</button>
<button class="button" [disabled]="btnState['val4']" (click)="btnClickFunction('val4')"> button 4</button>
and in your clickFunction:
btnClickFunction(val){
if(!this.btnState.hasOwnProperty(val)){
this.btnState[val] = false;
}
this.btnState[val] = !this.btnState[val];
}

Categories