Ir para conteúdo
Fórum Script Brasil
  • 0

Checkbox Dinâmicos E Input Texts


lmf.php

Pergunta

Olá gente...

Estou com um probleminha aqui... não sei ao certo o que está acontecendo, mas aparentemente, meu script tá me zuando.

Eu criei um script que manipula checkboxes, usando imagens ao invés daquela caixinha feia, tosca e ridícula.

Ei-lo:

/*******************************************************************************
* Dynamic Checkboxes  v 1.1                                                   *
*******************************************************************************
* Author: Guilherme Augusto Blanco                                            *
* MSN: guilhermeblanco@hotmail.com                                            *
* ICQ: 33288081                                                               *
*******************************************************************************
* GPL - The GNU General Public License    http://www.gnu.org/licenses/gpl.txt *
* Permits anyone the right to use and modify the software without limitations *
* as long as proper  credits are given  and the original  and modified source *
* code are included. Requires  that the final product, software derivate from *
* the original  source or any  software  utilizing a GPL  component, such  as *
* this, is also licensed under the GPL license.                               *
*******************************************************************************
* 11-30-2003: Added text click selection support                              *
* 11-16-2003: Version 1.0 released                                            *
*******************************************************************************
* Last modifyed: 11-30-2003                                                   *
*******************************************************************************/

/* Basic Configuration */
dCheckBox.unselected = new Image(16, 16);
dCheckBox.unselected.src = "system/img/unchecked.gif";
dCheckBox.selected = new Image(16, 16);
dCheckBox.selected.src = "system/img/checked.gif";

/* Auxiliar properties */
dCheckBox.all = {};
dCheckBox.objCounter = 0;

/* Constructor */
function dCheckBox( sMethod, sHint ) {
        this.id = "dotcom-radio-object-"+ dCheckBox.objCounter++;
        this.method = sMethod;
        this.hint = (sHint)? sHint: "";

        this.write();

        // Adding event handlers to the button
        var oThis = this;
        document.getElementById( this.id ).onclick = function ( ) { oThis.click( ); }

        dCheckBox.all[ this.id ] = this;
}

/* Constructor functions */
dCheckBox.prototype.write = function ( ) {
        str = "<input id=\"frm_" + this.id + "\" type=\"checkbox\" value=\"y\" name=\"" + this.method + "\" style=\"visibility: hidden; display: none;\">";
        str += "<img id=\"" + this.id + "\" src=\"" + dCheckBox.unselected.src + "\" style=\"width: 16px; height: 16px; margin: 2px; vertical-align: middle;\" alt=\""+ this.hint +"\">";
        document.write(str);
}

/* Instance event handlers */
dCheckBox.prototype.onclick = function ( ) { }

dCheckBox.prototype.click = function ( ) {
        if ( document.getElementById( "frm_" + this.id ).checked == true ) {
                 document.getElementById( this.id ).src = dCheckBox.unselected.src;
                 document.getElementById( "frm_" + this.id ).checked = false;
        } else {
                 document.getElementById( this.id ).src = dCheckBox.selected.src;
                 document.getElementById( "frm_" + this.id ).checked = true;
        }
        
        if (typeof this.onclick == "function")
            this.onclick();
}

dCheckBox.prototype.select = function ( ) {
        document.getElementById( this.id ).src = dCheckBox.selected.src;
        document.getElementById( "frm_" + this.id ).checked = true;
}

dCheckBox.prototype.deSelect = function ( ) {
        document.getElementById( this.id ).src = dCheckBox.unselected.src;
        document.getElementById( "frm_" + this.id ).checked = false;
}

dCheckBox.prototype.getSelected = function ( ) {
        return document.getElementById( "frm_" + this.id ).checked;
}

dCheckBox.prototype.getElement = function ( ) {
       return document.getElementById( "frm_" + this.id );
}

dCheckBox.prototype.toString = function ( ) {
       return "[object dCheckBox]";
}
Até aí, ele está funcionando normalmente... estou utilizando-o para criar um gerenciador de arquivos. Nele, está cotido uma janela dinâmica de CHMOD, na qual integra-se 9 destes checkboxes e 1 input do tipo text. Basicamente, a cada alteração do input, eu tenho que analisar o seu conteúdo e selecionar/deselecionar os checkboxes devidos. Então, tenho isto aqui:
<div id="file-chmod" class="window-outterBevel" style="position: absolute; width: 350px; height: 245px;">
<div class="window-innerBevel" style="width: auto; height: 239px;">
<div class="window-title" style="width: auto; height: 18px; vertical-align: middle;">
<div style="float: right; padding: 2px 3px 1px 0px;"><a href="javascript:closeFileChmodWindow()" title="Fechar a janela">
<img src="system/img/close.gif" style="width: 12px; height: 11px; border: 0; vertical-align: middle;" />
</a></div>
<b style="color: #888;">Permissões do arquivo</b>
</div>
<div style="padding: 10px 4px 2px;">
<table cellpadding="0" cellspacing="0" style="width: 335px; border: 0;">
<form name="chmod" action="fileList.php" method="post">
<tr>
<td>
<input type="hidden" name="action" value="chmod" />
<input type="hidden" name="submit" value="y" />
<input type="hidden" id="file-chmod-name-frm" name="filename" value="" />
<b>Pasta: </b><span id="file-chmod-folder">&nbsp;</span><br />
<br />
<b>Nome do item: </b><span id="file-chmod-name">&nbsp;</span><br />
<b>CHMOD: </b><span id="file-chmod-octal">&nbsp;</span> <b>(</b><span id="file-chmod-nix">&nbsp;</span><b>)</b><br />
<br />
<b>Novo CHMOD: </b><input type="text" class="imput-frm" id="file-chmod-new" name="filechmod" value="000" onchange="updateCheckboxes()" onkeypress="return checkChmodNumber()" maxlength="3" style="width: 50px;" /><br />

<div class="outterBevel" style="width: auto; margin-top: 10px;">
<div class="innerBevel" style="width: auto; padding: 1px;">
<script>var chmod = new Array();</script>
<table cellpadding="0" cellspacing="0" style="width: 328px; border: 0;">
<tr>
<td>
<b>Dono:</b><br />
<script>
chmod[1] = new dCheckBox("file-chmod-chk-1", "Leitura");
document.write("&nbsp;Leitura<br />");
chmod[2] = new dCheckBox("file-chmod-chk-2", "Escrita");
document.write("&nbsp;Escrita<br />");
chmod[3] = new dCheckBox("file-chmod-chk-3", "Execução");
document.write("&nbsp;Execução<br />");
</script>
</td>
<td>
<b>Grupo:</b><br />
<script type="text/javascript">
chmod[4] = new dCheckBox("file-chmod-chk-4", "Leitura");
document.write("&nbsp;Leitura<br />");
chmod[5] = new dCheckBox("file-chmod-chk-5", "Escrita");
document.write("&nbsp;Escrita<br />");
chmod[6] = new dCheckBox("file-chmod-chk-6", "Execução");
document.write("&nbsp;Execução<br />");
</script>
</td>
<td>
<b>Público:</b><br />
<script type="text/javascript">
chmod[7] = new dCheckBox("file-chmod-chk-7", "Leitura");
document.write("&nbsp;Leitura<br />");
chmod[8] = new dCheckBox("file-chmod-chk-8", "Escrita");
document.write("&nbsp;Escrita<br />");
chmod[9] = new dCheckBox("file-chmod-chk-9", "Execução");
document.write("&nbsp;Execução<br />");
</script>
</td>
</tr>
</table>
<script>
var oElCheckBox;
for (i = 1; i < chmod.length; i++) {
oElCheckBox = chmod[i];
//alert(chmod[i].id);
oElCheckBox.onclick = function () { updateChmodOctal(oElCheckBox); }
}
</script>
</div>
</div>

<div style="width: auto; padding-top: 10px; text-align: center">
<input type="submit" name="sender" class="window-button" value="Alterar" />
&nbsp;
<input type="button" class="window-button" value="Cancelar" onclick="closeFileChmodWindow()" />
</div>
</td>
</tr>
</form>
</table>
</div>
</div>
</div>
E, para o evento onchange do input text:
function checkChmodNumber() {
   var oEvent = window.event;
   if (!oEvent) return true;
   else {
       var key = oEvent.keyCode;
       if ((key >= 48 && key <= 55) || (key >= 96 && key <= 103))
           return true;
   }
   return false;
}


function updateCheckboxes() {
   var oElOctal = document.getElementById("file-chmod-new");
   var sChmod = oElOctal.value;

   var iValue;
   for (i = 0; i < 3; i++) {
       iValue = parseInt(sChmod.charAt(i));
       if (iValue > 7) iValue = 7;
       
       if (iValue % 2 != 0)
           chmod[(3 * i + 3)].select();
       if ((iValue < 4 && iValue > 1) || iValue >= 6)
           chmod[(3 * i + 2)].select();
       if (iValue >= 4)
           chmod[(3 * i + 1)].select();
   }
}
E para o onclick dos objectos dCheckbox:
function updateChmodOctal(oElCheckbox) {
   alert(oElCheckbox.method);
   var oElOctal = document.getElementById("file-chmod-new");
   var iChmod = parseInt(oElOctal.value);
   var iItem = parseInt(oElCheckbox.method);

   var iMultiplier = 1;
   if (iItem > 3 && iItem <= 6) iMultiplier *= 10;
   else if (iItem <= 3) iMultiplier *= 100;

   var iChmodValue;
   switch (iItem % 3) {
       case 0: iChmodValue = 1; break;
       case 1: iChmodValue = 4; break;
       case 2: iChmodValue = 2; break;
   }
   
   alert(iChmodValue);
   
   if (oElCheckbox.getSelected())
       iChmod += (iChmodValue * iMultiplier);
   else iChmod -= (iChmodValue * iMultiplier);
   
   oElOctal.value = iChmod;
}

Aparentemente, ele está obtendo o mesmo name para todos os checkboxes... quando na realidade, eles deveriam pegar o primeiro argumento do construtor do objeto.

Depois disto... se conseguirem resolver, veremos qual será o próximo bug...

Esta até que não é tão complicada... provavelmente podemos resolver isto por aqui. Estarei tentando, online no MSN... se alguém quiser entrar em contato...

===

OBS: Post feito pelo meu colega Guilherme Blanco

Link para o comentário
Compartilhar em outros sites

3 respostass a esta questão

Posts Recomendados

  • 0
Guest Guilherme Blanco

Já solucionei o problema...

Crystian,

Esta linha, ela atribui um id ao objeto e depois de atribuir, incrementa a variável.

Isto funciona no JavaScript desde a incorporação de ECMA Script ao JS (meados de 1999).

O problema estava na checagem de teclas... ele obtinha o evento como undefined no IE e no Moz. Esta função aqui:

function checkChmodNumber() {
  var oEvent = window.event;
  if (!oEvent) return true;
  else {
      var key = oEvent.keyCode;
      if ((key >= 48 && key <= 55) || (key >= 96 && key <= 103))
          return true;
  }
  return false;
}
Eu primeiro adicionei o suporte ao Moz (parâmetro "e"), depois ao invés de retornar true para as teclas aceitas, resolvi inverter e retornar falso se as teclas não fossem uma das que eu queria. Veja como fucou:
function checkChmodNumber(e) {
    e = e || window.event;

    if (!e) return true;
    else {
        var key = e.keyCode || e.charCode;
        if (!((key >= 48 && key <= 55) || (key >= 96 && key <= 103) || (key >= 37 && key <= 40) || (key == 8 || key == 46))) {
            if (e.preventDefault)
                e.preventDefault();
            e.returnValue = false;
            return false;
        }
    }
}

Nisto, já funcionou a integração do INPUT com os checkboxes dinâmicos... mas não funcionou ainda a dos checkboxes com o input. Estou analisando e em breve estarei corrigindo.

Grato mesmo assim....

[]s,

Link para o comentário
Compartilhar em outros sites

  • 0

Guilherme o padrão ECMA já está em nosso meio a bastante tempo(como você mesmo disse) e esse mesmo padrão fala em concatenação de string e o caracter usado é o plus(+). Se você quiser incrementar uma variavel inteira com o (++) você tem q se lembrar q não pode colocar uma string antes, pois este inteiro vai se transformar em uma string e não vai poder ser incrementado. O espaço q existe antes não adianta para ele reconhecer o incremento.

Posso estar enganado e q uma nova especificação tenha surgido, mas o meu mozilla 1.6 continua não funcionando para o exemplo q dei.

Abraço

Crystian

Link para o comentário
Compartilhar em outros sites

Participe da discussão

Você pode postar agora e se registrar depois. Se você já tem uma conta, acesse agora para postar com sua conta.

Visitante
Responder esta pergunta...

×   Você colou conteúdo com formatação.   Remover formatação

  Apenas 75 emoticons são permitidos.

×   Seu link foi incorporado automaticamente.   Exibir como um link em vez disso

×   Seu conteúdo anterior foi restaurado.   Limpar Editor

×   Você não pode colar imagens diretamente. Carregar ou inserir imagens do URL.



  • Estatísticas dos Fóruns

    • Tópicos
      152,2k
    • Posts
      651,9k
×
×
  • Criar Novo...