javascript function on multiple buttons - javascript

I have three buttons. I would like them to change colour when pressed, and back to no colour when pressed again.
I found this code on stackoverflow that allows me to almost do it however, it only works on one button, the other two are not affected.Also, when I pressed one of the other two buttons, the first button changes colour. I tried changing ID's on the buttons, adding another script with different getElementById() ID's but nothing works.
Do I need more than one function to achieve what I want?
The code I am using is below.
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF";
count = 1;
} else {
property.style.backgroundColor = "#E68352";
count = 0;
}
}
<head>
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
<input type="button" id="button" value = "A-D" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "E-H" style= "color:black" onclick="setColor('button', '#101010')";/>
</body>

Usually, when you write inline event handler you may take advantage of:
this: current element: When code is called from an in–line on-event handler, its this is set to the DOM element on which the listener is placed:
event: event element object
Therefore, change:
onclick="setColor('button', '#101010')"
with:
onclick="setColor(this, event, '#101010')"
So your code can be rewritten as:
function hexToRgb(hex) {
var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result ? 'rgb(' +
parseInt(result[1], 16) + ', ' +
parseInt(result[2], 16) + ', ' +
parseInt(result[3], 16) + ')'
: null;
}
function setColor(btnEle, evt, color) {
if (btnEle.style.backgroundColor == hexToRgb("#E68352")) {
btnEle.style.backgroundColor = "#FFFFFF"
}
else {
btnEle.style.backgroundColor = "#E68352"
}
}
<input type="button" id="button1" value = "A-D" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button2" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>
<input type="button" id="button3" value = "E-H" style= "color:black" onclick="setColor(this, event, '#101010')";/>

You should have uniques ID
You can use classList.toggle("yourClass") instead of using a count
var buttons = document.getElementsByClassName("button");
for (let i = 0, l = buttons.length; i < l; i++) {
buttons[i].addEventListener('click', function() {
buttons[i].classList.toggle('active');
})
}
.active {
background-color: #E68352 !important;
}
.button {
background-color: #FFFFFF;
}
<input type="button" id="button1" class="button" value="A-D" />
<input type="button" id="button2" class="button" value="E-H" />
<input type="button" id="button3" class="button" value="E-H" />

Set a class on the buttons, and then loop through the buttons and add an event listener to each of them:
EDIT: I see you are using an onclick handler, which I didn't notice at first; so this answer might not be as useful as I thought. You should definitely use different IDs though if you use that approach.
<button class="button" ... >
var buttons = document.getElementsByClassName('button')
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
// Do your button things.
})
}

IDs should be unique inside the document. Like this:
<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
<-- here ^ here ^ -->
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
<-- here ^ here ^ -->
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>
<-- here ^ here ^ -->
<!DOCTYPE html>
<html>
<head>
<script>
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
} else {
property.style.backgroundColor = "#E68352"
count = 0;
}
}
</script>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#101010')" ;/>
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#101010')" ;/>
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#101010')" ;/>
</body>
</html>

IDs need to be unique but you do not need them here
Give the buttons a class and use toggle the classList
window.onload=function() {
var buts = document.querySelectorAll(".but");
for (var i=0;i<buts.length;i++) {
buts[i].onclick=function() {
this.classList.toggle("clicked");
}
}
}
.but {background-color:black}
.clicked { background-color:#E68352; }
<input type="button" value="A-D" class="but" />
<input type="button" value="E-F" class="but" />
<input type="button" value="G-H" class="but" />

dont use numbers, use this instead
http://codepen.io/animhotep/pen/qRwjeX?editors=0010
var count = 1;
function setColor(btn, color) {
if (count == 0) {
btn.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
btn.style.backgroundColor = "#E68352"
count = 0;
}
}

Roberto, as Ibrahim correctly pointed out, the problem is that you are using the same ID for all buttons. When javascript executes this code:
var property = document.getElementById(btw);
it will always return the first element with the ID specified. One solution is choosing a different ID for each button and updating the corresponding onclick code. Another solution could be the one below, in which you do not need to specify IDs at all and the function setColor could be used for any element.
<!DOCTYPE html>
<html>
<head>
<script>
var count = 1;
function setColor(element, color) {
if (count == 0) {
el.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
el.style.backgroundColor = "#E68352"
count = 0;
}
}
</script>
<link rel="stylesheet" type="text/css" href="styles/main.css"/>
</head>
<body>
<input type="button" value = "A-D" style= "color:black" onclick="setColor(this, '#101010')";/>
<input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
<input type="button" value = "E-H" style= "color:black" onclick="setColor(this, '#101010')";/>
</body>
</html>
Note the use of the this variable as the first argument for setColor. In each of the buttons, the corresponding this will point to the element where it is defined.
Hope it helps.

You just need little bit of modification.
See the working code.
function setColor(btn, color) {
var elem = document.getElementById(btn);
if (elem.hasAttribute("style")) {
if (elem.getAttribute("style").indexOf("background-color:") == -1) {
elem.style.backgroundColor = color;
} else {
elem.style.backgroundColor = "";
}
}
}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles/main.css" />
</head>
<body>
<input type="button" id="button1" value="A-D" style="color:black" onclick="setColor('button1', '#E68352')" ;/>
<input type="button" id="button2" value="E-H" style="color:black" onclick="setColor('button2', '#E68352')" ;/>
<input type="button" id="button3" value="E-H" style="color:black" onclick="setColor('button3', '#E68352')" ;/>
</body>
</html>

Related

How to make buttons that increment and decrement a value when clicked?

I am new to programming. Every time I run this code, nothing happens. Can you please tell me why this is?
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<script type="text/javascript">
var x = 0
document.write(x)
function button1() {
document.write(x++)
}
function button2(){
document.write(x--)
}
</script>
</body>
The problem is that you put ++ and -- after the variable, meaning that it will increment/decrement the variable after printing it. Try putting it before the variable, like below.
Also, as mentioned, you have some trouble with document.write(). Consider the following documentation from the W3Schools page:
The write() method writes HTML expressions or JavaScript code to a
document.
The write() method is mostly used for testing. If it is used after an
HTML document is fully loaded, it will delete all existing HTML.
Thus, document.write() will remove all your existing content as soon as you click on a button. If you want to write to the document, use an element's .innerHTML like this:
var x = 0;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
document.getElementById('output-area').innerHTML = --x;
}
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<span id="output-area"></span>
Why don't you change your code a bit? Instead of document.write(x++) and document.write(x--) use document.write(++x) and document.write(--x).
The document.write is the problem. It only works before the browser is done loading the page completely. After that, document.write doesn't work. It just deletes all of the existing page contents.
Your first document.write is executed before you the page has loaded completely. This is why you should see the 0 next to the two buttons.
Then however, the page has loaded. Clicking on a button causes the event handler to be executed, so document.write will be called, which doesn't work at that point, because the page already has loaded completely.
document.write shouldn't be used anymore. There are many modern ways of updating the DOM. In this case, it would create a <span> element and update it's content using textContent.
Moreover, use addEventListener instead of inline event listeners:
var x = 0;
var span = document.querySelector('span'); // find the <span> element in the DOM
var increment = document.getElementById('increment'); // find the element with the ID 'increment'
var decrement = document.getElementById('decrement'); // find the element with the ID 'decrement'
increment.addEventListener('click', function () {
// this function is executed whenever the user clicks the increment button
span.textContent = x++;
});
decrement.addEventListener('click', function () {
// this function is executed whenever the user clicks the decrement button
span.textContent = x--;
});
<button id="increment">increment</button>
<button id="decrement">decrement</button>
<span>0</span>
As others have mentioned, the first x++ won't have a visible effect, because the value of x is incremented after the content of the <span> is updated. But that wasn't not your original problem.
document write will delete full html:
The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.
As in w3schools
try this instead
<body>
<input type=button value="increment" onclick="button1()" />
<input type=button value="decrement" onclick="button2()" />
<div id="value"></div>
<script type="text/javascript">
var x=0
var element = document.getElementById("value");
element.innerHTML = x;
function button1(){
element.innerHTML = ++x;
}
function button2(){
element.innerHTML = --x;
}
</script>
I changed the x-- and x++ to ++x and --x so the changes are immediatly. With this change your code would have worked aswell. showing 1 or -1.
HTML code for UI
<div class="card">
<div class="card-body">
<h5 class="card-title">How many guests can stay?</h5>
<div class="row">
<ul class="guestCounter">
<li data-btn-type="increment"><span class="romoveBtn"><i class="fa fa-plus"></i></span> </li>
<li class="counterText"><input type="text" name="guestCount" id="btnGuestCount" value="1" disabled /> </li>
<li data-btn-type="decrement"><span class="romoveBtn"><i class="fa fa-minus"></i></span></li>
</ul>
</div>
Java Script:
// set event for guest counter
$(".guestCounter li").on("click", function (element) {
var operationType = $(this).attr("data-btn-type");
//console.log(operationType);
var oldValue = $(this).parent().find("input").val();
//console.log(oldValue);
let newVal;
if (operationType == "increment") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
}
}
$(this).parent().find("input").val(newVal);
});
var x = 1;
document.getElementById('output-area').innerHTML = x;
function button1() {
document.getElementById('output-area').innerHTML = ++x;
}
function button2() {
if(x <= 0 ){
alert(' minimum value 0 // By Khaydarov Marufjon marvell_it academy uzb ')
return false ;
}
document.getElementById('output-area').innerHTML = --x;
}
input{
width: 70px;
background-color: transparent;
padding: 20px;
text-align: center;
}
button{
padding: 20px;
}
<input type='button' value="plus" onclick="button1()" />
<span id="output-area"></span>
<input type='button' value="minus" onclick="button2()" />
This question is very common. I have developed a solution with Bootstrap and pure JavaScript in another very similar thread here.
There is autoincrement input on keeping button pressed down.
Use ontouchstart and ontouchend instead than onmousedown and onmouseup method for mobile. To make it work for both mobile and desktop browser without headache use onpointerdown, onpointerup, onpointerleave
https://stackoverflow.com/a/70957862/13795525
function imposeMinMax(el) {
if (el.value != '') {
if (parseInt(el.value) < parseInt(el.min)) {
el.value = el.min;
}
if (parseInt(el.value) > parseInt(el.max)) {
el.value = el.max;
}
}
}
var index = 0;
var interval;
var timeout;
var stopFlag=false;
function clearAll(){
clearTimeout(timeout);
clearInterval(interval);
}
function modIn(el) {
var inId = el.id;
if (inId.charAt(0) == 'p') {
var targetId = inId.charAt(2);
var maxValue = Number(document.getElementById(targetId).max);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue < maxValue){
stopFlag=false;
document.getElementById(targetId).value++;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index+1 >= maxValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value++;
}
index++;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
if (inId.charAt(0) == 'm') {
var targetId = inId.charAt(2);
var minValue = Number(document.getElementById(targetId).min);
var actValue = Number(document.getElementById(targetId).value);
index = actValue;
if(actValue > minValue){
stopFlag=false;
document.getElementById(targetId).value--;
}else{
stopFlag=true;
}
timeout = setTimeout(function(){
interval = setInterval(function(){
if(index-1 <= minValue){
index=0;
stopFlag=true;
}
if(stopFlag==false){
document.getElementById(targetId).value--;
}
index--;
}, 100);
}, 500);
imposeMinMax(document.getElementById(targetId));
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Button example</title>
<meta charset="utf-8">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>
<body>
<button type='button' class='btn btn-danger btn-sm ' id='mbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='A' onchange='imposeMinMax(this)' value='200' max='350' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbA' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
<button type='button' class='btn btn-danger btn-sm signBut' id='mbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='B' onchange='imposeMinMax(this)' value='250' max='450' min='150' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbB' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button> 
<button type='button' class='btn btn-danger btn-sm signBut' id='mbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>-</button>
<input type='number' id='C' onchange='imposeMinMax(this)' value='3' max='10' min='1' step='1' style='width: 50px;'>
<button type='button' class='btn btn-danger btn-sm ' id='pbC' onmousedown='modIn(this)' onmouseup='clearAll()' onmouseleave='clearAll()'>+</button>
</body>
</html>

Buttons display progress

I'm doing a project for parent with a newborn Child, where they can progress in their learning taking care of their Child. This will be shown with buttons, and when a stage is complete, it will change the color on that button.
My code so far looks like this:
To change the buttons color to green.
var count = 1;
function setColor(btn, color) {
var property = document.getElementById(btn);
if (count == 0) {
property.style.backgroundColor = "#FFFFFF"
count = 1;
}
else {
property.style.backgroundColor = "#7FFF00"
count = 0;
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button" value = "Instructed" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done with help" style= "color:black" onclick="setColor('button', '#101010')";/>
<input type="button" id="button" value = "Done by yourself" style= "color:black" onclick="setColor('button', '#101010')";/>
</div>
</div>
When I Click the first button "Instructed" the color change to green (As I want it to). But when I click anyother button, the first button once again goes green and the other goes blue?
How can I fix it so whatever button they click on, will be colored green?
You gave every button the same id - an id should be identifying, which in this case it isn't. Your code here, takes the first element with the id button which is why the first button changes everytime.
Either use different ids for each individual button, or access the clicked element itself through the event-variable.
You also have only one count-variable, which won't work with multiple buttons. Imagine you pressing the first button => count is now 1. You then press the second button, it wouldn't turn green, as count is already 1.
You should probably store that information on the element itself, probably with a data-count-attribute.
Here is a working example:
function setColor(element) {
if(!element.hasAttribute('data-count')){
element.setAttribute('data-count', 1);
}
var count = element.getAttribute('data-count');
if(count == 0){
element.style.backgroundColor = '#ffffff';
element.setAttribute('data-count', 1);
}else{
element.style.backgroundColor = '#7fff00';
element.setAttribute('data-count', 0);
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" value = "Instructed" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done with help" style= "color:black" onclick="setColor(this)";/>
<input type="button" value = "Done by yourself" style= "color:black" onclick="setColor(this)";/>
</div>
</div>
So lets remove those duplicate ID's, and then we can actually pass the element into the function directly so we don't need to grab it by it's ID.
Then instead of using a count variable, we store value on the actual element in a data attribute so that it's state is stored on the element itself.
function setColor(element) {
if (element.getAttribute('data-done') === "0") {
element.style.backgroundColor = "#7FFF00"
element.setAttribute('data-done', "1");
} else {
element.style.backgroundColor = "#FFFFFF"
element.setAttribute('data-done', "0");
}
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input type="button" id="button1" value="Instructed" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button2" value="Done with help" style="color:black" onclick="setColor(this)" data-done="0" />
<input type="button" id="button3" value="Done by yourself" style="color:black" onclick="setColor(this)" data-done="0" />
</div>
</div>
Although perhaps the most semantic way would be to use classes and add an event listener:
// Grab all the buttons by their class
var btns = document.querySelectorAll('.btn-diaper');
// Loop through the buttons
for (var i = 0; i < btns.length; i++) {
// Assign a click listener to each button
btns[i].addEventListener("click", function(event) {
var el = event.toElement;
// Toggle the "active" class, which changes the button styling
if (el.classList.contains('active')) {
el.classList.remove('active');
} else {
el.classList.add('active');
}
});
}
.btn-diaper {
color: black;
background-color: #fff;
}
.btn-diaper.active {
background-color: #7fff00;
}
<div class="container">
<h2>Change diaper</h2>
<div class="well">
<input class="btn-diaper" type="button" id="button1" value="Instructed" />
<input class="btn-diaper" type="button" id="button2" value="Done with help" />
<input class="btn-diaper" type="button" id="button3" value="Done by yourself" />
</div>
</div>

Change a variable when button is clicked

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

HTML and Javascript changing visibility

I have tried searching this up many times. I have come close, but have not figured this out yet. What I am trying to do is when the user reaches a certain amount of clicks, a button pops up.
<!DOCTYPE html>
<html>
<head>
<title>++ Increment</title>
</head>
<body>
<h1>Click the Button</h1>
<input type="button" id="countButton" onclick="hi()" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<input type="button" id="countButton" onclick="store()" value="Store"/>
<input type="button" style="visibility:hidden;" value="Button" id="Sir" />
</body>
</html>
Here is the javascript:
var count = 0;
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
}
if (count >= 20) {
document.getElementById("Sir").style.visibility = "visible";
}
I think I need to assign the count variable outside the hi() function, but I don't know how to do that (or if that's possible)
From mobile so excuse my pseudo code
Is you're using jquery, you can store the value in a
$(btn).data('clicks')
Otherwise define a global variable above your hi function.
Then you need to put your logic of if(clicks > 20) inside your hi function
var count = 0;
function store(){
alert(count);
}
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
if (count >= 4) document.getElementById('Sir').style.display = 'inline-block';
}
#Sir{display:none;}
<h1>Click the Button</h1>
<input type="button" id="countButton" onclick="hi()" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<input type="button" id="countButton" onclick="store()" value="Store"/>
<input type="button" value="Button" id="Sir" />
Try this:
<!DOCTYPE html>
<html>
<head>
<title>++ Increment</title>
</head>
<body>
<h1>Click the Button</h1>
<input type="button" id="countButton" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<!-- <input type="button" id="countButton" onclick="store()" value="Store"/> -->
<input type="button" style="visibility:hidden;" value="Button" id="Sir" />
<script>
var count = 0;
var clickbutton = document.getElementById("countButton");
var showbutton = document.getElementById("Sir");
var amountstatus = document.getElementById("amount");
clickbutton.onclick = function(){
if(count < 3){
count++;
amountstatus.innerHTML = count;
}
else{
showbutton.style.visibility = "visible";
}
}
</script>
</body>
</html>
Check I put this <input type="button" id="countButton" onclick="store()" value="Store"/> in comments, that's why you must not have two id with the same name.
Hello can you please give a try to following code below:
var count = 0;
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
if (count >= 20) {
document.getElementById("Sir").style.visibility = "visible";
}
}
Only change i think to move if condition inside hi function. Hope it works
I agree with Zakk. Storing the value in a data attribute would be the best way to do this. Here's how I'd code it.
$(function() {
$( "#countButton" ).on( "click", function() {
var clicks = $( this ).data( "clicks" );
clicks++;
// Display the clicks.
$( "#amount" ).html( clicks );
$( this ).data( "clicks", clicks );
// Check to see if the sir button should be displayed.
if( clicks >= 20 ) {
$( "#Sir" ).css( "visibility", "visible" );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>++ Increment</title>
</head>
<body>
<h1>Click the Button</h1>
<input type="button" id="countButton" data-clicks="0" value="Click Me!"/>
<p class="ClickCount">Clicks: <a id="amount">0</a></p>
<input type="button" id="countButton" onclick="store()" value="Store"/>
<input type="button" style="visibility: hidden;" value="Button" id="Sir" />
</body>
</html>
Your condition is outside the function hi(), so it is checked once when the file loaded, no when hi() is call.
So you may put your condition inside hi().
var count = 0;
function hi() {
count += 1;
document.getElementById("amount").innerHTML = count;
if (count >= 20) {
document.getElementById("Sir").style.visibility = "visible";
}
}

How to get focused textbox

HTML code :
<input type="button" id="btn1" class="textboxclass" onclick="input(this.id)" />
<input type="button" id="btn2" class="textboxclass" onclick="input(this.id)" />
<input type="button" id="btn3" class="textboxclass" onclick="input(this.id)" />
<input type="button" id="btn4" class="textboxclass" onclick="input(this.id)" />
and Javascript code :
function input(e) {
e = e.charAt(3);
$(".textboxclass").each(function(index, value) {
if ($(this).is(':focus')) {
$(this).val($(this).val() + e);
$(this).focus();
}
});
}
and
$(this).is(':focus')
line is not working but when i set alert($(this)) it works after that alert
Thank you
I guess you want to append the last character of the ID to the value of the clicked input field. Then Why don't you just do,
$(function(){
$(".textboxclass").click(function(){
var num = this.id.charAt(3);
$(this).val($(this).val() + e);
});
});

Categories