2010-11-08 17 views
11

Estoy peleando con la casilla del complemento jQuery jsTree. Bien, he descubierto cómo manejar eventos al marcar o desmarcar la casilla de verificación. Si su utilidad puedo pegar un código:casilla jstree verificada en la carga

.bind("check_node.jstree", function(e, data) 
     { 

      if(data.rslt.obj !== undefined && data.rslt.obj.attr(\'id\') !== undefined) 
      { 

       jQuery.ajax({ 
         async : false, 
         type: "POST", 
         dataType: "json", 
         url: "adsmanager/adsfields/ajaxappendcategory", 
         data: 
         { 
          "id" : data.rslt.obj.attr(\'id\'), 
          "itemId" : "' . Yii::app()->getRequest()->getParam('id') . '", 
         }, 
         success: function(r) 
         { 
          if(r === undefined || r.status === undefined || !r.status) 
          { 
           data.rslt.obj.removeClass(\'jstree-checked\'); 

           data.rslt.obj.addClass(\'jstree-unchecked\'); 

          } 
          else 
          { 
           niceBox(\'ok\'); 
          } 
         } 
        }); 

      } 

      return true; 
     }) 

Con esta todo está bien, pero sé que puedo encontrar en cualquier lugar de cómo comprobar casillas de carga árbol, por ejemplo, si estoy usando jsTree como categoría de selector para mi news Artículo cuando creo nuevas noticias todo está bien y cuando quiero actualizar ese ítem necesito jsTree con categorías seleccionadas y es que no puedo encontrar ningún ejemplo de cómo seleccionar nodos al cargar jsTree.

¿Alguna ayuda con esta pregunta?

+0

He encontrado que es posible configurar las opciones 'seleccionadas' en su configuración como matriz, pero no está funcionando. – ignas

Respuesta

3

he encontrado la solución mediante el establecimiento de casilla opción two_state Plugin a cierto

"checkbox" => array( "two_state" => true) 

y luego si está utilizando datos XML añaden class="jstree-checked" en params

todo bien :)

buena suerte ;)

8

Si está utilizando JSON_DATA, agregue class:jstree-checked al objeto attr del nodo:

{ 
    "data": "node name", 
    "attr": { "id": "node id", "class":"jstree-checked" } 
} 
+0

Si está usando el formato JSON desde aquí: https://www.jstree.com/docs/json/, en lugar de 'attr', use 'a_attr' – thatOneGuy

+0

. Solo notado que esto solo muestra que está marcado, no lo configura en comprobado.Entonces, para desmarcarlo, tiene que hacer clic dos veces. Lo cual no tiene sentido Para evitar esto, debe establecer checked: true en el atributo de estado. Así que "state": {checked: true} – thatOneGuy

0

Puede ser que esto le ayudará más - v1 jstree

<script src="@Url.Content("~/Scripts/jquery.jstree.js")" type="text/javascript"></script> 
<script src="@Url.Content("~/Scripts/jquery.cookie.js")" type="text/javascript"></script> 

abajo - para la comprobación y se unen caso desmarque de jstree

<script type="text/javascript"> 
     $(document).ready(function() { 
      Refresh(); 
     }); 

     function Refresh() { 
      var dataId = {}; 
      $('#MainTree') 
       .bind("before.jstree", function (e, data) { 
       }) 
      .jstree({ 

       "json_data": { 
        ajax: { 

         "url": function (node) { 
          var url; 
          if (node == -1) { 
           url = ""; 
          } else { 
           var id = $(node).data("id"); 
           url = "?categoryId=" + id; 
          } 
          var productId = $("#Product_ProductId").val(); 
          if (!productId) { 
           url = "/Products/GetTreeData" + url; 
          } else { 
           url = "/Products/GetTreeData/" + productId + url; 
          } 
          return url; 
         }, 

         //"url": "@Url.Action("GetTreeData", "Categories")", 
         "type": "GET", 
         //"data": JSON.stringify(dataId), 
         "dataType": "json", 
         "contentType": "application/json charset=utf-8", 
        }, 
        progressive_render: true 
       }, 
       "themes": { 
        "theme": "classic", 
        "dots": true, 
        "icons": true, 
        "url": "@Url.Content("~/content/themes/classic/style.css")" 
       }, 
       "types": { 
        "max_depth": -2, 
        "max_children": -2, 
        "valid_children": ["folder"], 
        "types": { 
         "default": { 
          "valid_children": "none", 
          "icon": { 
           "image": "@Url.Content("~/gfx/file.png")" 
          } 
         }, 
         "folder": { 
          "valid_children": ["default", "folder"], 
          "icon": { 
           "image": "@Url.Content("~/gfx/folder.png")" 
          } 
         } 
        } 
       }, 
       "plugins": ["themes", "json_data", "ui", "types", "checkbox"] 

      }) 
      .bind("load_node.jstree", function (event, data) { 

       var productId = $("#Product_ProductId").val(); 
       if (!productId || productId < 1) { 
        data.inst.hide_checkboxes(); 
       } else 
        data.inst.change_state('li[selected=selected]', false); 
      }) 
      .bind("check_node.jstree", function (e, data) { 
       var productId = $("#Product_ProductId").val(); 
       if (!productId) 
        return; 
       $.post(
        "@Url.Action("ProductCategoriesSaveData", "Products")", 
        { 
         "ProductCategory.ProductId": productId, 
         "ProductCategory.CategoryId": $(data.rslt.obj).data("id") 
        }, 
        function (r) { 

         //Display message if any 
         if (r.Message) { 
          alert(r.Message); 
         } 

         //Display error if any 
         if (r.ValidationError) { 
          $.jstree.rollback(data.rlbk); 
          alert(r.ValidationError); 
         } else { 
          if (r.NewCreatedId) { 
           $(data.rslt.obj).data("mapId", r.NewCreatedId); 
          } 
         } 
        }); 
      }) 
      .bind("uncheck_node.jstree", function (e, data) { 
       var productId = $("#Product_ProductId").val(); 
       if (!productId) 
        return; 
       var mapId = $(data.rslt.obj).data("mapId"); 
       $.ajax({ 
        async: false, 
        type: 'POST', 
        url: "@Url.Action("ProductCategoryDelete", "Products")", 
        data: { 
         "id": mapId 
        }, 
        success: function (r) { 
         //Display message if any 
         if (r.Message) { 
          alert(r.Message); 
         } 

         //Display error if any 
         if (r.ValidationError) { 
          alert(r.ValidationError); 
         } else { 
          data.inst.refresh(); 
         } 
        } 
       }); 
      }); 
     } 
    </script> 

Servidor Asp.net MVC

3

Para la versión 3.2.1 JSTREE actual y los datos JSON tenemos que utilizar el estado: {verificado: true}

y añadir en las configuraciones de la sección casilla

"casilla de verificación": { "tie_selection": false }

este ejemplo funcione bien

data : [ 
      { "text" : "Root", state : { opened : true }, children : [ 

       { "text" : "Child 2", state : { checked : true }, 

] 
0

"state" : { "selected" : true } Hace una casilla seleccionada

$('#frmt').jstree({ 
     'core' : { 
      'data' : [{ 
        "text" : "root text", 
        "state" : { "opened" : true } , 
        "children" : [{ 
          "text" : "child text", 
          "id" : "idabc", 
          "state" : { "selected" : true } , 
          "icon" : "jstree-file", 

        }] 
       }, 

      ]}, 
      'checkbox': { 
         three_state: true 
      }, 
      'plugins': ["checkbox"] 
    });