반응형

Another and easy way of increasing any number of levels(dimensions) in Jqgrid is by adding setGroupHeaders that number of times

If my columns are like, ColNames = ['Id','Date', 'Client', 'Amount','Tax','Total','Notes'];

Now add setGroupHeaders Like

jQuery("#list").jqGrid('setGroupHeaders', {
          useColSpanStyle: true, 
          groupHeaders:[
            {startColumnName: 'id', numberOfColumns: 1, titleText: '.'},
            {startColumnName: 'date', numberOfColumns: 8, titleText: 'Nice'},
            ]   
        });
        jQuery("#list").jqGrid('setGroupHeaders', {
          useColSpanStyle: true, 
          groupHeaders:[
            {startColumnName: 'id', numberOfColumns: 1, titleText: '.'},
            {startColumnName: 'date', numberOfColumns: 4, titleText: 'rice'},
            {startColumnName: 'total', numberOfColumns: 2, titleText: 'dice'}
            ]   
        });

        jQuery("#list").jqGrid('setGroupHeaders', {
          useColSpanStyle: true, 
          groupHeaders:[
            {startColumnName: 'id', numberOfColumns: 1, titleText: '.'},
            {startColumnName: 'date', numberOfColumns: 2, titleText: 'Price'},
            {startColumnName: 'amount', numberOfColumns: 2, titleText: 'Shiping'},
            {startColumnName: 'total', numberOfColumns: 2, titleText: 'bipping'}
            ]   
        });

Following is the output

| .  |                       Nice                              |
----------------------------------------------------------------
| .  |                 rice                |       dice        |
----------------------------------------------------------------    
| .  |       Price     |      Shipping     |       bipping     | 
----------------------------------------------------------------    
| id |  Date  | Client |  Amount   |  Tax  | Total  |  Notes   |   



The reason of restriction of one level of group headers in jqGrid exist because jqGrid provide more as just displaying the headers. You can see on the example of the demo created for the answer that the column headers after grouping are clickable (to sort by the column) and resizable (by drag&drop on the separator between column headers). If you use titleText option of setGroupHeaders you can include HTML fragments, inclusive <table> element, in the column header. It gives you the possibility to display milti-level headers. One can include resizable: false to deny resizing or one can write which custom resizeStop handler which resizes columns in the table added by titleText option of setGroupHeaders.

All what I described above sound theoretical. So I wrote the small demo which demonstrates the approach. It displays the following grid

enter image description here

The demo is written not for the common case, but it's clear that one can use it as basis to more common solution. In any way I hope that you can change it to any your multi-level grid.

The most important parts of the demo you will find below:

var grid = $("#list"),
    setHeaderWidth = function () {
        var $self = $(this),
            colModel = $self.jqGrid("getGridParam", "colModel"),
            cmByName = {},
            ths = this.grid.headers, // array with column headers
            cm,
            i,
            l = colModel.length;

        // save width of every column header in cmByName map
        // to make easy access there by name
        for (i = 0; i < l; i++) {
            cm = colModel[i];
            cmByName[cm.name] = $(ths[i].el).outerWidth();
        }
        // resize headers of additional columns based on the size of
        // the columns below the header
        $("#h1").width(cmByName.amount + cmByName.tax + cmByName.total - 1);
        $("#h2").width(cmByName.closed + cmByName.ship_via - 1);
    };

grid.jqGrid({
    ...
    colModel: [
        {name: "id", width: 65, align: "center", sorttype: "int", hidden: true},
        {name: "invdate", width: 80, align: "center", sorttype: "date",
            formatter: "date", formatoptions: {newformat: "d-M-Y"}, datefmt: "d-M-Y"},
        {name: "name", width: 70},
        {name: "amount", width: 75, formatter: "number", sorttype: "number", align: "right"},
        {name: "tax", width: 55, formatter: "number", sorttype: "number", align: "right"},
        {name: "total", width: 65, formatter: "number", sorttype: "number", align: "right"},
        {name: "closed", width: 75, align: "center", formatter: "checkbox",
            edittype: "checkbox", editoptions: {value: "Yes:No", defaultValue: "Yes"}},
        {name: "ship_via", width: 100, align: "center", formatter: "select",
            edittype: "select", editoptions: {value: "FE:FedEx;TN:TNT;IN:Intim", defaultValue: "IN"}},
        {name: "note", width: 70, sortable: false}
    ],
    resizeStop: function () {
        // see http://stackoverflow.com/a/9599685/315935
        var $self = $(this),
            shrinkToFit = $self.jqGrid("getGridParam", "shrinkToFit");

        $self.jqGrid("setGridWidth", this.grid.newWidth, shrinkToFit);
        setHeaderWidth.call(this);
    }
});
grid.jqGrid ("navGrid", "#pager",
             {edit: false, add: false, del: false, refresh: true, view: false},
             {}, {}, {}, {multipleSearch: true, overlay: false});
grid.jqGrid("setGroupHeaders", {
    useColSpanStyle: true,
    groupHeaders: [{
        startColumnName: "amount",
        numberOfColumns: 5,
        titleText:
            '<table style="width:100%;border-spacing:0px;">' +
            '<tr><td id="h0" colspan="2"><em>Details</em></td></tr>' +
            '<tr>' +
                '<td id="h1">Price</td>' +
                '<td id="h2">Shiping</td>' +
            '</tr>' +
            '</table>'
    }]
});
$("th[title=DetailsPriceShiping]").removeAttr("title");
$("#h0").css({
    borderBottomWidth: "1px",
    borderBottomColor: "#c5dbec", // the color from jQuery UI which you use
    borderBottomStyle: "solid",
    padding: "4px 0 6px 0"
});
$("#h1").css({
    borderRightWidth: "1px",
    borderRightColor: "#c5dbec", // the color from jQuery UI which you use
    borderRightStyle: "solid",
    padding: "4px 0 4px 0"
});
$("#h2").css({
    padding: "4px 0 4px 0"
});
setHeaderWidth.call(grid[0]);
shareimprove this answer


Posted by 1010
반응형

http://www.trirand.com/jqgridwiki/doku.php?id=wiki:inline_editing

Inline Editing

Inline editing is a quick way to update database information by making changes directly in the row of the grid, as seen in the image below:

To use Inline Editing, users select a row with the mouse. In response, jqGrid converts each editable field to a data entry cell, as seen in the Name and Price fields above. Cells that aren't editable, such as the ID field above, don't change appearance and remain read-only. Whether an individual column is editable or read-only is controlled by setting the attribute in the ColModel.

When finished, users hit the “enter” key to send the data to the server.

Software Requirement & Installation

In order to use this functionality, make sure you put a check mark by the Inline Editing and Common modules when you downloaded jqGrid. For more information refer toDownload.

Note to Developers - Source code can be found in the grid.inlinedit.js file, located in the src directory.

The methods used in inline editing are a sub-set of those of the parent grid. They are described below.

Methods

For inline editing, we have five additional methods (of the Grid API) available:

  • editRow
  • saveRow
  • restoreRow
  • addRow
  • inlineNav

These methods can be called, of course, only on an already-constructed grid, from a button click or from an event of the grid itself:

Example:

jQuery("#grid_id").jqGrid({
...
   onSelectRow: function(id){
     if(id && id!==lastSel){ 
        jQuery('#grid_id').restoreRow(lastSel); 
        lastSel=id; 
     }
     jQuery('#grid_id').editRow(id, true); 
   },
...
});

In this example, if another was row being edited and has not yet been saved, the original data will be restored and the row “closed” before “opening” the currently-selected row for editing (where lastSel was previously defined as a var). 
If you want to save instead to restore the editing you can call saveRow in place of restoreRow.

editRow

Calling conventions:

jQuery("#grid_id").editRow(rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);

or when we use the new API

jQuery("#grid_id").jqGrid('editRow',rowid, keys, oneditfunc, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);

where

  • grid_id is the already constructed grid
  • rowid: the id of the row to edit
  • keys: when set to true we can use [Enter] key to save the row and [Esc] to cancel editing.
  • oneditfunc: fires after successfully accessing the row for editing, prior to allowing user access to the input fields. The row's id is passed as a parameter to this function.

succesfunc, url, extraparam, aftersavefunc,errorfunc and afterrestorefunc are described below, in the saveRow section.

The row can not be edited if it has class 'not-editable-row' instead that in colModel some fields can have a property editable set to true.

When set in the editRow the parameter function oneditfunc should not be enclosed in quotes and not entered with () - show just the name of the function.

As of version 4 of the jqGrid, parameters passed to the method can be enclosed in object see below

Calling with object parameter:

jQuery("#grid_id").jqGrid('editRow',rowid, 
{ 
    keys : true, 
    oneditfunc: function() {
        alert ("edited"); 
    }
});

The default object parameter is as follow:

editparameters = {
	"keys" : false,
	"oneditfunc" : null,
	"successfunc" : null,
	"url" : null,
        "extraparam" : {},
	"aftersavefunc" : null,
	"errorfunc": null,
	"afterrestorefunc" : null,
	"restoreAfterError" : true,
	"mtype" : "POST"
}
 
jQuery("#grid_id").jqGrid('editRow',rowid,  parameters);

If keys is true, then the remaining settings – successfunc, url, extraparam, aftersavefunc, errorfunc and afterrestorefunc - are passed as parameters to the saveRow method when the [Enter] key is pressed (saveRow does not need to be defined as jqGrid calls it automatically). For more information see saveRow method below. 

When this method is called on particular row, jqGrid reads the data for the editable fields and constructs the appropriate elements defined in edittype and editoptions

saveRow

Saves the edited row.

Calling convention:

jQuery("#grid_id").saveRow(rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);

or when we use the new API

jQuery("#grid_id").jqGrid('saveRow',rowid, successfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc);

As of version 4 of the jqGrid, parameters passed to the method can be enclosed in object see below

Calling with object parameter:

jQuery("#grid_id").jqGrid('saveRow',rowid, 
{ 
    successfunc: function( response ) {
        return true; 
    }
});

The default object parameter is as follow:

saveparameters = {
	"successfunc" : null,
	"url" : null,
        "extraparam" : {},
	"aftersavefunc" : null,
	"errorfunc": null,
	"afterrestorefunc" : null,
	"restoreAfterError" : true,
	"mtype" : "POST"
}
 
jQuery("#grid_id").jqGrid('saveRow',rowid,  saveparameters);

where

  • rowid: the id of the row to save
  • succesfunc: if defined, this function is called immediately after the request is successful. This function is passed the data returned from the server. Depending on the data from server; this function should return true or false.
  • url: if defined, this parameter replaces the editurl parameter from the options array. If set to 'clientArray', the data is not posted to the server but rather is saved only to the grid (presumably for later manual saving).
  • extraparam: an array of type name: value. When set these values are posted along with the other values to the server.
  • aftersavefunc: if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the response from the server request. Also the event is called too when the url is set to 'clientArray'.
  • errorfunc: if defined, this function is called after the data is saved to the server. Parameters passed to this function are the rowid and the the response from the server request.
  • afterrestorefunc if defined, this function is called in restoreRow (in case the row is not saved with success) method after restoring the row. To this function we pass the rowid

When set in the saveRow the parameters functions should not be enclosed in quotes and not entered with () - show just the name of the function.

Except when url (or editurl) is 'clientArray', when this method is called, the data from the particular row is POSTED to the server in format name: value, where the name is a name from colModel and the value is the new value. jqGrid also adds, to the posted data, the pair id: rowid. For example,

jQuery("#grid_id").saveRow("rowid", false);

will save the data to the grid and to the server, while

jQuery("#grid_id").saveRow("rowid", false, 'clientArray');

will save the data to the grid without an ajax call to the server.

or using the new API

jQuery("#grid_id").jqGrid('saveRow',"rowid", false);
jQuery("#grid_id").jqGrid('saveRow',"rowid", false, 'clientArray');

Using the object parameter this should be written:

jQuery("#grid_id").jqGrid('saveRow',"rowid", { url : 'clientArray' });

Additionally to this we have other two options which can be set in grid options.

PropertyTypeDescriptionDefault
ajaxRowOptionsobjectThis option allow to set global ajax settings for the row editiing when we save the data to the server. Note that with this option is possible to overwrite all current ajax setting in the save request including the complete event.empty object
serializeRowDatapostdataIf set this event can serialize the data passed to the ajax request when we save a row. The function should return the serialized data. This event can be used when a custom data should be passed to the server - e.g - JSON string, XML string and etc. To this event is passed the data which will be posted to the servernull

restoreRow

This method restores the data to original values before the editing of the row.

Calling convention:

jQuery("#grid_id").restoreRow(rowid, afterrestorefunc);

or when we use the new API

jQuery("#grid_id").jqGrid('restoreRow',rowid, afterrestorefunc);

As of version 4 of the jqGrid, parameters passed to the method can be enclosed in object

Calling with object parameter:

jQuery("#grid_id").jqGrid('restoreRow',rowid, 
{ 
    "afterrestorefunc" : function( response ) {
        // code here 
    }
});

The default object parameter is as follow:

restoreparameters = {
	"afterrestorefunc" : null
}
 
jQuery("#grid_id").jqGrid('restoreRow',rowid,  restoreparameters);

where

  • rowid is the row to restore
  • afterrestorefunc if defined this function is called in after the row is restored. To this function we pas the rowid

addRow

This method add a row for inline edit.

Calling convention:

jQuery("#grid_id").addRow(rowid, parameters);

or when we use the new API

jQuery("#grid_id").jqGrid('addRow',parameters);

where parameters is a object and has the following default values:

parameters =
{
    rowID : "new_row",
    initdata : {},
    position :"first",
    useDefValues : false,
    useFormatter : false,
    addRowParams : {extraparam:{}}
}

Where

  • rowID - (string) the value of the id of the new added row
  • initdata - (object) the object of the pair name:value where the name correspond to the name in colMode. When set this is the initial value of the the cell.
  • position - (string) determines the position of the new adde row in the grid. Default is first. Can have a value last to be added at the last position
  • useDefValues - (boolean) if set to true uses the defaultValue property in editoptions of the colModel
  • useFormatter : (boolean) if set to true synchronises the parameters from the formatter actions
  • addRowParams : (object) parameters which are passed to the addRow - they are the same as of editRow

Actually this method uses two already constructed methods. When calling the method first executes the addRowData method which add a local row. After this the method call editRow method to edit the row. If the keys parameter is set to true and the user press ESC key the row is automatically deleted.

inlineNav

Add a navigators buttons which correspond to the inline methods addRow, editRow, saveRow, restoreRow. In order to use this method a navGrid method should be called before to call this method

Calling convention:

jQuery("#grid_id").navGrid(pagerid, {...});
jQuery("#grid_id").inlineNav(pagerid, parameters);

or when we use the new API

jQuery("#grid_id").jqGrid('navGrid',pagerid, {...});
jQuery("#grid_id").jqGrid('inlineNav',pagerid, parameters);

Where parameters is a object with the following default values

parameters = { 
   edit: true,
   editicon: "ui-icon-pencil",
   add: true,
   addicon:"ui-icon-plus",
   save: true,
   saveicon:"ui-icon-disk",
   cancel: true,
   cancelicon:"ui-icon-cancel",
   addParams : {useFormatter : false},
   editParams : {}
}
PropertyTypeDescriptionDefault1)
addbooleanEnables or disables the add action in the Navigator. When the button is clicked a addRow with parameters addParams is executedtrue
addiconstringSet a icon to be displayed if the add action is enabled. Note that currently only icons from UI theme images can be addedui-icon-plus
addtextstringThe text than can be set in the add buttonempty
addtitlestringThe title that appear when we mouse over to the add button (if enabled)Add new row
editbooleanEnables or disables the edit action in the Navigator. When the button is clicked a editRow method is executed with editParamsparameter the - current selected rowtrue
editiconstringSet a icon to be displayed if the edit action is enabled. Note that currently only icons from UI theme images can be usedui-icon-pencil
edittextstringThe text than can be set in the edit buttonempty
edittitlestringThe title that appear when we mouse over to the edit button (if enabled)Edit selected row
positionstringDetermines the position of the Navigator buttons in the pager. Can be left, center and right.left
savebooleanEnables or disables the save button in the pager. When the button is clicked a saveRow method is executed with editParams parameterstrue
saveiconstringSet a icon to be displayed if the refresh action is enabled. Note that currently only icons from UI theme images can be usedui-icon-disk
savetextstringThe text than can be set in the refresh buttonempty
savetitlestringThe title that appear when we mouse over to the refresh button (if enabled)Save row
cancelbooleanEnables or disables the cancel(restore) button in the pager.When the button is clicked a restoreRow method is executed with parameters editParamstrue
canceliconstringSet a icon to be displayed if the search action is enabled. Note that currently only icons from UI theme images can be usedui-icon-cancel
canceltextstringThe text than can be set in the cancel buttonempty
canceltitlestringThe title that appear when we mouse over to the search button (if enabled)Cancel trow editiong
addParamsobjectParameters that can be passed to the addRow method in navigator. For detailed information see addRow parameters{useFormatter : false}
editParamsobjectParameters that can be passed to the editRow, saveRow, restoreRow methods in navigator. For detailed information the related methods{}

Notes

How is the data organized

When the row is edited and the input elements are created we set the following rules: 

  • the table row becomes attribute editable=“1”
  • the array savedRow (option in the grid) is filled with the values before the editing. This is a name:value pair array with additional pair id:rowid
  • Hidden fields are not included
  • The id of the editable element is constructed as 'rowid_'+ the name from the colModel array. Example if we edit row with id=10 and the only editable element is 'myname' (from colModel) then the id becomes 10_myname.
  • The name of the editable element is constructed from the name of the colModel array - property - name
  • after the row is saved or restored the editable attribute is set to “0” and the savedRow item with id=rowid is deleted

What is posted to the server?

When the data is posted to the server we construct an object {} that contain(s):

  • the name:value pair where the name is the name of the input element represented in the row (this is for all input elements)
  • additionally we add a pair id:rowid where the rowid is the id of the row
  • if the extraparam parameter is not empty we extend this data with the posted data

Example

...
<head>
<script type="text/javascript">
jQuery(document).ready(function(){ 
  var lastsel2
  jQuery("#rowed5").jqGrid({        
    datatype: "local",
    height: 250,
    colNames:['ID Number','Name', 'Stock', 'Ship via','Notes'],
    colModel:[
      {name:'id',index:'id', width:90, sorttype:"int", editable: true},
      {name:'name',index:'name', width:150,editable: true, editoptions:{size:"20",maxlength:"30"}},
      {name:'stock',index:'stock', width:60, editable: true, edittype:"checkbox",editoptions: {value:"Yes:No"}},
      {name:'ship',index:'ship', width:90, editable: true, edittype:"select",formatter:'select', editoptions:{value:"FE:FedEx;IN:InTime;TN:TNT;AR:ARAMEX"}},                       
      {name:'note',index:'note', width:200, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}}                      
              ],
    onSelectRow: function(id){
      if(id && id!==lastsel2){
        jQuery('#rowed5').restoreRow(lastsel2);
        jQuery('#rowed5').editRow(id,true);
          lastsel2=id;
      }
    },
    editurl: "server.php",
    caption: "Input Types"
  });
  var mydata2 = [
    {id:"12345",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FE"},
    {id:"23456",name:"Laptop",note:"Long text ",stock:"Yes",ship:"IN"},
    {id:"34567",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TN"},
    {id:"45678",name:"Speakers",note:"note",stock:"No",ship:"AR"},
    {id:"56789",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FE"},
    {id:"67890",name:"Play Station",note:"note3",stock:"No", ship:"FE"},
    {id:"76543",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"AR"},
    {id:"87654",name:"Server",note:"note2",stock:"Yes",ship:"TN"},
    {id:"98765",name:"Matrix Printer",note:"note3",stock:"No", ship:"FE"}
    ];
  for(var i=0;i<mydata2.length;i++)
    jQuery("#rowed5").addRowData(mydata2[i].id,mydata2[i]);
});
</script>
</head>
<body>
<table id="rowed5" class="scroll"></table>
</body>
</html>

Will produce this: Inline editing

1) English variant

Discussion

Satish2010/04/05 12:49

Is it possible to have diff fields for form edit and inline edit in a same grid?

zbacsi2010/08/02 20:23

There is an escaping bug with special characters. Try insert <script>alert('hello')</script> into a field. It should be displayed as common text, but its executed. This is a common problem with inline editing.

Take a look at http://www.jstree.com/documentation/crrm (rename section)

Nicolas Mercado2010/10/05 04:47

Hi. I can't get editRow to eval the JSON in responseText. May there be an encoding issue? I've got something like

jQuery(”#tableId”).editRow(

  rowId,
  true,
  null,
  function(xhr) {
var data = eval(xhr.responseText);   // nothing happens
if(data.result == "success") {
    jQuery("#"+tableId).jqGrid('delRowData',rowId);
}
  },
  ajaxurl,
  postData

);

Thanks

santiago kci2011/01/11 22:16

jQuery(”#tableId”).editRow( rowId, true, null, function(xhr) { var data = eval('(' + xhr.responseText + ')'); if(data.result == “success”) { jQuery(”#”+tableId).jqGrid('delRowData',rowId); } }, ajaxurl, postData );

Regards. Santiago

pascal2011/02/04 16:13

How is it possible to edit inline the grid without sending the data to the server, like shown on the example “Edit Row” (on the demo web site of trirand.com). The reason is that I have no PHP server and I want to save the grid locally.

And my second question: I wanted to serialize the grid data in a XML string: is it included in this plugin ?

Thanks, Pascal

pascal2011/02/07 13:43

After reading more carefully this page (sorry was too lazy …), I 've found the solution to save inside the grid only:

⇒> jQuery(”#grid_id”).saveRow(“rowid”, false, 'clientArray');

Data will not be posted to server. I am happy !!!

Waldney Souza de Andrade2011/05/03 06:00

I'm using the jqgrid 4 development, so i want to colaborate with that project.

I found a problem with inline editing. jqgrid 4 sets focus by static value. So i'm using onCellSelect and just added an extra param to editRow method. So i did edit grid.inlinedir.js, adding focus on the parameters and removing the variable declaration 'focus=null'.

Waldney Souza de Andrade2011/05/03 06:14

I did send the iCol param of onCellSelect by the focus param to the editRow method.

That is my code:

var lastsel; $(function(){ jQuery(”#rowed6”).jqGrid({ url:“listJSON”, editurl:“updateJSON”, datatype: “json”, height: 250, colNames:['Id','Data Inicial','Data final','Versão', 'Finalidade do Arquivo','codFin'], colModel:[ {name:'id',index:'id', width:90, sorttype:“int”}, {name:'dtIni',index:'dtIni',classes:'dtPicker',width:90,editable:true,sorttype:'date', editoptions:{ dataInit:function (elem) { $(elem).datepicker(); } }}, {name:'dtFin',index:'dtFin',classes:'dtPicker',width:90,editable:true,sorttype:'date', editoptions:{ dataInit:function (elem) { $(elem).datepicker(); } }}, {name:'codVer',index:'codVer',width:150,editable:true,editoptions:{size:“20”,maxlength:“30”}}, {name:'descCodVer',index:'descCodVer',width:150,editable:true,editoptions:{size:“20”,maxlength:“30”}}, {name:'codFin',index:'codFin',hidden: true} ], caption: “Date Picker Integration”, onCellSelect:function(rowid,iCol,cellcontent,e){ if(rowid && rowid!==lastsel){ jQuery('#rowed6').restoreRow(lastsel); lastsel=rowid; } jQuery('#rowed6').editRow(rowid, true,iCol); }, autowidth:true, rowNum:10, rowList:[10,20,30], pager: '#prowed3', sortname: 'id', viewrecords: true, sortorder: “asc” }); jQuery(”#rowed6”).jqGrid('navGrid',”#prowed3”,{edit:false,add:false,del:false}); });

grid.inlinedir.js line 13 - editRow : function(rowid,keys,focus,oneditfunc,succesfunc, url, extraparam, aftersavefunc,errorfunc, afterrestorefunc)

line 35 - var $t = this, nm, tmp, editable, cnt=0, svr={}, ind,cm;

Diosney Sarmiento Herrera2011/08/21 23:56

It could be great if the data being edited do not change, then the data won't be saved to the server (that is the expected behaviour, I think ;) ).

Currently there is any way to do this?

Diosney Sarmiento Herrera2011/08/22 01:52

There is a primitive solution to sort this problem at: http://stackoverflow.com/questions/6360512/jqgrid-inline-edit-detect-dirty-changed-cells/7141667

Demetrios C. Christopher2011/09/30 21:56

I'm a long-time fan of jqGrid and I hate to make my first official contact on the website a technical issue but this one has me really stumped (and I have rummaged through the documentation and searched all over the internets) …

I am using a jqGrid (latest version) in inline-edit mode to manage data completely on the client side (dataType is 'local'; I upload it to the server once the user is ready to move to the next phase). I use a OnSelectRow event to save the row being edited when you click on a different row. Both the editRow and saveRow methods in the event handler make a reference to 'clientArray'. editRow also uses keys = true (so I expect it to act accordingly on the Esc and Enter keys).

I am seeing this buggy behavior where pressing Enter only makes it “appear” that the data has been saved. The data in the underlying array (getGridParam('data')) is still unchanged. The only way data gets truly saved is when I click to a different row (and the OnSelectRow handler takes care of saving the row explicitly). Pressing Enter with keys = true (according to the source code) calls saveRow with rowId and “o” which appears to be the settings array starting with “keys”. Well, that would yield very different results given the saveRow method signature starts with “successfunc”. I have a feeling that this is causing the Enter-based saveRow to behave quite differently from the explicit saveRow in OnSelectRow because the parameter 'clientArray' is misaligned and the saveRow method treats it as some other sort of storage location (server-, url-based?). Any thoughts?

Thank you, all, in advance.

Jair Muñoz Gomez2011/11/02 19:06

Tengo un problema con el dataInit reulta que deseo mostrar el formulario de editar y tengo dos campos fecha y quiero a ambos asignar el “datepicker”; lo asigna corectamente a ambos pero cuando deseo cambiar la fecha del segundo campo se pasa el foco al primer campo: Les dejo mi codigo…

jQuery(”#listado_es”).jqGrid({

	height: 200,
	url:'reges_detalle.php?q=1',
	datatype: "xml",
	colNames:['Fecha inicio','Fecha fin', 'Tipo', 'estado'],
	colModel:[
		{name:'horaent',index:'horaent',width:130,editable:true,searchtype:"date",
			sorttype:"datetime",
			formatter:'datetime', 
			editrules:{custom:true, custom_func:valfechahora},
			searchoptions:{dataInit:function(elb){$(elb).datepicker({dateFormat:'yy-mm-dd'});} },
			editoptions:{
				size:25,
			/*	dataInit:function(horaent){
					$(horaent).datepicker();
				}*/
			}
		},
		{name:'horasal',index:'horasal',width:130,editable:true,searchtype:"date",
			sorttype:"datetime", 
			formatter:'datetime', 
			editrules:{custom:true, custom_func:valfechahora},
			searchoptions:{
				dataInit:function(elex){
					
					$(elex).datepicker({dateFormat:'yy-mm-dd'});
				} 
			},
			editoptions:{
				size:25,
				/* 
				dataInit:function(horasal){
					$(horasal).datepicker();
				}*/
			}
		},
		
		{name:'nom_dep',index:'nom_dep', width:200,editable:true,edittype:"select", editoptions:{
			dataUrl:'includes/cargar_selec_normal.php'+parametros,
		}},
		{name:'pta_ent',index:'pta_ent', width:200},
	],
	
	rowNum:10,
	rowList:[5,10,20],
	pager: '#pager_es',
	sortname: 'horaent',
	viewrecords: true,
	sortorder: "asc",
	editurl:'opera.php',
	caption:"--------------"
})
jQuery("#listado_es").jqGrid('navGrid','#pager_es',{add:false,edit:false,del:false}, {}, {}, {}, {multipleSearch:true});

Espero me puedan ayudar a solucionar este problema

Austin2011/11/29 22:47

Is there an easy way to check if the row is open for editing before acting on the key events. Currently I'm looping through RowIDs and comparing them and if it's the same then I save it.

Gabriele2012/02/03 13:03

Hi, i've found a small bug into the createEl function of grid.common.js (i use the 3.8.2 version but i see that is present in the 4.3.1 too). If i set a dataUrl for create a select element within inline editing, if the value (or text) of options contains html entity, in my case blank space (&nbsp;), when i click on row and go in edit mode the selected element not correspond with the option with the same text.

This occurs because this code checks for the text() or val() of an option into the value (ovm) (or values if multiselect) : setTimeout(function(){ $(“option”,elem).each(function(i){ if(i===0) { this.selected = ””; } $(this).attr(“role”,”option”); if($.inArray($.trim($(this).text()),ovm) > -1 || $.inArray($.trim($(this).val()),ovm) > -1 ) { this.selected= “selected”; if(!msl) { return false; } } }); },0); I solved adding the checks for the html() …so:

 ''if($.inArray($.trim($(this).html()),ovm) > -1 || $.inArray($.trim($(this).text()),ovm) > -1 || $.inArray($.trim($(this).val()),ovm) > -1 )''

Hope this help, Bye Gabriele

Jair Muñoz Gomez2012/05/22 17:27

Haz lo siguiente:

Dentro de la funcion dataInit $(elemento_select).trigger('change') algo asi:

editoptions:{

size:25,
dataInit:function(ele){
	$(ele).trigger('change')
      }

}

Darren Boss2012/03/07 10:10

I am having an issue with getting the keys (Esc and Enter) to work on a new record. Below is the code for my button:

$(”#t_clients”).append('<button type=“button” onclick=“$(\'#clients\').jqGrid(\'addRow\', {addRowParams: {extraparam: {keys: true}} });”>Add Client</button>');

According to the documentation, it seems like this should be working. Unfortunately, it doesn't. Any help would be greatly appreciated.

Varela Gonzalo2012/06/04 22:37

when using actions formatter (http://www.trirand.com/jqgridwiki/doku.php?id=wiki:predefined_formatter) restore rows like this

if(id && id!==lastsel2){ jQuery.fn.fmatter.rowactions(lastsel2,'rowed5','cancel',0); jQuery('#rowed5').editRow(id,true); lastsel2=id; }

instead of

if(id && id!==lastsel2){ jQuery('#rowed5').restoreRow(lastsel2); jQuery('#rowed5').editRow(id,true); lastsel2=id; }

It is more complete, not only restore row but restore edit buttons also. you can call the function using the onEdit event on colmodel.

;)

Paulo Diogo2012/09/05 16:29

put formatter:'select' in select columns to get the value instead of text of the line


Posted by 1010
반응형
This example demonstartes the new Frozen Columns
Try to scroll horizontally.


Frozen Header
 
InvNo
 
Client
 
Amount
 
Tax
 
Total
 
Closed
 
Shipped via
 
Notes
13Client 31,000.000.001,000.00  
8Client 3200.000.00200.00  
12Client 2700.00140.00840.00  
10Client 2100.0020.00120.00  
11Client 1600.00120.00720.00  
9Client 1200.0040.00240.00  
5Client 3100.000.00100.00 no tax at all
7Client 2120.0012.00134.00  
6Client 150.0010.0060.00  
4Client 3150.000.00150.00 no tax
 
InvNo
 
Client
13Client 3
8Client 3
12Client 2
10Client 2
11Client 1
9Client 1
5Client 3
7Client 2
6Client 1
4Client 3
Page of 2
View 1 - 10 of 13


HTML Java Scrpt code jQuery("#gfrc1").jqGrid({ url:'server.php?q=4', datatype: "json", colNames: ['InvNo', 'Client', 'Amount', 'Tax', 'Total', 'Closed', 'Shipped via', 'Notes'], colModel: [ {name: 'id', index: 'id', width: 60, align: 'center', sorttype: 'date', frozen : true}, {name: 'name', index: 'name', width: 100, frozen : true }, {name: 'amount', index: 'amount', width: 75, formatter: 'number', sorttype: 'number', align: 'right'}, {name: 'tax', index: 'tax', width: 75, formatter: 'number', sorttype: 'number', align: 'right'}, {name: 'total', index: 'total', width: 75, formatter: 'number', sorttype: 'number', align: 'right'}, {name: 'closed', index: 'closed', width: 75, align: 'center', formatter: 'checkbox', edittype: 'checkbox', editoptions: {value: 'Yes:No', defaultValue: 'Yes'}}, {name: 'ship_via', index: 'ship_via', width: 120, align: 'center', formatter: 'select', edittype: 'select', editoptions: {value: 'FE:FedEx;TN:TNT;IN:Intim', defaultValue: 'Intime'}}, {name: 'note', index: 'note', width: 120, sortable: false} ], rowNum:10, width:700, rowList:[10,20,30], pager: '#pgfrc1', sortname: 'invdate', viewrecords: true, sortorder: "desc", jsonReader: { repeatitems : false }, shrinkToFit: false, caption: "Frozen Header", height: 'auto' }); jQuery("#gfrc1").jqGrid('setFrozenColumns');


Posted by 1010
반응형

출처 : http://blog.naver.com/bboy12/10187788656



jqGrid 옵션을 사용하여 틀고정을 처리할 수 있습니다.

 


 

사용방법

 

colModel 틀고정 항목에 옵션 추가  

frozen:true

 

메소드 호출  

$("#listInfo").jqGrid("setFrozenColumns");

 

 

 

 

주의사항1

 

cellEditsortNamesortAble 옵션과 사용불가


 

해당옵션이 true면 틀고정기능은 false 반환

 

 

 

주의사항2


틀고정 옵션은 jqGrid를 모두 그린 뒤


틀고정항목(영역)을 위에 덮는 형식입니다.


(위 그림에 틀고정영역이 위에 떠있다고 보시면 됩니다.)


완전히 위에 겹치지 않기 때문에 css를 조정해줘야 합니다.

 

즐거운 하루되세요


Posted by 1010
반응형

http://www.ama3.com/anytime/

Posted by 1010
반응형

http://braincast.nl/samples/jsoneditor/

Posted by 1010
반응형


今回は昨年末(2011/12/20)にリリースされたjqGrid4.3.1の新機能を実際に使ってみましょう。
#というのも、実際使おうとしたらVersion.4台でサンプルプログラム載せている
 ところがほとんどなかったので私にとっての備忘録です。
 今回は最終成果物(DLすればすぐ動かせるもの)もこのページに掲載します。

今回試すのは以下の機能です。

  • 行/列のセルマー(ColSpanとかRowSpanとかいうアレ)
  • スクロール時のセル固定(Excelで見かけるアレ)

ん〜、にしてもどんどんExcelと同じようなことができるようになってきてますね。
便利になるのはいいとしても、パフォーマンス大丈夫なのかな?
大量データを描画する際に間違いなくパフォーマンス問題を起こしそうな。。。

まぁ、今回はそこには触れずに上記新機能を実装します。

完成イメージ

今回は先に結論と成果物を共有しちゃいます。
jgGrid_sample.zip 直
これをDLしてsample.htmlを開くと、こんな画面が開けます。

スクロールすると、こんな感じにセル固定もします。

ちなみに、これら、デモサイトの作りと異なる作りをしています。
つまり、、、デモサイトの情報はこれから紹介する問題に対応していないんです!!!
古い!!!
早期改修を期待します。

内容解説

Group Header

まずはセルマージのアレを実現します。
これはjQueryメソッド内で以下を呼んであげれば実現完了です。

$("#sample1").jqGrid('setGroupHeaders', {
	useColSpanStyle: true,
	groupHeaders:[
		{startColumnName: 'age', numberOfColumns: 3, titleText: '<em>Details</em>'},
		{startColumnName: 'note1', numberOfColumns: 3, titleText: '<em>Notes</em>'}
	]
});

「useColSpanStyle: true」という指定で縦セル結合の設定。
groupHeadersで横セルのマージを行っています。
なんと簡単なことか!

Frozen Cols

次にセル固定についてです。jqGrid4.3.0から、何と1つの設定とメソッド呼び出しで
機能として実現されます。
#まずはデモサイト通りの実装です。
colModelの設定で以下を設定します。

frozen:true
/** 例:{name:'name',index:'name',width:150,align:'center',classes:'name_class',frozen:true}, */

次に、jQueryの最後で以下のメソッドを呼び出します。

$("#sample1").jqGrid('setFrozenColumns');
/** #sample1はサンプルのテーブルID */

これだけで実装完了です。これも簡単!

ハマりどころ

[Frozen Cols]そもそもテーブル操作しないとセル固定が中途半端に実現される

上記のとおりjQuery内で最後にメソッド呼び出しをすると、、、こうなります。
Windows 7 64-bit環境)

忌々しき事態です、まったく使い物になりません。

ちなみにテーブル操作を行って一度でもテーブルをリフレッシュさせると問題は起こりません。。。

色々調べましたが、全く同じ症状の人がいましたね。掲示板にて外人さんが質問しています。
英語のフォーラムなのであまり読んでませんが要約するとこんな感じでしょうか。

ユーザ
そのままsetFrozenColumnsメソッド使ってもうまく固定されないから
リロードする仕組み入れてるんだけど、リロードってパフォーマンス落ちるよね?
何とかならないの?
製作者
こっちじゃ確認できないよ、環境悪いんでない?

・・・(こんなやり取りを何度か繰り返す。)

製作者
確かに問題がありそうだね、こちらでも確認したよ。
ユーザ
現状はこうやって解消してますわぁ。

gridComplete: function() {
mygrid.jqGrid('setFrozenColumns');
}

なるほど、colModelの属性としてgridCompleteに設定するのね。
これならgrid完成後にセル固定処理が走るから問題なさそうですね。
これで一つ解決

[Frozen Cols]セル固定状態のフィルタリングで処理がストップする

上記gridCompleteに記述することにすると、次にこの問題にあたります。
セル固定やマージは一度だけ行えばいいのに、gridComplete内に記述すると、
フィルタなどの再描画の際にもさらにマージしようとするから生じるのかな?

いずれにしても、処理がストップしてフィルタリングができません。
一応現在は下記のようにして回避しています。

var isLoaded = false;

・・・

gridComplete: function(){
  if (!isLoaded == true){
    $("#sample1").jqGrid('setGroupHeaders', {
      useColSpanStyle: true,
      groupHeaders:[
        {startColumnName: 'age', numberOfColumns: 3, titleText: '<em>Details</em>'},
        {startColumnName: 'note1', numberOfColumns: 3, titleText: '<em>Notes</em>'}
      ]
    });
    $("#sample1").jqGrid('setFrozenColumns');
    isLoaded = true;
  }
},

一度でもセルマージなどの読み込みを行ったら、その後は行わない、という実装です。
一応今のところこれで問題が発生しなくなっています。
(他の機能との連携を全て試しているわけではないのでどうなるかわかりませんが。。。)

いずれにしても、本体の改修でこの辺の問題がFixされることを期待しています。
jqGridは最近とても短い期間でBugFix版を出しているので、
(4.3.0から4.3.1へのUpdateも10日足らず)すぐに修正されることを願っています。

では、今回はこの辺で。


Posted by 1010
반응형
http://stackoverflow.com/q/12606945/315935
jqgridDnD.html
Posted by 1010
반응형

JSONP

From Wikipedia, the free encyclopedia

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of thesame-origin policy.

Note that for JSONP to work, a server must know how to reply with JSONP-formatted results. JSONP does not work with JSON-formatted results. The JSONP parameters passed as arguments to a script are defined by the server.

Reason for JSONP[edit]

Under the same-origin policy (SOP)JavaScript code loaded from one domain is not allowed to fetch data from another domain. However, this restriction does not apply to the <script> tag, which can specify a URL of JavaScript code to load from a remote server in a src attribute. This was used to work around the SOP limitations by pointing the src to aweb service returning dynamically generated JavaScript code (JSONP), instead of JSON data. Because the code is loaded by the <script> tag, it can be normally executed and return the desired data block, thus bypassing SOP.

Execution of raw JavaScript from a third party raised security concerns and creates a possible vulnerability.[1] Cross-origin resource sharing (CORS) is a more recent method of getting data from a server in a different domain, which addresses some of those criticisms. All modern browsers now support CORS making it a viable cross-browser alternative.

How it works[edit]

To see how this technique works, first consider a URL request that returns JSON data. A JavaScript program might request this URL via XMLHttpRequest, for example. Suppose the user ID of Foo is 1234. A browser requesting the URLhttp://server2.example.com/Users/1234, passing the ID of 1234, would receive something like:

{
    "Name": "Foo",
    "Id": 1234,
    "Rank": 7
}

This JSON data could be dynamically generated, according to the query parameters passed in the URL.

Here, an HTML <script> element specifies for its src attribute a URL that returns JSON:

<script type="application/javascript"
        src="http://server2.example.com/Users/1234">
</script>

The browser will, in order, download the script file, evaluate its contents, interpret the raw JSON data as a block, and throw a syntax error. Even if the data were interpreted as a JavaScript object literal, it could not be accessed by JavaScript running in the browser, since without a variable assignment object literals are inaccessible.

In the JSONP usage pattern, the URL request pointed to by the <script>'s src attribute returns JSON data, with a function call wrapped around it. In this way, a function that's already defined in the JavaScript environment can manipulate the JSON data. A JSONP payload might look like this:

functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});

The function call is the "P" of JSONP—the "padding" around the pure JSON, or according to some[2] the "prefix". By convention, the browser provides the name of the callback function as a named query parameter value, typically using the name jsonp or callback as the named query parameter field name, in its request to the server, e.g.,

<script type="application/javascript"
        src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</script>

In this example, the received payload would be:

parseResponse({"Name": "Foo", "Id": 1234, "Rank": 7});

Padding[edit]

While the padding (prefix) is typically the name of a callback function that is defined within the execution context of the browser, it may also be a variable assignment, an if statement, or any other JavaScript statement. The response to a JSONP request is not JSON and is not parsed as JSON; the returned payload can be any arbitrary JavaScript expression, and it does not need to include any JSON at all. But conventionally, it is a JavaScript fragment that invokes a function call on some JSON-formatted data.

Said differently, the typical use of JSONP provides cross-domain access to an existing JSON API, by wrapping a JSON payload in a function call.

Script element injection[edit]

JSONP makes sense only when used with a script element. For each new JSONP request, the browser must add a new <script> element, or reuse an existing one. The former option—adding a new script element—is done via dynamic DOM manipulation, and is known as script element injection. The <script> element is injected into the HTML DOM, with the URL of the desired JSONP endpoint set as the "src" attribute. This dynamic script element injection is usually done by a JavaScript helper library. jQuery and other frameworks have JSONP helper functions; there are also standalone options.[3][4][5]

The dynamically injected script element for a JSONP call looks like this:

<script type="application/javascript"
        src="http://server2.example.com/Users/1234?jsonp=parseResponse">
</script>

After the element is injected, the browser evaluates the element, and performs an HTTP GET on the src URL, retrieving the content. Then the browser evaluates the return payload as JavaScript. This is typically a function invocation.

In that way, the use of JSONP can be said to allow browser pages to work around the same-origin policy via script element injection.

The script runs within the scope of the including page and, as such, is still subject to cross-domain restrictions relative to the including page's domain. This means that one cannot, for example, load a library hosted on another site via JSONP and then make XMLHttpRequest requests to that site (unless CORS is supported) although one could use such a library to make XMLHttpRequests to one's own site.

Cross-domain requests using a proxy server[edit]

The JavaScript same-origin policy normally prevents browsers from sending AJAX requests to a different domain and receiving a response (newer browsers that support CORS can relax this constraint). A cooperating proxy server, however, does not have such restrictions and can relay a browser request to a server in a separate domain, store the result, and then return that JSON payload when the browser makes a second request. The server would be instructed within the first request to store the output (POST returning JSON payload) temporarily into a local store (for example memcached or within a session variable), and a second request from the browser then would fetch the cached response to the initial query.[6] The xd_arbiter.php used by Facebook's JS SDK is a popular example of this cooperating server technique.[7]

Security concerns[edit]

Including script tags from remote servers allows the remote servers to inject any content into a website. If the remote servers have vulnerabilities that allow JavaScript injection, the page served from the original server is exposed to an increased risk. If an attacker can inject any JavaScript into the original web page, then that code can retrieve additional JavaScript from any domain. The Content Security Policy HTTP Header lets web sites tell web browsers which domains scripts should be included from.

An effort is underway to define a safer strict subset definition for JSON-P[8] that browsers would be able to enforce on script requests with a specific MIME type such as "application/json-p". If the response didn't parse as strict JSON-P, the browser could throw an error or just ignore the entire response. For the moment however the correct MIME type is "application/javascript" for JSONP.[9]

Cross-site request forgery[edit]

Native deployments of JSONP are subject to cross-site request forgery (CSRF or XSRF) attacks.[10] Because the HTML<script> tag does not respect the same-origin policy in web browser implementations, a malicious page can request and obtain JSON data belonging to another site. This will allow the JSON-encoded data to be evaluated in the context of the malicious page, possibly divulging passwords or other sensitive data if the user is currently logged into the other site.

This is problematic only if the JSON-encoded data contains sensitive information which should not be disclosed to a third party, and the server depends on the browser's same-origin policy to block the delivery of the data in the case of an improper request. There is no problem if the server determines the propriety of the request itself, only putting the data on the wire if the request is proper. Cookies are not by themselves adequate for determining if a request was authorized. Exclusive use of cookies is subject to cross-site request forgery.

History[edit]

In July 2005 George Jempty suggested an optional variable assignment be prepended to JSON.[11][12] The original proposal for JSONP, where the padding is a callback function, appears to have been made by Bob Ippolito in December 2005[13] and is now used by many Web 2.0 applications such as Dojo ToolkitGoogle Web Toolkit and Web services.

An unnamed process equivalent to JSONP has been used by PostX envelopes (now owned by Cisco Systems and deployed on Cisco's Email Security Appliance and Cisco Registered Envelope Service (CRES)) since May 2002.

See also[edit]

References[edit]

External links[edit]


Posted by 1010
반응형

This jQuery plugin converts a properly formatted table, having thead and tbody elements (tfoot optional), into a scrollable table. Scrollable tables are most useful when having to display lots of tubular data in a fixed space.

Show Me The Money (Demo)

citystate codeziplatitudelongitudecounty
HoltsvilleNY0050140.8152-73.0455Suffolk
HoltsvilleNY0054440.8152-73.0455Suffolk
AdjuntasPR0060118.1788-66.7516Adjuntas
AguadaPR0060218.381389-67.188611Aguada
AguadillaPR0060318.4554-67.1308Aguadilla
AguadillaPR0060418.4812-67.1467Aguadilla
AguadillaPR0060518.429444-67.154444Aguadilla
MaricaoPR0060618.182778-66.980278Maricao
AnascoPR0061018.284722-67.14Anasco
AngelesPR0061118.286944-66.799722Utuado
AreciboPR0061218.4389-66.6924Arecibo
AreciboPR0061318.1399-66.6344Arecibo
AreciboPR0061418.1399-66.6344Arecibo
BajaderoPR0061618.428611-66.683611Arecibo
BarcelonetaPR0061718.4525-66.538889Barceloneta
10215--9

Table Scroll Plugin Overview

The tablescroll jQuery plugin is a simple markup manipulation plugin, it will manipulate the table, create a couple of new elements and wrap everything in a DIV.

Using the plugin is pretty straight forward, when you download the plugin you can view the demo file to get up to speed and begin working with it immediately.

The HTML TABLE markup is also pretty basic:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<table id="thetable" cellspacing="0">
<thead>
    <tr>
      <td>city</td>
      <td>state code</td>
      <td>zip</td>
      <td>latitude</td>
      <td>longitude</td>
      <td>county</td>
    </tr>
</thead>
<tfoot>
    <tr>
      <td>city</td>
      <td>state code</td>
      <td>zip</td>
      <td>latitude</td>
      <td>longitude</td>
      <td>county</td>
    </tr>
</tfoot>
<tbody>
    <tr class="first">
      <td>Holtsville</td>
      <td>NY</td>
      <td>00501</td>
      <td>40.8152</td>
      <td>-73.0455</td>
      <td>Suffolk</td>
    </tr>
    <tr>
      <td>Holtsville</td>
      <td>NY</td>
      <td>00544</td>
      <td>40.8152</td>
      <td>-73.0455</td>
      <td>Suffolk</td>
    </tr>
    <tr>
      <td>Adjuntas</td>
      <td>PR</td>
      <td>00601</td>
      <td>18.1788</td>
      <td>-66.7516</td>
      <td>Adjuntas</td>
    </tr>
</tbody>
</table>

Styling the table should go pretty smoothly, but be warned, the plugin does some width/height calculations which require the styles to be in place prior to doing the calculations.

Here is the demo CSS which should get you started:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
.tablescroll {
    font: 12px normal Tahoma, Geneva, "Helvetica Neue", Helvetica, Arial, sans-serif;
}
 
.tablescroll td,
.tablescroll_wrapper,
.tablescroll_head,
.tablescroll_foot {
    border:1px solid #ccc;
}
 
.tablescroll td {
    padding:3px 5px;
    border-bottom:0;
    border-right:0;
}
 
.tablescroll_wrapper {
    background-color:#fff;
    border-left:0;
}
 
.tablescroll_head,
.tablescroll_foot {
    background-color:#eee;
    border-left:0;
    border-top:0;
    font-size:11px;
    font-weight:bold;
}
 
.tablescroll_head {
    margin-bottom:3px;
}
 
.tablescroll_foot {
    margin-top:3px;
}
 
.tablescroll tbody tr.first td {
    border-top:0;
}

The plugin is basic and only has a few options:

1
2
3
4
5
6
7
$.fn.tableScroll.defaults =
{
    flush: true, // makes the last thead and tbody column flush with the scrollbar
    width: null, // width of the table (head, body and foot), null defaults to the tables natural width
    height: 100, // height of the scrollable area
    containerClass: 'tablescroll' // the plugin wraps the table in a div with this css class
};

Like most jQuery plugins, implementation is a snap:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
jQuery(document).ready(function($)
{
    $('#thetable').tableScroll({height:200});
 
    // other examples
 
    // sets the table to have a scrollable area of 200px
    $('#thetable').tableScroll({height:200});
 
    // sets a hard width limit for the table, setting this too small
    // may not always work
    $('#thetable').tableScroll({width:400});
 
    // by default the plugin will wrap everything in a div with this
    // css class, if it finds that you have manually wrapped the
    // table with a custom element using this same css class it
    // will forgo creating a container DIV element
    $('#thetable').tableScroll({containerClass:'myCustomClass'});
});

Like many projects, we developers build out of necessity. I couldn’t quite find what I needed, so i wrote my own! This plugin accomplished all of what I needed, and I thought it useful enough that I would share. If you have any feature requests and/or bug reports please let me know. And the plugin name is pretty generic too (if you have a better one, feel free to drop me a line).

I’ve tested the plugin on Windows with Chrome, FF 3.6, IE 6, IE 8, Safari 4. If anyone is on a Mac, please let me know what your results are?

Download

jQuery TableScroll plugin, this project is on github

Posted by 1010
반응형

Example: Standard jQuery drag-and-drop

 

출처 : http://wwwendt.de/tech/dynatree/doc/samples.html

 

jquery_dynatree-1_2_5-all.zip

 

This sample uses the standard jQuery draggable and droppable.

Skin:

This tree allows dragging.

This tree allows dropping.

Active node: -
Active node: Sub-item 2.1.1(_4)

Drag me around

Drop something here


Dynatree DEVELOPMENT, jQuery UI 1.8.24, jQuery 1.8.2

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1">
 
<title>Dynatree - Example</title>
<!--
  <script src="../jquery/jquery.cookie.js" type="text/javascript"></script>
  <script src="../jquery/jquery.js" type="text/javascript"></script>
  <script src="../jquery/jquery-ui.custom.js" type="text/javascript"></script>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>
-->

 
<script src="../jquery/jquery.cookie.js" type="text/javascript"></script>
 
<script src="../jquery/jquery.js" type="text/javascript"></script>
 
<script src="../jquery/jquery-ui.custom.js" type="text/javascript"></script>

 
<link href="../src/skin/ui.dynatree.css" rel="stylesheet" type="text/css" id="skinSheet">
 
<script src="../src/jquery.dynatree.js" type="text/javascript"></script>

 
<style type="text/css">
   
#draggableSample, #droppableSample {
      height
:100px;
      padding
:0.5em;
      width
:150px;
      border
:1px solid #AAAAAA;
   
}
   
#draggableSample {
      background
-color: silver;
      color
:#222222;
   
}
   
#droppableSample {
      background
-color: maroon;
      color
: white;
   
}
   
#droppableSample.drophover {
      border
: 1px solid green;
   
}
 
</style>

 
<!-- (Irrelevant source removed.) -->

<script type="text/javascript"><!--
$
(function(){
 
// --- Initialize first Dynatree -------------------------------------------
  $
("#tree").dynatree({
    initAjax
: {
      url
: "sample-data3.json"
   
},
    onLazyRead
: function(node){
     
// Mockup a slow reqeuest ...
      node
.appendAjax({
        url
: "sample-data2.json",
        debugLazyDelay
: 750 // don't do thi in production code
     
});
   
},
    onActivate
: function(node) {
      $
("#echoActive").text(node.data.title + "(" + node.data.key + ")");
   
},
    onDeactivate
: function(node) {
      $
("#echoActive").text("-");
   
},
    dnd
: {
      revert
: false, // true: slide helper back to source if drop is rejected
      onDragStart
: function(node) {
       
/** This function MUST be defined to enable dragging for the tree.
         *  Return false to cancel dragging of node.
         */

        logMsg
("tree.onDragStart(%o)", node);
       
if(node.data.isFolder){
         
return false;
       
}
       
return true;
     
},
      onDragStop
: function(node) {
        logMsg
("tree.onDragStop(%o)", node);
     
}
   
}
 
});
 
// --- Initialize second Dynatree ------------------------------------------
  $
("#tree2").dynatree({
    initAjax
: {
      url
: "sample-data3.json"
   
},
    onLazyRead
: function(node){
     
// Mockup a slow reqeuest ...
      node
.appendAjax({
        url
: "sample-data2.json",
        debugLazyDelay
: 750 // don't do thi in production code
     
});
   
},
    onActivate
: function(node) {
      $
("#echoActive2").text(node.data.title + "(" + node.data.key + ")");
   
},
    onDeactivate
: function(node) {
      $
("#echoActive2").text("-");
   
},
    onLazyRead
: function(node){
      node
.appendAjax({
        url
: "sample-data2.json"
     
});
   
},
    dnd
: {
      autoExpandMS
: 1000,
      preventVoidMoves
: true, // Prevent dropping nodes 'before self', etc.
      onDragEnter
: function(node, sourceNode) {
       
/* sourceNode may be null for non-dynatree droppables.
         * Return false to disallow dropping on node. In this case
         * onDragOver and onDragLeave are not called.
         * Return 'over', 'before, or 'after' to force a hitMode.
         * Any other return value will calc the hitMode from the cursor position.
         */

        logMsg
("tree.onDragEnter(%o, %o)", node, sourceNode);
       
// For the sake of this example deny dropping over folders
       
if(node.data.isFolder){
         
return false;
       
}
       
return true;
//                return "over";
     
},
      onDragOver
: function(node, sourceNode, hitMode) {
       
/* Return false to disallow dropping this node.*/
//         if(node.data.isFolder){
//           var dd = $.ui.ddmanager.current;
//           dd.cancel();
//           alert("folder");
//         }
        logMsg
("tree.onDragOver(%o, %o, %o)", node, sourceNode, hitMode);
     
},
      onDrop
: function(node, sourceNode, hitMode, ui, draggable) {
       
/* This function MUST be defined to enable dropping of items on the tree.
         * sourceNode may be null, if it is a non-Dynatree droppable.
         */

        logMsg
("tree.onDrop(%o, %o)", node, sourceNode);
       
var copynode;
       
if(sourceNode) {
          copynode
= sourceNode.toDict(true, function(dict){
            dict
.title = "Copy of " + dict.title;
           
delete dict.key; // Remove key, so a new one will be created
         
});
       
}else{
          copynode
= {title: "This node was dropped here (" + ui.helper + ")."};
       
}
       
if(hitMode == "over"){
         
// Append as child node
          node
.addChild(copynode);
         
// expand the drop target
          node
.expand(true);
       
}else if(hitMode == "before"){
         
// Add before this, i.e. as child of current parent
          node
.parent.addChild(copynode, node);
       
}else if(hitMode == "after"){
         
// Add after this, i.e. as child of current parent
          node
.parent.addChild(copynode, node.getNextSibling());
       
}
     
},
      onDragLeave
: function(node, sourceNode) {
       
/** Always called if onDragEnter was called.
         */

        logMsg
("tree.onDragLeave(%o, %o)", node, sourceNode);
     
}
   
}
 
});
 
// --- Initialize simple draggable sample ----------------------------------
  $
("#draggableSample").draggable({
//      revert: "invalid", // slide back, when dropping over non-target
    revert
: function(dropped){
     
// Return `true` to let the helper slide back.
     
if(typeof dropped === "boolean"){
       
// dropped == true, when dropped over a simple, valid droppable target.
       
// false, when dropped outside a drop target.
       
return !dropped;
     
}
     
// Drop comes from another tree. Default behavior is to assume
     
// a valid drop, since we are over a drop-target.
     
// Therefore we have to make an extra check, if the target node
     
// was rejected by a Dynatree callback.
     
var helper = $.ui.ddmanager && $.ui.ddmanager.current && $.ui.ddmanager.current.helper;
     
var isRejected = helper && helper.hasClass("dynatree-drop-reject");
     
return isRejected;
     
},
    connectToDynatree
: true,
    cursorAt
: { top: -5, left:-5 },
    helper
: "clone"
 
});
 
// --- Initialize simple droppable sample ----------------------------------
  $
("#droppableSample").droppable({
    hoverClass
: "drophover",
    addClasses
: true,
//    tolerance: "pointer",
    over
: function(event, ui) {
      logMsg
("droppable.over, %o, %o", event, ui);
   
},
    drop
: function(event, ui) {
     
var source = ui.helper.data("dtSourceNode") || ui.draggable;
      $
(this).addClass("ui-state-highlight").find("p").html("Dropped " + source);
//      alert("dropped");
   
}
 
});
 
<!-- (Irrelevant source removed.) -->
});
--></script>
</head>

<body class="example">
 
<h1>Example: Standard jQuery drag-and-drop</h1>
 
<p class="description">
    This sample uses the standard jQuery draggable and droppable.
 
</p>
 
<div>
    Skin:
   
<select id="skinCombo" size="1">
     
<option value="skin">Standard ('/skin/')</option>
     
<option value="skin-vista">Vista ('/skin-vista/')</option>
   
</select>
 
</div>

 
<table>
 
<thead>
 
<tr>
   
<th>
   
<p>This tree allows dragging.</p>
   
</th>
   
<th>
   
<p>This tree allows dropping.</p>
   
</th>
 
</tr>
 
</thead>
 
<tbody>
 
<tr valign="top">
   
<td>
     
<div id="tree"> </div>
   
</td>
   
<td>
     
<div id="tree2"></div>
   
</td>
 
</tr>
 
<tr>
   
<td>
     
<div>Active node: <span id="echoActive">-</span></div>
   
</td>
   
<td>
     
<div>Active node: <span id="echoActive2">-</span></div>
   
</td>
 
</tr>
 
<tr>
   
<td>
     
<div id="draggableSample" class="ui-widget-content">
       
<p>Drag me around</p>
     
</div>
   
</td>
   
<td>
     
<div id="droppableSample" class="ui-widget-content">
       
<p>Drop something here</p>
     
</div>
   
</td>
 
</tr>
 
</tbody>
 
</table>

 
<!-- (Irrelevant source removed.) -->
</body>
</html>
Posted by 1010
반응형


 menuCd

 highMenuCd

 menuNm

 orderNo

 

 1001

 0

 고객

 1

 1002

 1001

 고객리스트

 2
 1003  1002  대기리스트  3
 1004  0  게시판  4
 1005  1004  자유게시판  5
 1006  1004  유머게시판  6

 


위와 같은 형식의 데이터를 DB에서 뽑아 냈을때 오른쪽과 같이 화면에 표현하고 싶었다.


우선 Tree는 jQuery기반의 드래그앤랍이 기능이 되는 "jquery.dynatree.js" 를 선택했다.


이제 위 2차원 배열형태의 데이터를 dynatree가 요구하는 데이터형태로 변환을 해야 한다.

요구하는 데이터형태는 트리형식으로 아래와 같은 스타일로 만들어주면 된다.


[

{"isFolder":"true","title":"고객","children":[

{"isFolder":"true","title":"고객리스트" }

...

    ]

....

]


위와 같은 형태로 만들려고 삽질 좀 하다가 javascript 기반으로 잘 만들어져있는 소스를 구글링을통해 발견하여 그것을 java기반으로 수정 하였습니다.

(http://programmingsummaries.tistory.com/250)


package com.ezwel.welfare.core.util;
 
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
 
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
 
/**
 * JSON관련 가공에 필요한 함수들
 * @auther ddakker 2013. 12. 12.
 */
public class JsonUtil {
    private static final Log log = LogFactory.getLog(JsonUtil.class);
    /**
     * 2차원 배열의 부모/자식 관계의 데이터를 트리형식으로 재나열 한다.
     * @param list          2차원 배열
     * @param rootId        최상위 id
     * @param idKey         유니크한 키(id가 될 필드명)
     * @param pIdKey        부모키(pId가 될 필드명)
     * @param titleKey      메뉴명이 표시될 필드명
     * @return
     * @auther ddakker 2013. 12. 12.
     */
    public static List<Map<String, Object>> convertorTreeMap(final List<Map<String, Object>> list, String rootId, final String idKey, final String pIdKey, final String titleKey){
        return convertorTreeMap(list, rootId, idKey, pIdKey, titleKey, null);
    }
    /**
     * 2차원 배열의 부모/자식 관계의 데이터를 트리형식으로 재나열 한다.
     * @param list          2차원 배열
     * @param rootId        최상위 id
     * @param idKey         유니크한 키(id가 될 필드명)
     * @param pIdKey        부모키(pId가 될 필드명)
     * @param titleKey      메뉴명이 표시될 필드명
     * @param orderKey      정렬이 필요한경우 정령 필드명
     * @return
     * @auther ddakker 2013. 12. 12.
     */
    public static List<Map<String, Object>> convertorTreeMap(List inList, String rootId, final String idKey, final String pIdKey, final String titleKey, final String orderKey){
        List<Map<String, Object>> treeList = new ArrayList<Map<String,Object>>();   // 최종 트리
         
        if( inList == null || inList.size() == 0 throw new RuntimeException("List<Map> 데이터가 없습니다.");
        if( inList.get(0) == null )                 throw new RuntimeException("Map 데이터가 없습니다.");
         
        final List<Map<String, Object>> list = new ArrayList<Map<String,Object>>(); // 원본데이터(Bean일경우 Map으로 변환)
        Iterator iter;
        for( iter=inList.iterator(); iter.hasNext(); ) {
            try{
                Object obj = iter.next();
                if( obj instanceof Map ) {
                    list.add((Map<String, Object>) obj);
                }else{
                    list.add((Map<String, Object>) BeanUtils.describe(obj));
                }
            }catch (Exception e) {
                throw new RuntimeException("Collection -> List<Map> 으로 변환 중 실패: " + e);
            }
        }
         
         
        int listLength = list.size();
        int loopLength = 0;
        final int[] treeLength = new int[] { 0 };
         
        while ( treeLength[0] != listLength && listLength != loopLength++ ) {
            for ( int i=0; i<list.size(); i++ ) {
                Map<String, Object> item = list.get(i);
                if ( rootId.equals((String)item.get(pIdKey)) ) {
                    Map<String, Object> view = new HashMap<String, Object>(item);
                    view.put("title", item.get(titleKey));
                    view.put("children", new ArrayList<Map<String,Object>>());
                     
                    treeList.add(view);
                    list.remove(i);
                     
                    treeLength[0]++;
                     
                     
                    if( orderKey != null ){
                        Collections.sort(treeList, new Comparator<Map<String, Object>>(){
                            public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                                // TODO Auto-generated method stub
                                return ((String)arg0.get(orderKey)).compareTo((String)arg1.get(orderKey));
                            }
                        });
                    }
                    view.put("isFolder", "true");
                     
                    break;
                }else{
                    new InnerClass(){
                        public void getParentNode(List<Map<String, Object>> children, Map<String, Object> item ) {
                            for ( int i=0; i<children.size(); i++ ) {
                                Map<String, Object> child = children.get(i);
                                if ( child.get(idKey).equals(item.get(pIdKey)) ) {
                                    Map<String, Object> view = new HashMap<String, Object>(item);
                                    view.put("title", item.get(titleKey));
                                    view.put("children", new ArrayList<Map<String,Object>>());
                                    ((List<Map<String,Object>>) child.get("children")).add(view);
                                     
                                    treeLength[0]++;
                                     
                                    list.remove(list.indexOf(item));
                                    view.put("isFolder", "true");
                                     
                                    if( orderKey != null ){
                                        Collections.sort(((List<Map<String,Object>>) child.get("children")), new Comparator<Map<String, Object>>(){
                                            public int compare(Map<String, Object> arg0, Map<String, Object> arg1) {
                                                // TODO Auto-generated method stub
                                                return ((String)arg0.get(orderKey)).compareTo((String)arg1.get(orderKey));
                                            }
                                        });
                                    }
                                    break;
                                }else{
                                    if( ((List<Map<String,Object>>) child.get("children")).size() > 0 ){
                                        getParentNode((List<Map<String,Object>>) child.get("children"), item);
                                    }
                                }
                            }
                        }
                    }.getParentNode(treeList, item);
                }
            }
        }
        return treeList;
    }
     
    public interface InnerClass {
        public void getParentNode(List<Map<String, Object>> list, Map<String, Object> item );
    }
     
}

출처 : http://ddakker.tistory.com/296

Posted by 1010
반응형

if ($.browser.msie) {
    $
(".audio").prepend($("<embed>").attr({
       
'src':'/resources/voices/'+voice+'.wav',
       
'HIDDEN':'true',
       
'AUTOSTART':'true'
   
}));
}else if($.browser.safari){
    $
(".audio").removeAttr("style");
    $
(".audio").prepend($("<object></object>").attr({
       
'type':'audio/x-wav',
       
'data':'/resources/voices/'+voice+'.wav',
       
'width':'0',
       
'height':'0'
   
}));
    $
("object:first").prepend($("<param>").attr({
       
'name':'autoplay',
       
'value':'true'
   
}));
}else{
    $
(".audio").prepend($("<audio></audio>").attr({
       
'src':'/resources/voices/'+voice+'.wav',
       
'volume':0.4,
       
'autoplay':'autoplay'
   
}));
}

Posted by 1010
반응형

[jQuery] 제이쿼리(jQuery) 플러그인 목록 모음입니다.

 

해당 소스는 라이선스 조건을 확인한 다음에 사용해주세요^^ 라이센스 정보 보기

 

-BACKGROUND-

 

[jQuery] 001. 백그라운드 이미지를 활용 할 수 있는 제이쿼리 [다운받기][미리보기]

[jQuery] 002. 백그라운드에 영상을 제어하는 제이쿼리입니다.[다운받기][미리보기]

[jQuery] 003. 스크롤과 버튼을 통한 백그라운드 제어하기 [다운받기][미리보기]

[jQuery] 004. 다양한 옵션에 따라 백그라운드 이미지 조절하기 [다운받기][미리보기]

[jQuery] 005. 페이지의 숨겨진 영역을 보여주는 페이지 슬라이드 [다운받기][미리보기]

[jQuery] 006. 백그라운드 배경을 기본으로 하는 이미지 갤러리 [다운받기][미리보기]

[jQuery] 007. 다양한 효과를 줄 수 있는 백그라운드 갤러리 [다운받기][미리보기]

[jQuery] 008. 화면 크기에 따라 변하는 풀 스크린 이미지 소스 [다운받기][미리보기]

[jQuery] 009. 마우스에 움직임에 따라 움직이는 배경 이미지들 [다운받기][미리보기]

 

 

-GALLERY-

 

[Gallery] 001. 여러가지 이미지를 볼 수 있는 라이크 박스 갤러리 [다운받기][미리보기]

[Gallery] 002. 썸네일 이미지와 디테일 이미지가 나오는 갤러리 [다운받기][미리보기]

[Gallery] 003. 썸네일 이미지와 풀스크린 이미지의 제이쿼리 갤러리 [다운받기][미리보기]

[Gallery] 004. 스폰서의 정보를 보여주는 플립효과의 갤러리 스타일 [다운받기][미리보기]

[Gallery] 005. 사진을 하나씩 보여주는 포토 갤러리 플러그인 제이쿼리 [다운받기][미리보기]

[Gallery] 006. 이미지 갤러리 벽을 형상화한 갤러리 스타일 소스 [다운받기][미리보기]

[Gallery] 007. 박스 갤러리 형태의 이미지 갤러리 제이쿼리 소스 [다운받기][미리보기]

[Gallery] 008. 독특한 장면 효과를 제공하는 COIN SLIDER 갤러리 [다운받기][미리보기]

[Gallery] 009. 반응형, 모바일, CSS3를 지원하는 Slides.js 갤러리 [다운받기][미리보기]

[Gallery] 010. 제이쿼리를 이용한 라이트 박스 갤러리 이미지 [다운받기][미리보기]

 


출처 : http://webstoryboy.tistory.com/1266#.Urka39qIrwc

Posted by 1010
반응형

 

 

jquery.browser.js

 

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> New Document </title>
  <meta name="Generator" content="EditPlus">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
<script src="http://code.jquery.com/jquery-1.9.0.js"></script>
<script type="text/javascript" src="jquery.browser.js"></script>
<script type="text/javascript">
<!--
 function test(){
  $.browser.msie ? alert('Internet Explorer') : alert('Not Internet Explorer');
 }
//-->
</script>
 </head>

 <body>
  <input type="button" value="test" onclick="test();">
 </body>
</html>

Posted by 1010
반응형

request #16 from bitdeli-chef/master

Add a Bitdeli Badge to README
latest commit 083f5495e6
authored

Octocat-spinner-32 dist Added uglify task to grunt
Octocat-spinner-32 test Casperserver can now be stopped and finishes with no errors
Octocat-spinner-32 .gitignore Added node related stuff to gitignore
Octocat-spinner-32 Gruntfile.js Added test task for grunt
Octocat-spinner-32 MIT-LICENSE.txt Added license file from jQuery MIT LICENSE with acknowledgement for m…
Octocat-spinner-32 README.md Add a Bitdeli badge to README
Octocat-spinner-32 bower.json Bumped version to 0.0.5
Octocat-spinner-32 browser.jquery.json Bumped version to 0.0.5
Octocat-spinner-32 package.json Added test task for grunt

README.md

A jQuery plugin for browser detection. jQuery removed support for browser detection on 1.9.1 so it was abstracted into a jQuery plugin

Installation

Include script after the jQuery library:

<script src="/path/to/jquery.browser.js"></script>

Usage

Returns true if the current useragent is some version of Microsoft's Internet Explorer. Supports all IE versions including IE11

$.browser.msie;

Returns true if the current useragent is some version of a Webkit browser (Safari, Chrome and Opera 15+).

$.browser.webkit;

Returns true if the current useragent is some version of Firefox.

$.browser.mozilla;

Reading the browser verion

$.browser.version

Things not included in the original jQuery $.browser implementation

  • Detect Windows, Mac, Linux, iPad, iPhone, Android and Windows Phone useragents
    $.browser.ipad
    $.browser.iphone
    $.browser["windows phone"]
    $.browser.android
    $.browser.win
    $.browser.mac
    $.browser.linux
  • Detect the browser's major version
    // User Agent for Chrome
    // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/32.0.1664.3 Safari/537.36

    $.browser.versionNumber // Returns 32 as a number
  • Support for new useragent on IE11
  • Support for webkit based Opera browsers
  • Added testing using PhantomJS and different browser user agents

Testing

Testing for this plugin is done with Casperjs v1.1 to take advantage of multiple phantomjs browsers with different user agents.

For instructions on how to install Casperjs v1.1 go to http://docs.casperjs.org/en/latest/installation.html

Note: Testing requires Casperjs v1.1

Install the grunt-cli dependency by running npm install -g grunt-cli Run npm install to install all dependencies including grunt and all tasks

Once Casperjs and the grunt-cli npm package is installed you can execute all the tests by using:

grunt test

Development

Attributions

 

$.browser.msie ? alert('Internet Explorer') : alert('Not Internet Explorer');

 

 

-----------------------------------------------

 

 

1. 브라우저 체크

 

$.browser.msie : 익스플로러인지를 확인. IE라면 true를 반환 아니라면 false를 반환합니다.
$.browser.mozilla : 파이어폭스인지 확인. 반환값은 위와 같습니다.
$.browser.safari : 사파리인지를 확인. 크롬의 경우도 해당합니다. 반환값은 위와 같습니다.
$.browser.opera : 오페라인지를 확인. 반환값은 위와 같습니다.


2. 브라우저 버전 체크

 

$.browser.version : 각각의 브라우저의 버전을 알아옵니다. 브라우저의 종류는 알아오지 않습니다.

 

3. 기본적인 사용 예제

 

$(function(){
  if($.browser.msie==true) {
    alert('인터넷 익스플로러를 사용 중 입니다. 버전은 '+$.browser.version+'입니다.');
  } else {
    alert('인터넷 익스플로러를 사용하고 있지 않습니다.');
  }
});

 

Posted by 1010
반응형
Posted by 1010
반응형
Posted by 1010
반응형
Posted by 1010
반응형
http://jquerylist.com/
http://jqueryui.com/


Posted by 1010
반응형

jQuery.utils is a library I maintain and use in my every day work and spare time. It's a collection of jQuery plugins and widget that I often use.

Some are made by me, some by other authors, but they are all under MIT or dual Open Source license.

General Notice I'm looking for some help to maintain this project and make it better (especially an IE expert). Any kind of help would be greatly appreciated (bug report, documentation, unit tests, bug fixing, etc..). You can contact me at haineault (at) gmail.com

Notice:

I'm interesting about how developers use this library and what plugins they use the most. If you do use my library and have some feedback to give me it's the right time:

Take a minute to fill this survey

Goals

  • Provide extra jQuery features for everyday web development
  • Provide downloads on a highly available server
  • Easily make custom builds
  • Provide unit tests for plugins who hasn't
  • Centralize the documentation of the plugins I often use on a highly available server
  • Maybe find some contributors
  • Have fun with jQuery

Builds

Build Plugins
jquery.utils.js utils, strings, anchorHandler, cookie, countdown, cycle, delayedObserver, flash, i18n, masked, mousewheel, slimbox, timeago
jquery.utils.lite.js utils, strings, cookie, cycle, flash, masked, mousewheel, slimbox

Plugins

Plugin Description Author
jquery.utils.js Various utility that I don't know where to put Maxime Haineault
jquery.strings.js Various string formatting method (by now it only has a format method inspired by the Advanced String Formatting module in Python3K, sprintf is expceted next) Maxime Haineault
jquery.anchorhandler.js Handle URLs anchor gracefully with regular expressions (inspired by Django URLs dispatcher). Maxime Haineault
jquery.cookie.js Cookie manipulation Klaus Hart
jquery.countdown.js A simple countdown script Maxime Haineault
jquery.cycle.js A cycle script, useful for banner rotation M. Alsup
jquery.delayedobserver.js A delayed observer. Maxime Haineault
jquery.flash.js A plugin for embedding Flash movies Luke Lutman
jquery.i18n.js Provide a simple API for plugin translation Maxime Haineault
ui.masked.js Input restriction libary Josh Bush
jquery.mousewheel.js Adds mouse wheel support for your application Brandon Aaron
jquery.slimbox.js Slimbox 2 is a 4 KB visual clone of the popular Lightbox 2 script by Lokesh Dhakar, written using the jQuery javascript library. Christophe Beyls
jquery.timeago.js A plugin that makes it easy to support automatically updating fuzzy timestamps (e.g. "4 minutes ago" or "about 1 day ago") Ryan McGeary

Extra plugins

These plugins are not built by default. To include them you only have to uncomment a line in build.yml and type ./built.py -m. See the build system documentation for more details.

Plugin Description Author
jquery.flickrshow.js This plugins takes a flickr photostream link and turns it into a nice little slideshow.
jquery.arrayUtils.js Provide additional functional method to work with array. This library is largely inspired by the enumerables concept in the Prototype Javascript Library
jquery.ddbelated.js A plugin designed to fix that problem by applying appropriate filters to user specified elements, while keeping all element tags intact.

UI (widgets)

These plugin are available with the jquery.utils.ui.js build.

Widget Description Author
ui.builder.js Simple template generator for UI common widgets Maxime Haineault
ui.toaster.js IM style popup notification system Maxime Haineault
ui.timepickr.js Time picker control Maxime Haineault
dev.timepickrDev UI timepickr development notes Maxime Haineault

Note: Depends on the jQuery UI library.

Experimental

These are toy projects, some might be eventually included in the build, some are not even actually working yet. In other words, it's my sandbox

Name Description Author
jquery.extendCSS.js Maxime Haineault
jquery.jpath.js Maxime Haineault
jquery.valid.js Validation libary Maxime Haineault
jquery.keynav.js Maxime Haineault

Links

Discussions about jQuery utils
Project statistics

Stats

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
                var htmlStr = $("P").html();
                $("DIV").text(htmlStr);



        });
    </script>
  </head>
  <body>
    <body>
      <p class=blue>A</p>

      <DIV></DIV>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <style type="text/css">
        a.test { font-weight: bold; color:red;}
    </style>

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

    $("input.buttonA").click(function(){ $("div.contentToChange").find("em").css({color:"#993300", fontWeight:"bold"}); });


 });

    </script>
  </head>
  <body>
    <input type="button" value="Change" class="buttonA" />



    <div style="background:#eee;" class="contentToChange">
        <h2>Header 2</h2>
       
        <p class="firstparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
       
        <p class="fifthparagraph">Lorem ipsum <em>dolor</em> sit amet, consectetuer <em>adipiscing</em> elit, sed diam nonummy nibh euismod <em>tincidunt</em> ut laoreet dolore magna aliquam erat <strong>volutpat</strong>. Ut wisi enim ad minim <em>veniam</em>, quis nostrud exerci <strong>tation</strong> ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat.</p>
       
    </div>

  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
          $("div").css("background", "blue")
            .filter(function (index) {
                  return  $(this).attr("id") == "fourth" ;
            })
            .css("border", "1px solid red");

        });
    </script>
     <style>
     div { border:2px white solid;}
  </style>

  </head>
  <body>
    <body>
      <div id="first">asdf</div>
      <div id="second">asdf</div>
      <div id="third">asdf</div>
      <div id="fourth">asdf</div>
      <div id="fifth">asdf</div>
      <div id="sixth">asdf</div>


  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("input").keypress(function (e) {
               if (e.which > 65 ) {
                 alert(e.which);
               }
            });
        });
    </script>
  </head>
  <body>
    <body>
     <input type="text" />


    </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>

    <script type="text/javascript">
 $(document).ready(function(){
   $("a").click(function(event){
     alert("Thanks for visiting!");
   });
 });


    </script>
  </head>
  <body>
    <a href="http://java2s.com/">java2s.com</a>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
  $(document).ready(function(){
    $(document).ready(function(){
      $("*").css("background","red");
    });
  });
    </script>

  </head>
  <body>
      <div class="notMe">div </div>
      <div class="myClass">div</div>
      <span class="myClass myOtherClass">span</span>

  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
       var input = $(":submit").css({background:"yellow", border:"3px red solid"});
   
       $('#result').text('jQuery matched ' + input.length + ' elements.');
       
    });
    </script>
  </head>
  <body>
     <form><input type="submit" /></form>
     <div id="result"></div>


  </body>
</html>
Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("div").text("data").css("color", "red");
       
       
    });
    </script>
  </head>
  <body>
     <form>
      <input type="text" />
    </form>
     <div></div>
  </body>
</html>

Posted by 1010
반응형
<html>
  <head>
    <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("div").html("<b>bold</b> not bold");
            $("div b").append(document.createTextNode("!!!")).css("color", "red");
        });
    </script>
  </head>
  <body>
    <body>
      <DIV></DIV>
  </body>
</html>
Posted by 1010