I have generated a list of buttons , and would like each one to independently change colour when click, so they go red/green alternately on each click.
<?php
$getInfo = getAllRows();
$button = '<button type="button" id ="toggle" ></button>';?>
</php>
<html>
<div class ="enableButtons">
//there are 5 values to iterate over
<?php foreach ($getInfo):
echo $button;
?>
<?php endforeach ?>
</div>
</html>
<script>
$('#toggle').click(function(){
$(this).toggleClass('green');
});
</script>
.green
{
background-color:green;
}
The problem Im having is that only the first button seems to be toggling colour , the others dont do anything when I click! Also Im unsure how to make it toggle from red/green alternately.
Any help would be great cheers!
The problem is with the id
. It seems all the button will have same id
which is wrong markup.
Try by replacing id
with a common class
$button = '<button type="button" class="someCommonCLass" ></button>'
In js
$('.someCommonCLass').click(function(){
$(this).toggleClass('green');
});
As you are generating a list of buttons so you should use class instead of id
Try this:
$button = '<button type="button" class ="toggle" ></button>'
<script>
$('.toggle').click(function(){
$(this).toggleClass('green');
});
</script>
Here's a JSFiddle. Like others have suggested, you want to output your buttons with a class
instead of an id
, to make your buttons easier to select with jQuery. Here's an example, with nice CSS. Your buttons should be formatted like this.
<button type="button" class="toggle"> label </button>
Here's a working SO Snippet.
$('.toggle').click(function(){
$(this).toggleClass('green');
});
.toggle {
background-color:#df0606;
padding:7px;
border:1px solid red;
color:white;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.toggle:hover {
background-color:#cd0101;
padding:7px;
border:1px solid red;
color:#ff2a31;
font-size:1.18em;
box-shadow:2px 4px #510809;
margin-left:4px;
margin-right:4px;
}
.green {
color:white;
padding:7px;
border:1px solid lime;
background-color:green;
font-size:1.18em;
box-shadow:2px 4px black;
margin-left:4px;
margin-right:4px;
}
.green:hover {
color:lime;
padding:7px;
border:1px solid lime;
background-color:#12de09;
font-size:1.18em;
box-shadow:2px 4px #044f12;
margin-left:4px;
margin-right:4px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<p>
These buttons generated with PHP:
</p>
<div class ="enableButtons">
<button type="button" class="toggle">One</button>
<button type="button" class="toggle">Two</button>
<button type="button" class="toggle">Three</button>
</div>
<p>
Here's some text. Text text text.
</p>
</body>
</html>
</div>