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>
Related
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>
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>
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/
I am having trouble getting one of my buttons to append data to a HTML text area. The button in question is "BPI". I am trying to append a few digits of pi to my first text area. The other 4 buttons operate within the 2nd text area. Thank you in advance for your help.
$(document).ready(function() {
$('#BAddition').click(function(e) {
$('#TOperator').val() += "+";
})
$('#BSubtract').click(function(e) {
$('#TOperator').val() += "-";
})
$('#BMultiplication').click(function(e) {
$('#TOperator').val() += "*";
})
$('#BDivision').click(function(e) {
$('#TOperator').val() += "/";
})
$('#BPI').click(function(e) {
$('#TFirstnum').val() += "3.141592657";
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input:<br>
<textarea id="TFirstnum"></textarea>
<textarea id="TOperator"></textarea>
<textarea id="TSecondnum"></textarea>
<label id="LEquals"></label>
<br>
<button type="button" onclick="" id="BAddition">+</button>
<button type="button" onclick="" id="BSubtract">-</button>
<button type="button" onclick="" id="BDivision">/</button>
<button type="button" onclick="" id="BMultiplication">*</button>
<button type="button" onclick="" id="BPI">π</button>
<button type="button" onclick="" id="BEquals">=</button>
If you want to add a value use $(yourObject).val("yourvalue")
If you want to add a value to the already existing value use $(yourObject).val($(yourObject).val() + "yourvalue")
Working example below
$(document).ready(function() {
$('#BAddition').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "+");
})
$('#BSubtract').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "-");
})
$('#BMultiplication').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "*");
})
$('#BDivision').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "/");
})
$('#BPI').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "3.141592657");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input:<br>
<textarea id="TFirstnum"></textarea>
<textarea id="TOperator"></textarea>
<textarea id="TSecondnum"></textarea>
<label id="LEquals"></label>
<br>
<button type="button" onclick="" id="BAddition">+</button>
<button type="button" onclick="" id="BSubtract">-</button>
<button type="button" onclick="" id="BDivision">/</button>
<button type="button" onclick="" id="BMultiplication">*</button>
<button type="button" onclick="" id="BPI">π</button>
<button type="button" onclick="" id="BEquals">=</button>
When you want to set an element's value attribute using Jquery, you need to set the value inside the parantheses: .val('newValue').
When you want to get an element's value, use blank parantheses: var x = elem.val().
So to concatenate (or append) values, you should use:
$('#TOperator').val($('#TOperator').val() + '+');
A longer version to elaborate:
var expr = $('#TOperator').val(); // Get current value
expr += '+'; // Concatenate the + sign
$('#TOperator').val(expr); // Set the new value
You are useing += which does not work. You have to get the value, and then set the value;
$('#BAddition').click(function(e) {
$('#TOperator').val( $('#TOperator').val() + "+");
});
You're repeating yourself a lot. I suggest you change the html a bit and create a much neater function.
<button type="button" class="MathSign" data-sign="+">+</button>
<button type="button" class="MathSign" data-sign="-">-</button>
<button type="button" class="MathSign" data-sign="/">/</button>
<button type="button" class="MathSign" data-sign="*">*</button>
<button type="button" id="BPI">π</button>
<button type="button" class="MathSign" data-sign="=">=</button>
// handle the [+ - * / =] in one go:
$('.MathSign').on('click', function(){
$('#TOperator').val( $('#TOperator').val() + $(this).data('sign'));
// Or,you can drop the data-sign attribute and use the content of the button
$('#TOperator').val( $('#TOperator').val() + this.innerHTML);
})
$(selector).val() is used to get the value of the input box.
If you want to set the value, you need to pass the value $(selector).val(value).
I have modified your example. One thing you need to consider is when you do $(selector).val(), you will get string. If you want to have addition instead of concatenation of two strings, You should probably use parseInt
$(document).ready(function() {
$('#BAddition').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "+");
})
$('#BSubtract').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "-");
})
$('#BMultiplication').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "*");
})
$('#BDivision').click(function(e) {
$('#TOperator').val($('#TOperator').val() + "/");
})
$('#BPI').click(function(e) {
$('#TFirstnum').val($('#TFirstnum').val() + "3.141592657");
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input:<br>
<textarea id="TFirstnum"></textarea>
<textarea id="TOperator"></textarea>
<textarea id="TSecondnum"></textarea>
<label id="LEquals"></label>
<br>
<button type="button" onclick="" id="BAddition">+</button>
<button type="button" onclick="" id="BSubtract">-</button>
<button type="button" onclick="" id="BDivision">/</button>
<button type="button" onclick="" id="BMultiplication">*</button>
<button type="button" onclick="" id="BPI">π</button>
<button type="button" onclick="" id="BEquals">=</button>
Trying to make simple tic-tac-toe game. I'm trying to change the button's value when clicked, but I don't know which one the user will click first. Obviously, I've got 9 buttons like this:
<input type="button" id="Button1" onclick="Button1_Click()" />
and a function like this, to handle their onclick event.
<script>
var Caption = "X";
function Button1_Click() {
document.getElementById('Button1').value = Caption;
if (Caption=="X") {
Caption = "O";
Caption="X";
}
}
</script>
But the thing is, when i click other buttons, The caption is always the same (X), how can I change it?
I think you may just change your Button1_Click() like below:
function Button1_Click() {
document.getElementById('Button1').value = Caption;
if (Caption=="X") {
Caption = "O";
} else {
Caption="X";
}
}
But, in this way, you said you have 9 buttons. Then you have to create 9 separated but look quite the same function like the one above.
How about this:
<!--You need to make it look better..-->
<div id='buttonParent'>
<input type='button' id='btn1'>
<input type='button' id='btn2'>
<input type='button' id='btn3'>
<input type='button' id='btn4'>
<input type='button' id='btn5'>
<input type='button' id='btn6'>
<input type='button' id='btn7'>
<input type='button' id='btn8'>
<input type='button' id='btn9'>
</div>
<script>
// wrap all your 9 buttons in a tag <div id='buttonParent'> or whatever you like.
var buttonParentNode = document.getElementById('buttonParent');
var button_click = function(e) {
// this function handle all button click event
var btn = e.target; // DOM element which was click. It must be any tag inside buttonParentNode
if (btn.tagName == 'INPUT') { // if DOM element is a input tag.
if (btn.innerHTML == 'X') {
btn.innerHTML = 'O';
} else {
btn.innerHTML = 'X';
}
}
};
buttonParentNode.addEventListener('click', button_click, false);
</script>
Method 1: Closure
One way to do it is using a closure for the click handler, so it knows which button was pressed. Keep track of who'se turn it is in a variable.
// Do this only when the page is loaded.
window.addEventListener('DOMContentLoaded', function() {
// Variable to keep track of turns in.
var Xturn = true;
// A function that returns a specific click handler for a button.
function createClickHandler(element, index) {
// The anonymous function that is returned is the actual click handler.
return function() {
// Logs text in the console (press F12 to view it). Very useful for testing/debugging!
console.log('Button ' + index + ' clicked');
// Only do something if this button was still open.
if (element.innerText == '') {
element.innerText = Xturn ? 'X' : 'O';
Xturn = !Xturn; // Toggle player
};
}
}
// Now for the actual initialisation:
// Find all buttons.
var buttons = document.querySelectorAll('button');
// Attach a click handler to each of them.
for (n = 0; n < buttons.length; n++) {
buttons.item(n).addEventListener('click', createClickHandler(buttons.item(n), n));
}
});
button {
width: 50px;
height: 50px;
line-height: 50px;
vertical-align: bottom;
}
<div>
<button/><button/><button/>
</div>
<div>
<button/><button/><button/>
</div>
<div>
<button/><button/><button/>
</div>
Method 2: Event target
When an event is triggered, the event handler gets an event object as a parameter. This object contains information about the event, like the element that triggered it. This way you can also find the button. If you give every button an id or other recognizable property, you can distinguish between the buttons.
You can bind an event handler on every button, but it's even easier to bind it to a parent element. You can even bind the click handler to the document. That way you also don't have to wait for the DOM to be loaded. The even handler will capture every click, and it will even capture clicks on elements that are dynamically added later.
Inside the event handler, you can get the element that triggered it, and only respond if it is one of the buttons of the game:
// Variable to keep track of turns in.
var Xturn = true;
document.addEventListener('click', function(event) {
var event = event || window.event;
var element = event.target || event.srcElement;
// Only respond to button clicks
if (element.tagName == 'BUTTON') {
console.log('Button ' + element.id + ' clicked');
// Only do something if this button was still open.
if (element.innerText == '') {
element.innerText = Xturn ? 'X' : 'O';
Xturn = !Xturn; // Toggle player
}
}
});
button {
width: 50px;
height: 50px;
line-height: 50px;
vertical-align: bottom;
}
<div>
<button id='b1' /><button id='b2' /><button id='b3' />
</div>
<div>
<button id='b4' /><button id='b5' /><button id='b6' />
</div>
<div>
<button id='b7' /><button id='b8' /><button id='b9' />
</div>
function button_Click(e) {
if(e.value === 'X') {
e.value = 'O';
} else {
e.value = 'X';
}
}
<input type="button" id="button1" onclick="button_Click(this)" value="X" />
<input type="button" id="button2" onclick="button_Click(this)" value="O" />
<input type="button" id="button3" onclick="button_Click(this)" value="X" />
<input type="button" id="button4" onclick="button_Click(this)" value="O" />
<input type="button" id="button5" onclick="button_Click(this)" value="X" />
<input type="button" id="button6" onclick="button_Click(this)" value="O" />
<input type="button" id="button7" onclick="button_Click(this)" value="X" />
<input type="button" id="button8" onclick="button_Click(this)" value="O" />
<input type="button" id="button9" onclick="button_Click(this)" value="X" />
<input type="button" id="button10" onclick="button_Click(this)" value="O" />
However a better approach would be as follows:
document.addEventListener("DOMContentLoaded", buttonClickHandler);
function buttonClickHandler() {
var buttons = document.getElementsByClassName('button');
for(var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
if(this.value === 'X') {
this.value = 'O';
} else {
this.value = 'X';
}
});
}
}
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
<input type="button" class="button" value="X" />
<input type="button" class="button" value="O" />
try this,
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<div>
<input type="button" id="Button1" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button2" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button3" class="btn" onclick="Button1_Click(this)" />
</div>
<div>
<input type="button" id="Button4" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button5" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button6" class="btn" onclick="Button1_Click(this)" />
</div>
<div>
<input type="button" id="Button7" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button8" class="btn" onclick="Button1_Click(this)" />
<input type="button" id="Button9" class="btn" onclick="Button1_Click(this)" />
</div>
<script>
var Caption = "X";
function Button1_Click(btn) {
$(btn).val(Caption);
if (Caption == "X") {
Caption = "O";
} else {
Caption = "X";
}
}
</script>
</body>
</html>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" />
<input type="button" value=' ' onclick="Button_Click(this)" /> <br/>
<script>
var turn = 'x';
function Button_Click(btn) {
if (btn.value == ' ') {
btn.value = turn;
turn = (turn == 'x') ? 'o' : 'x';
}
}
</script>
You may try it here