Search code examples
javascriptjquerycheckboxradio-button

function to push value to array on checkbox OR radio change


I have a function like this:

$('input:checkbox').change(function() {
  array = [];
  $('input:checkbox:checked').each(function() { 
    array.push($(this).val()); // push checked checkbox values to array
  });
  $('input:radio:checked').each(function() { 
    array.push($(this).val()); // push checked radio values to array
  });
  someOtherFunction();
});

... which collects values from checkboxes and radio buttons in one array. At the moment it runs when a checkbox changes but I want it to run when a radio button changes too.

As a noob I have no idea where to start so have tried very little. And I didn't find the answer after a good search.

Thanks in advance.


Solution

  • Try with

    $('input:checkbox, input:radio').change(function() {
    

    The problem is that your current selector is only applicable for checkboxes.