Parent-und child-Checkboxen

  <div id="customerServices">
        <input id="s9" type="checkbox" /> Parent element<br/>
            <input id="s15" class="parent-s9" type="checkbox" /> Child element<br/>
            <input id="s16" class="parent-s9" type="checkbox" /> Child element<br/>
        <br/><br/><br/>

         <input id="s10" type="checkbox" /> Parent element2<br/>
            <input id="s151" class="parent-s10" type="checkbox" /> Child element2<br/>
            <input id="s161" class="parent-s10" type="checkbox" /> Child element2<br/>
          <br/><br/><br/>

           <input id="s101" type="checkbox" /> Parent element3<br/>
           <input id="s102" type="checkbox" /> Parent element4<br/>
     </div>

Gibt es einige Checkboxen auf einer Seite. Ich brauche:

  1. Überprüfen Sie alle Kinder-wenn Eltern überprüft wird.
  2. Deaktivieren Sie Elternteils, wenn alle Kinder sind deaktiviert.
  3. Überprüfen Elternteils wenn mindestens ein Kind markiert ist.

Dies ist etwas wenig code, aber es funktioniert nicht

  $('input[type=checkbox]').change(function() {
        var id = $(this).attr('id');
        var children = $('.parent-' + id);


        //Is this a child
        if (children.length)
        {
           //Is it checked
             if ($(this).is(':checked'))
             {
                 //Find the parent
                 var className = $(this).attr('class');
                 var pId = className.replace("parent-","");

                 //If the parent is not checked, then check this parent
                 if (!$(pId).is(':checked'))
                     $(pId).attr('checked','checked');
             }

            //Is it NOT checked
            else{
                //Do other childs are not checked too?
               //var className2 = $(this).attr('class');
                //$(className2)
            }
        }
        //If this is a parent, then check all childs
        esle{ 
            children.attr('checked', $(this).attr('checked'));

        }


     });
InformationsquelleAutor Alexandre | 2011-03-01
Schreibe einen Kommentar