I have 2 fields with checkboxes. I need that when I uncheck one, and if another checkbox is not activated, then activate it. In general, I need to leave no empty flags.

    1 answer 1

    1) In some situations, this is enough:

    <div> <input type = "checkbox" name = "ch1" onchange = "if ( !this.checked ) this.nextElementSibling.checked = true;" > <input type = "checkbox" name = "ch2" onchange = "if ( !this.checked ) this.previousElementSibling.checked = true;" > </div> 

    PS: checkbox 's should go in a row

    2) It is possible so:

    Js:

     function recheck( el, id ){ if ( !el.checked ) document.getElementById( id ).checked = true; } 

    HTML:

     <input type = "checkbox" name = "ch1" id = "ch1" onchange = "recheck( this, 'ch2' );"> <input type = "checkbox" name = "ch2" id = "ch2" onchange = "recheck( this, 'ch1' );"> 

    3) In order not to generate unnecessary events:

    Js:

     function recheck( el, id ){ if ( !el.checked ){ var el2 = document.getElementById( id ); if ( !el2.checked ) el2.checked = true; } } 

    HTML:

     <input type = "checkbox" name = "ch1" id = "ch1" onchange = "recheck( this, 'ch2' );"> <input type = "checkbox" name = "ch2" id = "ch2" onchange = "recheck( this, 'ch1' );"> 
    • thanks, the first was enough - Vitaly Zaslavsky