Search code examples
jqueryarrayslistcheckboxeventtrigger

Trigger jQuery event and know if and Checkbox in list/array is checked


The code below is a cut down version of the page, but you see that it will iterate through a list and produce a checkbox for each item in the list.

What I want to know:

  1. How do I trigger a jQuery event when ANY of the checkboxes are clicked (either making them checked or unchecked)?
  2. What jQuery code do I need to then look at the list of checkboxes produced by the below code and then make a button (e.g. with id="DeleteSelected" ) visible if any are checked, or hide the button if they are all unchecked?
<s:form action="manageQuestions" >
    <s:iterator value="questions" id="currentQuestion">
        <s:checkbox name="questionCheck" id="ch-%{id}" value="selected" fieldValue="%{id}"/>
    </s:iterator>
</s:form>

I'm such a jQuery dunce that I know that I need to put:

<script>

</script>

there at the end but that's all I know. I don't know if I need to put:

$(document).ready(function() {
    //something here
}

or if I don't need the document ready etc. at all.


Solution

  • Try this: http://jsbin.com/AfEriqe/1/edit

    $(document).ready(function() {
      var checkboxes = $('input[type=checkbox]');
      $(checkboxes).on('change', function() {
        console.log('checkbox changed');
        if($(checkboxes).is(':checked')) {
          console.log('at least one checked');
        }
      });
    });