Ognj3n Ognj3n - 7 months ago 8
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

onclick
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
value
of
input
element. Tried doing it like this:

$(document).ready(function(){
$('button.clicked').click(function(){
var clickedButtons= new Array();
$('button[background-color="rgb(76, 175, 80)"]').each(function(){
clickedButtons[clickedButtons.length]=this.value;
});
});
});


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

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.

Code:

 $(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 

     console.log(clickedButtons);

     $("here").val(clickedButtons.join());

   });


 });

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:

FROM:

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

TO:

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

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

Working jsFiddle

Comments