-1

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>
  • I can't quite tell - because everything is surrounded with back-ticks, so this may be a template-literal? - but it seems like you're trying to use `"` characters inside of a string delimited with the same `"` characters: `$("input[name="seccionesG"] input:checkbox")`; this won't work unless you escape the inner pair: `$("input[name=\"seccionesG\"] input:checkbox")` or - preferably - use different quotes on the outer, and inner, strings. – David Thomas Mar 24 '23 at 15:42
  • yes I just saw it but even when adjusted it is still not working – JuanJoseVega Mar 24 '23 at 15:48
  • Where does it fail, what - if any - errors are reported? What's the HTML that your browser sees, and works with? (It definitely *shouldn't* include any php, which is almost certainly irrelevant to the problem.) It's worth pointing out the obvious issue that the `name` of the `` you show does not match the `name` you quote in your jQuery. – David Thomas Mar 24 '23 at 15:57

2 Answers2

0

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>

Amundria
  • 11
  • 3
0

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.

Zbigniew
  • 27,184
  • 6
  • 59
  • 66