Javascript checkbox onclick only with top one

I've got a small problem. Finally some code is working, but only with the first available checkbox. It should submit the form, which does, but again, only with one.

Used JavaScript:

<script type=\"text/javascript\"> 
    $(document).ready(function() {
         $('#opties').on('click', function(){
                if($(this).is(':checked')) {

Used PHP checkbox form items

<li class="list-group-item"><input type="checkbox" id="opties" name="opties_in[]" value="2240" checked > Item 2240</li>

<li class="list-group-item list-group-item-info"><input type="checkbox" id="opties" name="opties_in[]" value="2251" >Item 2251</li>

<li class="list-group-item"><input type="checkbox" id="opties" name="opties_in[]" value="2252" >Item 2252</li>

<li class="list-group-item list-group-item-info"><input type="checkbox" id="opties" name="opties_in[]" value="2250" >Item 2250</li>

The second question, for later ;-), is that it needs do do the action onchange, not on click. But that should be easy.

2 answers

  • answered 2017-10-11 10:11 bouguima

    you should use 'class' instead of a 'id' try to modify id="opties" by class="opties"

    $('.opties').on('click', function(){
                    if($(this).is(':checked')) {

  • answered 2017-10-11 10:11 Quentin

    Your HTML is invalid. Use a validator.

    An id must be unique in a document.

    To identify a group of related elements, use a class attribute and a class selector (which starts with a .).

    A checkbox is not a UI control that people expect to submit a form. You should strongly consider using a submit button instead.


    <button name="opties_in[2240]" value="turn off"> Item 2240 </button>

    That would remove the need for JavaScript.