Grid table (add, remove, import, edit)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Romulo NF
    New Member
    • Nov 2006
    • 54

    Grid table (add, remove, import, edit)

    Greetings again to everyone,

    Im back to show this grid componenet i´ve developed. With this grid you can show the data like a normal table, remove the rows that you need, add rows, import data, call determined functions, and edit the data already present

    What will you need to use the grid? A table with standard markup and an ID to call the script that will turn the table into a grid

    Parameters:
    tabelaID => id of the table that will turn into a grid
    maxLinha => number of rows that the grid will display, if number of rows exceed this number the grid will create a scrollbar
    edicao => array that control the edition of the grid. this parameter accepts 2 arrays, metodo and unico
    edicao.metodo => array that determine how each column will be edited. use null for no edition, "default" to free edition, and an array to a select with that options
    edicao.unico ==> array that determine if one data is unique in the grid, example: the last column have a edition method of "yes" and "no", but you wanna only 1 yes in all the grid. possible values are null or index of the respective array that will be unique
    valor => accept an array called tag that determine how the value of the grid will be filled. possible values are "default" to put all the data in the cell, specific tag name like "span" to get data only from spans in that column, and null to skip that column
    largura => array that detemine the width of each column in percentage (max = 100)
    alinhamento => array that determine the alingment of each column (left, right, center, justify)
    fn => determine the function that will be called when the add button is pressed

    The parameters may look kinda hard to pass, but the example will help a bit here

    file: grid.css
    [code=css]
    .grid {border-collapse:collap se; table-layout:fixed; width:560px; font:normal 11px arial;}
    .grid th {background:url (img/headerBg.jpg); border-right:1px solid #ddd; border-bottom:1px solid #ddd; color:#fff}
    .grid td, .grid table td {text-indent:5px; white-space:nowrap; overflow:hidden ; padding:0px 5px 0px 0;}

    .grid table td {height:20px}

    .grid .holder {overflow:auto; width:559px;}
    .grid table {table-layout:fixed; border-collapse:collap se; width:540px; font:normal 11px arial}
    .grid .scrollBar {border:0; background:tran sparent; width:13px;}

    .grid .par td {background:#ff f}
    .grid .impar td {background:#ee e}
    .grid .hover td {background:#D9 E8FB}

    .grid span {display:none}

    * html .grid .scrollBar {width:16px}

    .divEdicao {background:#ee e; border:1px solid #aaa; position:absolu te; width:auto; height:18px;}
    .divEdicao img {margin:2px; cursor:pointer}

    .overlay {position:absol ute; background:#eee ; filter:alpha(op acity=0); -moz-opacity:0; opacity:0}

    .botaoAdicionar {position:relat ive; cursor:pointer; margin-bottom:10px}
    .botaoAceitar, .botaoCancelar {position:absol ute; cursor:pointer; }

    .edicaoTable {position:absol ute; font:normal 11px arial; background:#fff ; border-collapse:collap se; table-layout:fixed}
    .edicaoTable td {white-space:nowrap; overflow:hidden ; padding:0;}
    .edicaoTable td input {margin:0; padding:0; width:100%; height:20px; overflow:hidden ; font:normal 11px arial; padding:2px}
    .edicaoTable td select {margin:0; padding:0; width:100%; height:18px; overflow:hidden ; font:normal 11px arial;}
    [/code]

    file: sample.html
    [HTML]
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <head>
    <title>Grid</title>
    </head>

    <link rel="stylesheet " href="grid.css" >

    <script src="grid.js"></script>

    <script>
    window.onload = function() {
    gridUm = new criarGrid('tabe laUm',10, {metodo:[null,null,null,['Yes','No']],unico:[null,null,null, 1]}, {tag:['default',null, null,'default']},[40,25,15,20],['left','right', 'center','right '], 'abrirPopup("fi ltro.html")');
    }

    function abrirPopup(url) {
    janela = window.open(url ,'Janela','widt h=670,height=40 0,left=200,top= 200,toolbar=no' )
    }

    </script>

    <body>

    <table id="tabelaUm">
    <thead>
    <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
    <th>Header 4</th>
    </tr>
    </thead>
    <tbody>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Yes</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    <tr>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>Dummy text</td>
    <td>No</td>
    </tr>
    </tbody>
    </table>

    <br><br><br>

    <button onclick="alert( gridUm.valores) ">Valor</button>

    </body>
    </html>
    [/HTML]

    [CODE=javascript]
    ////////////////////////////////////////////
    // Author: Romulo do Nascimento Ferreira //
    // Email: romulo.nf@gmail .com //
    ////////////////////////////////////////////

    /* parametros

    tabelaID: id da tabela que vai ter funcionalidade de grid
    maxLinha: número máximo de linhas a ser mostrado (para criação de barra de rolagem)
    edicao: array que determina o método de edição de cada coluna
    edicao.metodo:
    default = edicao livre
    null = sem edicao
    array de string = opcoes da combo box
    edicao.unico:
    index = indica exclusividade de uma opcao de index x
    valor: array que determina qual elemento vai compor o array valores[] do grid
    default = conteudo da coluna
    null = nenhum valor atribuido
    tag = atribui ao array o conteudo da tag escolhida dentro da coluna
    ex: span
    largura: array com a porcentagem de largura de cada coluna
    alinhamento: array que determina o alinhamento de cada coluna (left,right,cen ter,justify)
    fn: função chamada pelo botao de adicionar na parte inferior do grid

    */

    function criarGrid(tabel aID,maxLinha,ed icao,valor,larg ura,alinhamento ,fn) {

    this.tempInputs = new Array()
    this.tabela = document.getEle mentById(tabela ID)
    this.tabela.cla ssName = "grid"
    this.cabecalho = this.tabela.tHe ad
    this.numCol = this.cabecalho. rows[0].cells.length
    this.corpo = this.tabela.tBo dies[0]
    this.tamMax = this.corpo.rows .length > 0 ? (maxLinha * this.corpo.rows[0].offsetHeight) : maxLinha * 20
    this.holder = this.tabela.par entNode
    this.alturaCabe calho = this.cabecalho. rows[0].offsetHeight
    this.opcoes = false
    this.protecao = false
    this.larguraCol = typeof largura !="undefined" ? largura : null
    this.alignCol = typeof alinhamento !="undefined" ? alinhamento : null

    if (edicao && edicao !=false) {
    this.metodoEdic ao = typeof edicao.metodo !="undefined" ? edicao.metodo : null
    this.unicoEdica o = typeof edicao.unico !="undefined" ? edicao.unico : null
    }
    if (edicao == false) {
    this.bloquearEd icao = true
    }

    if (valor) this.tagValor = typeof valor.tag !="undefined" ? valor.tag : null

    this.organizarE strutura(fn)
    this.executarTa refas()
    }

    criarGrid.proto type.verificarT amanho = function() {
    this.alturaLinh as = 0

    for (x=0; x<this.novoCorp o.rows.length; x++) { this.alturaLinh as += this.novoCorpo. rows[x].offsetHeight }

    this.divHolder. style.height = this.alturaLinh as < this.tamMax ? this.alturaLinh as + "px" : this.tamMax + "px"
    }

    criarGrid.proto type.associarVa lores = function() {
    if (!this.valores) this.valores = new Array()

    if (this.valores.l ength > this.novoCorpo. rows.length) this.valores = new Array()

    for (x=0; x<this.novoCorp o.rows.length; x++) {
    this.valores[x] = new Array()
    for (y=0; y<this.numCol; y++) {
    if (this.tagValor[y] != "default") {
    tag = this.novoCorpo. rows[x].cells[y].getElementsByT agName(this.tag Valor[y])
    tag.length > 0 ? conteudo = tag[0].innerHTML : conteudo = null
    }
    else { conteudo = this.novoCorpo. rows[x].cells[y].innerHTML }

    if (this.tagValor[y] != "undefined" || this.tagValor[y] != null) { this.valores[x][y] = conteudo }
    }
    }
    }

    criarGrid.proto type.funcoesTr = function() {
    for (x=0; x<this.novoCorp o.rows.length; x++) {
    this.novoCorpo. rows[x].grid = this

    // zebraRows
    x%2 == 0 ? this.novoCorpo. rows[x].className = "par" : this.novoCorpo. rows[x].className = "impar"

    // mouseover event
    this.novoCorpo. rows[x].onmouseover = function() {
    if (this.grid.time r) clearTimeout(th is.grid.timer)
    this.grid.mostr arOpcoes(this)
    this.className += " hover"
    }

    // mouseout event
    this.novoCorpo. rows[x].onmouseout = function() {
    var _this = this.grid
    this.grid.timer = setTimeout(func tion(){_this.re moverOpcoes()}, 500)
    this.className = this.className. substring(0,thi s.className.ind exOf(" hover"))
    }

    }
    }[/code]
    [code=javascript]criarGrid.proto type.criarOverl ay = function() {
    if (this.protecao) this.removerOve rlay()
    this.protecao = true
    this.overlay = document.create Element("div")
    this.overlay.cl assName = "overlay"
    this.overlay.st yle.height = this.divHolder. offsetHeight + 10 + "px"
    this.overlay.st yle.width = this.novaTabela .offsetWidth + 10 + "px"
    this.overlay.st yle.top = this.divHolder. offsetTop + this.tabela.off setTop + this.alturaCabe calho + "px"
    this.overlay.st yle.left = this.divHolder. offsetLeft + this.tabela.off setLeft + "px"
    this.holder.app endChild(this.o verlay)

    this.divHolder. style.overflow = "hidden"
    this.botaoAdici onar.style.disp lay = "none"
    }

    criarGrid.proto type.removeOver lay = function() {
    this.overlay.pa rentNode.remove Child(this.over lay)
    this.protecao = false

    this.divHolder. style.overflow = "auto"
    this.botaoAdici onar.style.disp lay = ""
    }

    criarGrid.proto type.editarLinh a = function(tr) {
    this.removerOpc oes()
    this.criarOverl ay()

    this.edicaoTabl e = document.create Element("table" )
    this.edicaoTabl e.className = "edicaoTabl e"
    this.edicaoTbod y = document.create Element("tbody" )
    this.cloneTr = tr.cloneNode(tr ue)
    this.edicaoTabl e.appendChild(t his.edicaoTbody )
    this.edicaoTbod y.appendChild(t his.cloneTr)

    this.edicaoTabl e.style.width = tr.offsetWidth + "px"
    this.edicaoTabl e.style.top = tr.offsetTop - this.divHolder. scrollTop + this.tabela.off setTop + this.alturaCabe calho + "px"
    this.edicaoTabl e.style.left = this.tabela.off setLeft - this.divEdicaoT r.offsetWidth + "px"

    // metodos de edicao
    for (x=0; x<this.cloneTr. cells.length; x++) {
    this.cloneTr.ce lls[x].style.width = tr.cells[x].offsetWidth + "px"

    if (this.metodoEdi cao[x] == "default") {
    this.tempInputs[x] = document.create Element("input" )
    this.tempInputs[x].value = tr.cells[x].innerHTML
    this.cloneTr.ce lls[x].replaceChild(t his.tempInputs[x],this.cloneTr.c ells[x].childNodes[0])
    }

    else if (this.metodoEdi cao[x] && this.metodoEdic ao[x].length > 1) {
    this.tempInputs[x] = document.create Element("select ")
    for (y=0; y<this.metodoEd icao[x].length; y++) {
    opcaoTemp = document.create Element("option ")
    opcaoTemp.value = this.metodoEdic ao[x][y]
    opcaoTemp.inner HTML = this.metodoEdic ao[x][y]
    this.tempInputs[x].appendChild(op caoTemp)
    }
    this.cloneTr.ce lls[x].replaceChild(t his.tempInputs[x],this.cloneTr.c ells[x].childNodes[0])

    for (y=0; y<this.tempInpu ts[x].options.length ; y++) {
    if (this.tempInput s[x].options[y].innerHTML.toLo werCase() == tr.cells[x].innerHTML.toLo werCase()) {
    this.tempInputs[x].options[y].selected = "selected"
    }
    }
    }

    else {
    this.tempInputs[x] = document.create Element("input" )
    this.tempInputs[x].value = tr.cells[x].innerHTML
    this.tempInputs[x].disabled = "disabled"
    this.cloneTr.ce lls[x].replaceChild(t his.tempInputs[x],this.cloneTr.c ells[x].childNodes[0])
    }

    }

    this.holder.app endChild(this.e dicaoTable)

    this.botaoAceit ar = new Image()
    this.botaoAceit ar.src = "img/aceitar.gif"
    this.botaoAceit ar.className = "botaoAceit ar"
    this.botaoAceit ar.grid = this
    this.botaoAceit ar.onclick = function() { this.grid.aceit arEdicao(tr) }
    this.botaoAceit ar.style.top = parseInt(this.e dicaoTable.styl e.top) + this.edicaoTabl e.offsetHeight/6 + "px"
    this.botaoAceit ar.style.left = parseInt(this.e dicaoTable.styl e.left) + this.edicaoTabl e.offsetWidth + 3 + "px"
    this.holder.app endChild(this.b otaoAceitar)

    this.botaoCance lar = new Image()
    this.botaoCance lar.src = "img/cancelar.gif"
    this.botaoCance lar.className = "botaoCance lar"
    this.botaoCance lar.grid = this
    this.botaoCance lar.onclick = function() { this.grid.cance larEdicao() }
    this.botaoCance lar.style.top = parseInt(this.b otaoAceitar.sty le.top) + "px"
    this.botaoCance lar.style.left = parseInt(this.e dicaoTable.styl e.left) + this.edicaoTabl e.offsetWidth + 20 + "px"
    this.holder.app endChild(this.b otaoCancelar)
    }[/code]
    [code=javascript]
    criarGrid.proto type.aceitarEdi cao = function(tr) {

    for (x=0; x<this.tempInpu ts.length; x++) {
    if (this.unicoEdic ao[x] && this.tempInputs[x].value != this.metodoEdic ao[x][this.unicoEdica o[x]]) {
    for (y=0; y<this.novoCorp o.rows.length; y++) {
    this.novoCorpo. rows[y].cells[x].innerHTML = this.metodoEdic ao[x][this.unicoEdica o[x]]
    }
    }
    tr.cells[x].innerHTML = this.tempInputs[x].value
    }

    this.cancelarEd icao()
    this.executarTa refas()
    }

    criarGrid.proto type.cancelarEd icao = function() {
    this.removeOver lay()
    this.edicaoTabl e.parentNode.re moveChild(this. edicaoTable)
    this.botaoCance lar.parentNode. removeChild(thi s.botaoCancelar )
    this.botaoAceit ar.parentNode.r emoveChild(this .botaoAceitar)
    }

    criarGrid.proto type.excluirLin ha = function(tr) {
    this.removerOpc oes()
    tr.parentNode.r emoveChild(tr)
    this.executarTa refas()
    }

    criarGrid.proto type.removerOpc oes = function() {
    if (this.divEdicao Tr) this.divEdicaoT r.parentNode.re moveChild(this. divEdicaoTr)
    this.opcoes = false
    }

    criarGrid.proto type.mostrarOpc oes = function(tr) {
    if (this.opcoes) this.removerOpc oes()

    this.opcoes = true

    this.divEdicaoT r = document.create Element("div")
    this.divEdicaoT r.className = "divEdicao"
    this.divEdicaoT r.grid = this

    this.divEdicaoT r.onmouseover = function() { if (this.grid.time r) clearTimeout(th is.grid.timer) }
    this.divEdicaoT r.onmouseout = function() {
    var _this = this.grid
    this.grid.timer = setTimeout(func tion(){_this.re moverOpcoes()}, 500)
    }

    this.holder.app endChild(this.d ivEdicaoTr)

    if (!this.bloquear Edicao) {
    this.botaoEdita r = new Image()
    this.botaoEdita r.grid = this
    this.botaoEdita r.alt = "Clique aqui para editar a linha " + (tr.rowIndex + 1)
    this.botaoEdita r.title = "Clique aqui para editar a linha " + (tr.rowIndex + 1)
    this.botaoEdita r.onclick = function() { this.grid.edita rLinha(tr) }
    this.botaoEdita r.src = "img/lapis.gif"
    this.divEdicaoT r.appendChild(t his.botaoEditar )
    }

    this.botaoExclu ir = new Image()
    this.botaoExclu ir.grid = this
    this.botaoExclu ir.alt = "Clique aqui para excluir a linha " + (tr.rowIndex + 1)
    this.botaoExclu ir.title = "Clique aqui para excluir a linha " + (tr.rowIndex + 1)
    this.botaoExclu ir.onclick = function() { this.grid.exclu irLinha(tr) }
    this.botaoExclu ir.src = "img/lixeira.gif"
    this.divEdicaoT r.appendChild(t his.botaoExclui r)

    this.divEdicaoT r.style.top = tr.offsetTop - this.divHolder. scrollTop + this.tabela.off setTop + this.alturaCabe calho + "px"
    this.divEdicaoT r.style.left = tr.offsetWidth + this.tabela.off setLeft - this.divEdicaoT r.offsetWidth + "px"
    }

    criarGrid.proto type.executarTa refas = function() {
    this.corrigirLa rgura()
    this.funcoesTr( )
    this.associarVa lores()
    this.verificarT amanho()
    }

    criarGrid.proto type.corrigirLa rgura = function() {
    for (x=0; x<this.numCol; x++) {
    if (this.larguraCo l) { this.cabecalho. rows[0].cells[x].style.width = this.larguraCol[x] + "%" }
    for (y=0; y<this.novoCorp o.rows.length; y++) {
    if (this.larguraCo l) { this.novoCorpo. rows[y].cells[x].style.width = this.larguraCol[x] + "%" }
    if (this.alignCol) { this.novoCorpo. rows[y].cells[x].style.textAlig n = this.alignCol[x] }
    }
    }
    }

    criarGrid.proto type.organizarE strutura = function(fn) {
    this.scrollBar = document.create Element("th")
    this.trHolder = document.create Element("tr")
    this.tdHolder = document.create Element("td")
    this.divHolder = document.create Element("div")
    this.novaTabela = document.create Element("table" )
    this.novoCorpo = document.create Element("tbody" )

    while (this.corpo.row s.length > 0) { this.novoCorpo. appendChild(thi s.corpo.rows[0]) }

    this.scrollBar. innerHTML = "&nbsp;"
    this.scrollBar. className = "scrollBar"
    this.cabecalho. rows[0].appendChild(th is.scrollBar)

    this.corpo.appe ndChild(this.tr Holder)

    this.tdHolder.c olSpan = (this.numCol+1)
    this.trHolder.a ppendChild(this .tdHolder)

    this.divHolder. className = "holder"
    this.divHolder. style.height = this.tamMax + "px"
    this.tdHolder.a ppendChild(this .divHolder)

    this.divHolder. appendChild(thi s.novaTabela)

    this.novaTabela .appendChild(th is.novoCorpo)

    this.botaoAdici onar = new Image()
    this.botaoAdici onar.onmouseove r = function() { this.src = "img/add2-hover.gif" }
    this.botaoAdici onar.onmouseout = function() { this.src = "img/add2.gif" }
    this.botaoAdici onar.className = "botaoAdicionar "
    this.botaoAdici onar.src = "img/add2.gif"
    this.botaoAdici onar.onclick = function() { eval(fn) }
    this.holder.ins ertBefore(this. botaoAdicionar, this.tabela.nex tSibling)
    }

    criarGrid.proto type.importarDa dos = function(tr) {

    inserirTr = true

    for (x=0; x<this.novoCorp o.rows.length; x++) {
    conteudoAtual = this.novoCorpo. rows[x].textContent ? this.novoCorpo. rows[x].textContent : this.novoCorpo. rows[x].innerText
    conteudoNovo = tr.textContent ? tr.textContent : tr.innerText
    if (conteudoAtual == conteudoNovo) { inserirTr = false }
    }

    if (inserirTr) {

    this.novoCorpo. insertRow(this. novoCorpo.rows. length)

    for (x=0; x<this.numCol; x++) {
    this.novoCorpo. rows[this.novoCorpo. rows.length-1].insertCell(x)
    this.novoCorpo. rows[this.novoCorpo. rows.length-1].cells[x].innerHTML = tr.getElementsB yTagName("td")[x].innerHTML
    }

    this.divHolder. scrollTop = this.divHolder. scrollHeight

    this.executarTa refas()
    }

    else { janela.alert("I nformação existente") }
    }
    [/CODE]
    Thats basically it.
    Feel free to use/modify the grid to serve your own purposes.
    I just ask for you to keep the copyright there.

    The url bellow is a zip containing a sample of the grid getting data from the filter, another component i´ve already posted here. The file also contains some images that i use on the grid, but you can easily change that to make your custom grid.

    Grid & filter
    Attached Files
    Last edited by Romulo NF; Dec 3 '07, 08:14 PM. Reason: fixing the topic
  • Romulo NF
    New Member
    • Nov 2006
    • 54

    #2
    If any admin gets here can you try to fix this topic? The above topic contains the js but using the [*code*] tag i couldnt manage to make the post visible. When everything is fixed delete this post also. I´d be grateful!

    Comment

    • acoder
      Recognized Expert MVP
      • Nov 2006
      • 16032

      #3
      Hopefully fixed.

      Is it possible to make an English version? It'd make the code a lot easier to understand!

      Comment

      • filmword
        New Member
        • Feb 2008
        • 1

        #4
        Originally posted by acoder
        Hopefully fixed.

        Is it possible to make an English version? It'd make the code a lot easier to understand!
        Hi

        maybe users can try following for English help:

        Translation favelet/bookmarklet from:



        Babelfish Portuguese to English

        Code:
        javascript:void(document.location='http://babelfish.altavista.com/babelfish/urltrurl?url=' +escape(document.location)+'&lp=pt_en&tt=url')
        Last edited by acoder; Feb 6 '08, 06:44 PM.

        Comment

        • Romulo NF
          New Member
          • Nov 2006
          • 54

          #5
          I´ve made lots of changes, and i hope to post an english version of it when i have some free time!!

          Comment

          • acoder
            Recognized Expert MVP
            • Nov 2006
            • 16032

            #6
            Originally posted by filmword
            Hi

            maybe users can try following for English help:

            Translation favelet/bookmarklet from:



            Babelfish Portuguese to English

            Code:
            javascript:void(document.location='http://babelfish.altavista.com/babelfish/urltrurl?url=' +escape(document.location)+'&lp=pt_en&tt=url')
            Thanks for the tip. Is it Portuguese? :)

            Comment

            • acoder
              Recognized Expert MVP
              • Nov 2006
              • 16032

              #7
              Originally posted by Romulo NF
              I´ve made lots of changes, and i hope to post an english version of it when i have some free time!!
              Look forward to the changes. Thanks for the updates.

              Comment

              Working...