Ognj3n Ognj3n - 1 year ago 39
Javascript Question

How to put values of all active buttons into one array with jQuery

Here is the fiddle that represents my problem: https://jsfiddle.net/Ognj3n/jLjh9oLm/
Basically, when someone clicks on any of buttons

function is changing background color of button, so that user knows which button is clicked, but I omitted that part of code in my fiddle. Now I tried to put values of all clicked buttons into one array, in fiddle it should become
element. Tried doing it like this:

var clickedButtons= new Array();
$('button[background-color="rgb(76, 175, 80)"]').each(function(){

But inside
$('button[background-color="rgb(76, 175, 80)"]').each(function()
nothing is console logging, as if that part of code is not interpreting at all. Please help, I'm stuck

Answer Source

If you want to add the buttons value inside an array, each time a button is pressed you can edit your code like below:

Each time you press a button, I call the push() function which adds the element value inside the array.


 $(document).ready(function() {

   var clickedButtons = new Array();

   $('button.clicked').click(function() {

     clickedButtons.push(this.value); // adds element to the array
     $(this).unbind('click'); // stop listening 





Working jsFiddle

Additional note:

  • I removed all the onclick="..." buttons attribute from the html as it is not needed if you listen to the click event with jQuery.


Edit (Toggle version)

If you need to toggle the button values inside the array you just have to make the following edits:


 clickedButtons.push(this.value); // adds element to the array
 $(this).unbind('click'); // stop listening 


 var index = clickedButtons.indexOf(this.value);

 if (index === -1) 
   clickedButtons.push(this.value);  //value not found so push it
   clickedButtons.splice(index, 1);   // value found so remove it

Working jsFiddle