Search code examples
jqueryasp.netjquery-pluginstreeviewjquery-1.4

Check a radiobutton onload and expand the treeview accordingly using jquery


I have a treeview which is implemented using jquery Treeview version 1.4. TreeView is Implemented as below

<div id="container">
   <ul id="outerlist">
      <li>
         <span>level-1</span>
         <ul>
            <li>
               <span>level-2</span>
               <ul>
                  <li>
                     <input type="radio" name="lastnode" value="125" onclick="somefunction()" />
                     <span>lastnodetext</span>
                  </li>
               </ul>
            </li>
         </ul>
      </li>
   </ul>
</div>

What i need is ,onload the lastnode radiobutton to be checked and all its parent nodes to be expanded (note :there are multiple levels and radiobuttons in the tree).

Below is the code that i have used acheive this

$('#container').find(':radio').each(function (index, value) {
var $this = $(this);
if ($this.val() != undefined && $this.val() == "125") {
    $this.attr('checked', 'checked');
    $(this).parents('ul').show();
    return false;
}});

This code works perfectly fine in terms of selecting the radiobutton and expanding the level-2 and level-1 nodes. Although the Image (+ or -) does not change. How can i achieve this

Thanks in Advance!!


Solution

  • I went through the tree view document and found that you just need to add class="open" for the li which needs to be opened. This will handle all other things like adding images etc.

    Also you are doing your operation on single radio button, so don't need to iterate all and then choose your desired one. Instead, use jQuery selector to get only your radio button and do operation on it.

    Use below code -

    HTML : add css class to your first level and second level lis

    <div id="container">
       <ul id="outerlist">
          <li class="firstLevel">
             <span>level-1</span>
             <ul>
                <li class="secondLevel">
                   <span>level-2</span>
                   <ul>
                      <li>
                         <input type="radio" name="lastnode" value="125" onclick="somefunction()" />
                         <span>lastnodetext</span>
                      </li>
                   </ul>
                </li>
             </ul>
          </li>
       </ul>
    </div>
    

    jQuery : find first level and second level li to add open CSS class to it.

    var $radio = $('#container input[type="radio"][value="125"]');
    $radio.attr('checked',true);
    $radio.closest('.firstLevel').addClass('open');
    $radio.closest('.secondLevel').addClass('open');