Pregunta

Tengo una edición simple en línea en mi cuadrícula, y deseo confirmar el cambio cuando el usuario separa el cuadro de texto. El comportamiento predeterminado de jqGrid obliga al usuario a presionar 'Enter' para confirmar el cambio, pero esto no es intuitivo para nuestros usuarios.

texto alternativo http://i32.tinypic.com/e62iqh.jpg

    onSelectRow: function(id) {
         $(gridCoreGroups).editRow(id, true, undefined, function(response) 
         {
              alert("hello world");
         }
    }

He trabajado a través de los eventos provistos, pero todos ocurren como resultado de que el usuario presione 'Enter', lo que quiero evitar. ¿Hay algo que pueda conectar que desencadene una acción cuando el usuario separa esta celda?

¿Fue útil?

Solución 3

Mi solución fue utilizar selectores y eventos básicos de jQuery independientemente de la cuadrícula para detectar este evento. Utilizo los eventos en vivo y borrosos en los cuadros de texto en la cuadrícula para capturar el evento. Los dos eventos no son compatibles en combinación, por lo que este truco terminó siendo la solución:

Simulando " focus " y "desenfoque" en el método jQuery .live ()

Otros consejos

Para la edición en línea, puede lograr esto de varias maneras. Para vincular un evento onblur al campo de entrada utilizando el activador onSelectRow, eliminando la necesidad de editar y guardar botones, haga algo como esto:

  $('#gridId').setGridParam({onSelectRow: function(id){
    //Edit row on select
    $('#gridid').editRow(id, true); 

    //Modify event handler to save on blur.
    var fieldName = "Name of the field which will trigger save on blur.";
    //Note, this solution only makes sense when applied to the last field in a row.
    $("input[id^='"+id+"_"+fieldName+"']","#gridId").bind('blur',function(){
      $('#gridId').saveRow(id);
    });
  }});

Para aplicar un controlador de eventos en vivo jQuery a todas las entradas que pueden aparecer dentro de una fila (jqGrid etiqueta todas las entradas como rowId_fieldName), haga un bucle con el número de filas en su cuadrícula y haga algo como esto:

var ids = $("#gridId").jqGrid('getDataIDs');
for(var i=0; i < ids.length; i++){ 
  fieldName = "field_which_will_trigger_on_blur";
  $("input[id^='"+ids[i]+"_"+fieldName+"']","#gridId").live('blur',function(){
    $('#gridId').jqGrid('saveRow',ids[i]);
  });
}

Nota: Para usar el desenfoque con .live () como arriba, necesitará jQuery 1.4 o el parche ubicado en: Simulando " focus " y "desenfoque" en el método jQuery .live ()

Tenga cuidado con rowIds. Cuando empiece a ordenar, agregar y eliminar filas, puede encontrarse escribiendo un poco de jQuery para convertir los identificadores de fila en iRows o números de fila.

Si eres como yo y fuiste con la edición de celda individual, querrás modificar el disparador afterEditCell con algo como:

  $('#gridId').setGridParam({afterEditCell: function(id,name,val,iRow,iCol){
    //Modify event handler to save on blur.
    $("#"+iRow+"_"+name,"#gridId").bind('blur',function(){
      $('#gridId').saveCell(iRow,iCol);
    });
  }});

Espero que ayude ..

Esto es bastante horrible, pero es mi opinión sobre este problema, y ??es probablemente un poco más fácil y más genérico: presiona enter mediante programación cuando el elemento pierde el foco :)

       afterEditCell: function() {
            //This code saves the state of the box when focus is lost in a pretty horrible
            //way, may be they will add support for this in the future

            //set up horrible hack for pressing enter when leaving cell
            e = jQuery.Event("keydown");
            e.keyCode = $.ui.keyCode.ENTER;
            //get the edited thing
            edit = $(".edit-cell > *");
            edit.blur(function() {
                edit.trigger(e);
            });
        },

Agregue ese código a su código de configuración jqgrid.

Se supone que el último elemento editado es lo único con .edit-cell como td padre.

Sé que esta pregunta es antigua, pero la respuesta no está actualizada.

Se debe crear una variable global llamada lastsel y agregar lo siguiente al código jqGrid

 onSelectRow: function (id) {
            if (!status)//deselected
            {
                if ($("tr#" + lastsel).attr("editable") == 1) //editable=1 means row in edit mode
                    jQuery('#list1').jqGrid('saveRow', lastsel);
            }
            if (id && id !== lastsel) {
                jQuery('#list1').jqGrid('restoreRow', lastsel);
                jQuery('#list1').jqGrid('editRow', id, true);
                lastsel = id;
            }
        },

Tuve el mismo problema y probé las respuestas anteriores. Al final elegí una solución que inserta un " Enter " pulsación de tecla cuando el usuario abandona la pestaña.

// Call this function to save and unfinished edit
// - If an input exists with the "edit-call" class then the edit has
//   not been finished.  Complete the edit by injecting an "Enter" key press
function saveEdits() {
    var $input = $("#grid").find(".edit-cell input");
    if ($input.length == 1) {
        var e = $.Event("keydown");
        e.which = 13;
        e.keyCode = 13;
        $input.trigger(e);
    }
}

En lugar de usar selectRow use CellSelect .

onCellSelect: function (row, col, content, event) {
    if (row != lastsel) {
            grid.jqGrid('saveRow', lastsel);
            lastsel = row;
        }           
        var cm = grid.jqGrid("getGridParam", "colModel");
        //keep it false bcoz i am calling an event on the enter keypress
        grid.jqGrid('editRow', row, false);

        var fieldName = cm[col].name;
        //If input tag becomes blur then function called.
          $("input[id^='"+row+"_"+fieldName+"']","#gridId").bind('blur',function(e){
                grid.jqGrid('saveRow', row);
                saveDataFromTable();
        });

       //Enter key press event.
       $("input[id^='"+row+"_"+fieldName+"']","#gridId").bind('keypress',function(e){
            var code = (e.keyCode ? e.keyCode : e.which);
            //If enter key pressed then save particular row and validate.
            if( code == 13 ){
                grid.jqGrid('saveRow', row);
                saveDataFromTable();
            }
        });
    }

// saveDataFromTable () es la función que valida mis datos.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top