Print all buttons in order of their click Javascript - javascript

I have 10 buttons 0-9. I want to print out all the numbers of the buttons in order of their 'click'. For example, If I click on buttons 5,4,3,2,1 then it should be printed like 54321 but with my coding it is printing in ascending order only. Can anybody help me figure this one out?
function nmbr0(){
var displaySpan = document.getElementById('result0');
displaySpan.innerHTML = 0;
}
function nmbr1(){
var displaySpan = document.getElementById('result1');
displaySpan.innerHTML = 1;
}
function nmbr2(){
var displaySpan = document.getElementById('result2');
displaySpan.innerHTML = 2;
}
<button type="button" onClick="nmbr0()"> 0 </button>
<button type="button" onClick="nmbr1()"> 1 </button>
<button type="button" onClick="nmbr2()"> 2 </button>
You have entered
<span id="result0"></span>
<span id="result1"></span>
<span id="result2"></span>
This is my output after clicking on 4321:

The problem is that the spans are already defined in ascending order, so even if you print 2 before 1, it'll still go inside the 'result2' span.
<span id="result0"></span>
<span id="result1"></span>
<span id="result2"></span>
How about this alternate instead?
<button type="button" onClick="print(this)"> 0 </button>
<button type="button" onClick="print(this)"> 1 </button>
<button type="button" onClick="print(this)"> 2 </button>
You have entered
<span id="displaySpan"></span>
<script>
var displaySpan = document.getElementById('displaySpan')
function print(button){
displaySpan.innerHTML += button.innerHTML
}
</script>

First, you don't have to create a function for each button number because you can use selector for that. Look a simple solution for that:
var element = "";
$("button").click(function() {
element += $(this).html(); //Get the button number
$("#result").html(element);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
<div>
<strong>You have entered:</strong> <span id="result"></span>
</div>

Your code was behaving unexpectedly becase you were using ids for each button text display, so the order was already predefined in them from 0-10.
You can append the numbers to the html itself like below
function nmbr(num){
var displaySpan = document.getElementById('numbers');
//appending one after another
displaySpan.innerHTML += num + ' ';
}
You have entered<br>
<span id="numbers"></span>
<br>
<button type="button" onClick="nmbr('0')"> 0 </button>
<button type="button" onClick="nmbr('1')"> 1 </button>
<button type="button" onClick="nmbr('2')"> 2 </button>
<button type="button" onClick="nmbr('3')"> 3 </button>
<button type="button" onClick="nmbr('4')"> 4 </button>

Using vanilla JavaScript :
function showButtonClicked ()
{
// Get the output node
let output = document.querySelector( '.output' );
// Get the buttons parent and add a click event on it
document.querySelector( '.buttons' ).addEventListener( 'click', () => {
// Get the clicked element
let target = event.target;
// If it is not a button, return
if ( target.nodeName !== 'BUTTON' ) return;
// Add the button number to the output
output.textContent += ` ${ target.textContent }`;
});
}
showButtonClicked();
<div class="buttons">
<button>0</button>
<button>1</button>
<button>2</button>
<button>3</button>
<button>4</button>
<button>5</button>
<button>6</button>
<button>7</button>
<button>8</button>
<button>9</button>
</div>
<p>You have entered : </p>
<div class="output"></div>

Related

Detect innerHTML of clicked button

I am trying to make the innerHTML of a single button (amongst various buttons) the value of an input.
I have an empty div inside a form and six buttons (each with the same class).
<form>
<div id='wrapper'></div>
<button type='submit'>Submit</button>
</form>
<div class="col-lg-6 Div1">
<button class="form-button" onclick="addForm()">Button 1</button>
<button class="form-button" onclick="addForm()">Button 2</button>
<button class="form-button" onclick="addForm()">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button" onclick="addForm()">Button 4</button>
<button class="form-button" onclick="addForm()">Button 5</button>
<button class="form-button" onclick="addForm()">Button 6</button>
</div>
And then I have a dynamically added inputs, a button and a div. The inputs and buttons gets added into the div (.innerDiv) which get's added inside the #wrapper div (in the html code). The reason is so that the remove button can remove everything from it's parent element without removing all the dynamically added tags.
i = 1;
addForm() {
if(i < Infinity) {
var innerDiv = document.createElement('div');
innerDiv.classList = 'innerDiv' + i;
$('.wrapper').append(innerDiv);
//This adds a fixed input
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName' +i;
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
$(".form-button").click(function() { dynamicInput.value = this.innerHTML; }); //Gives the innerHTML of the button that was clicked as the value of the input
$('.innerDiv' + i).append(dynamicInput);
var anotherInput = document.createElement('input');
anotherInput.type = 'text';
anotherInput.name = 'anotherInput' +i;
anotherInput.classList = 'anotherInputClass';
anotherInput.placeholder = 'Write name here';
$('.innerDiv' + i).append(anotherInput);
var removeButton = document.createElement('button'); //This removes one element inside a parent div.
removeButton.type = 'button';
removeButton.classList = 'remove';
removeButton.innerHTML = '-';
removeButton.onclick = function () {
this.parentElement.remove();
}
$('.innerDiv').append(removeButton);
i++;
}
}
I've fixed the function for the dynamicInput to what was suggested to me by s.Bergmann. So whenever a button with the class of .form-button is clicked, all the above stiff will be added and the dynamicInput will have a fixed value of the button that was clicked. If I click Button 5 and then Button 2, in code, it will look a little something like this:
<form>
<div id='wrapper'>
<div class='innerDiv1'>
<input type='text' name='dynamicInputName1' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput1' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
<div class='innerDiv2'>
<input type='text' name='dynamicInputName2' class='dynamicInputClass' value='Button 2' disabled>
<input type='text' name='anotherInput2' class='anotherInputClass' placeholder='Write name here'>
<button type='button' class='remove'>-</button>
</div>
</div>
<button type='submit'>Submit</button>
</form>
As you can see, each button added one div, with the two inputs and the button. However, both inputs that were created from the dynamicInput have the same value (Button 2.). The idea is, if I press Button 5 first the first dynamicInput should have a value = 'Button 5' and if I then press Button 2, the second dynamicInput should have a value = 'Button 2' (These inputs are the first input of each div).
I'm not sure this is what you're going for,
but it might nudge you in the right direction.
It seems that onclick on a .form-button two things should happen:
it should create a dynamic input element
addForm() should be called // or perhaps addForm is what creates the input element?
If i were you, i'd reconsider the need for that "dynamic element". why not just use the actual button clicked?
anyway...
$(".form-button").click(function () { // replaces all the onlick=
addForm(this);
var dynamicInput = document.createElement('input');
dynamicInput.type = 'text';
dynamicInput.name = 'dynamicInputName';
dynamicInput.disabled = true;
dynamicInput.classList = 'dynamicInputClass';
dynamicInput.value = this.innerText;
console.log("Dynamic input", dynamicInput.value);
});
function addForm (formButton) { // dummy function? unclear what it's used for.
console.log("Form Button:", formButton)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-lg-6 Div1">
<button class="form-button"> Button 1</button>
<button class="form-button">Button 2</button>
<button class="form-button">Button 3</button>
</div>
<div class="col-lg-6 Div2">
<button class="form-button">Button 4</button>
<button class="form-button">Button 5</button>
<button class="form-button">Button 6</button>
</div>

How to get the Value in the labels for the 2 independent buttons?

I have two buttons with a single label like the below. The two buttons were independent.
<label for="buttons" class ="val">0</label>
<input class="btn btn-primary button1" type="button" value="button1" onclick="changeLabel()">
<input class="btn btn-primary button2" type="button" value="button2">
When I click the button1 1sttime, the Value in the label should be 1, for the 2nd time, the value in the label should be 2 and for the 3rd time, the value in the label should be 3. When I click the button1 for the 4th time, the value should again go back to 0. Like 0,1,2,3,0,1.....
The same should be the case for the button2 too. But, If i press the button1 2times. Then the Value in the label should be 2.At the same time, if I press the button2 for 3times the value in the label should change to 3 immediately.
Both the buttons, should be independent. The Values should be different for each buttons when they were clicked.
(".button1").click(function(){
var value = $('.val').html(parseInt($('.val').html())+1);
});
$(".button2").click(function(){
$('.val').html(parseInt($('.val').html())+1);
});
I couldn't do so. The value should return to 0 after clicking the buttons 3 times.
here is my codepen, https://codepen.io/Davi9/pen/LYLqWKx
could anyone please help?
Many thanks.
If you want to reset the counter to 0 when it reach 3, then try this:
$(".button1").click(function() {
var v = +$(".val").html();
$(".val").html(v > 2 ? 0 : v + 1);
});
Demo
$(".button1").click(function() {
var v = +$(".val").html();
$(".val").html(v > 2 ? 0 : v + 1);
});
$(".button2").click(function() {
var v = +$(".val").html();
$(".val").html(v > 2 ? 0 : v + 1);
});
body {
font-family: system-ui;
background: #f06d06;
color: white;
text-align: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="container">
<div class="row ">
<div class="col-md-6">
<br />
<label for="buttons" class="val">0</label>
<br />
<input class="btn btn-primary button1" type="button" value="button1">
<input class="btn btn-primary button2" type="button" value="button2">
</div>
</div>
</div>
</body>
Check the value of the label, if its greater than 3, set it to zero, somthing like
(".button1").click(function(){
incr();
});
$(".button2").click(function(){
incr();
});
function incr() {
var val = parseInt($('.val').html());
val=val+1;
if(val > 3)
val = 0;
$('.val').html(val);
}

Add specific items to cart on click

I want the cart to add the item that the Add to cart button relates to. Can you also please explain the reason behind it not working. Currently it is only adding the first product.
Here is the HTML:
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<form>
<button type="button" onclick="addToCart()">Add to cart</button>
</form>
and here is the JavaScript:
const name = document.querySelectorAll(".name");
const price = document.querySelectorAll("#price");
const button = document.querySelectorAll("button");
const cart = []
const addToCart = () => {
for (var i = 0; i < 1; i++) {
cart.push(name[i].innerText)
cart.push(parseInt(price[i].innerText))
}
console.log(cart)
}
Thank you
Here is an example, where we use data- attributes in the html. To help us when we load the cart.
let buttons = document.getElementsByTagName("button");
const cart = [];
for(var i=0; i<buttons.length; i++) {
let button = buttons[i];
console.log(button);
button.addEventListener('click', function(event){
console.clear();
console.log(event.target);
console.log(event.target.dataset.productSku);
cart.push( event.target.dataset.productSku );
console.log(cart)
});
}
<p class="name">Playstation 4 console (Black)</p>
<p class="pricetitle">Price: <span id="price">1899</span> AED</p>
<button data-product-sku="ps4black">Add to cart</button>
<p class="name">Xbox one console (Black)</p>
<p class="pricetitle">Price: <span id="price">1800</span> AED</p>
<button data-product-sku="xboxoneblack">Add to cart</button>
<div id="cart"></div>

how to click multiple buttons in a row with javascript?

is it possible to create script that click multiple buttons in a row with x time interval between clicks ?
for example when first button is clicked after x time second is clicked and etc.
(using Javascript).
var inputs = document.getElementsByClassName('className');
for(var i=0; i<inputs.length;i++) {
setInterval(function()
{inputs[i].click() },1000
}
use this code
var allButtons = document.getElementsByClassName("button")
var timeInterval = 5000 // x time in miliseconds
function pressButton(iteration=0){
setTimeout(function(){
allButtons[iteration].click();
pressButton(iteration++);
}, timeInterval)
}
pressButton();
<div id="parent">
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
<button class="button" type="submit" > </button>
</div>
More can be helped if you paste your code
var clickcallback = function(i) {
setTimeout(function() {
let id = "button" + i;
document.getElementById(id).click();
}, 1000); // one second
if(i <= 3) {
clickcallback(i+1);
}
};
<div>
<button id="button1" onClick="alert('click button1');">Button 1</button>
<button id="button2" onClick="alert('click button2');">Button 2</button>
<button id="button3" onClick="alert('click button3');">Button 3</button>
</div>
Here the demo:
https://jsfiddle.net/frasim/730xmhfv/8/

How to get the name of a button pressed in Javascript?

I have 2 <div>s of at least 81 buttons, all with the same class, but they have different ids and names. I am trying to figure out how to alert the name of the current button that was being pressed.
function runMe(e){
return function(){
console.log(e.getAttribute("id"));
}
}
var eles = document.getElementsByClassName("myButton")
Array.prototype.forEach.call(eles,function(ele){
ele.onclick = runMe(ele);
})
<button id="a1" class="myButton">A1</button>
<button id="b2" class="myButton">B2</button>
Get all the buttons with the same class name and assign the click event listener to each buttons so that when you click the button the listener is invoked:
function btnClick(){
console.log(this.id + " " + this.name);
}
var allButtons = document.getElementsByClassName('myButton');
for(i=0; i<allButtons.length; i++){
allButtons[i].addEventListener('click', btnClick);
}
<button id="1" class="myButton" name='name1'>B1</button>
<button id="2" class="myButton" name='name2'>B2</button>
<button id="3" class="myButton" name='name3'>B2</button>
<button id="4" class="myButton" name='name4'>B2</button>
<button id="5" class="myButton" name='name5'>B2</button>
You can try the following way by using this.name inside the click handler function:
var btns = document.querySelectorAll('button');
btns.forEach(function(btn){
btn.addEventListener('click', function(){
console.log('Name of the cliked button is:', this.name)
})
})
<div>
<button type="button" id="btn1" name="btnName1">Button 1</button>
<button type="button" id="btn2" name="btnName2">Button 2</button>
<!--------- More Buttons--------->
</div>
<div>
<!--------- More Buttons--------->
<button type="button" id="btn48" name="btnName48">Button 48</button>
<button type="button" id="btn49" name="btnName49">Button 49</button>
<button type="button" id="btn50" name="btnName50">Button 50</button>
<!--------- More Buttons--------->
</div>

Categories