skip to Main Content

I want to get the value of the checkbox that goes from being checked to unchecked.

<input type="checkbox" class="cbx" name="privilegiosG[]" id="privilegioG_<?= $privilegio->getId() ?>" value="<?= $privilegio->getId() ?>" <?= $checked; ?> />

tried this but it doesn’t work for me

<script type="text/javascript>"

    $("input[name='seccionesG'] input:checkbox").change(function() {
    var ischecked= $(this).is(":checked");
    if(!ischecked)
        alert("uncheckd " + $(this).val());
    });

</script>

2

Answers


  1. The code looks quite complicated for a simple task, this should work:

    <input type="checkbox" onchange="check_state(this);">
    
    <script type="text/javascript">
    
      function check_state(checkbox)
      {
        var val = checkbox.value;
        if(checkbox.checked)
        {
          //is checked
        }
        else
        {
          //is not checked
        }
      }
    
    </script>
    
    
    Login or Signup to reply.
  2. This is because of incorrect selector: input[name='seccionesG'] input:checkbox.

    It’s invalid, it’s means: find an input with name seccionesG, then inside it look for all inputs which are checkboxes.

    You can test it quickly by making a selector which will work for all checkboxes:

    $('input:checkbox').change(function() { 
        console.log(this.name, this.checked); 
    });
    

    Now, since your input name is privilegiosG[] then your selector should be:

    $('input[name="privilegiosG[]"]').change(function() { 
        console.log(this.name, this.checked); 
    });
    

    Note that you have a name with square brackets, which has a special meaning. For this reason you will need to add quotes to make it work. If you want to know more check jQuery selector for inputs with square brackets in the name attribute.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search