Programación Web y Scripting > JavaScript

 Problemas con Código en Opera/Firefox

(1/2) > >>

xNeCrOx:
Holas! soy nuevo en el foro, quisiera saber si me pueden ayudar con un problemita que tengo con un código que encontre en la red, lo que sucede es que solo funciona con Internet Explorer y no me funciona con Opera/Firefox, alguien me podría ayudar a modificarlo para que estos últimos navegadores señalados fucione el código? habia leído algo de getElementById pero no se como ponerlo para que funcione... ya que en document."algo" puse document.getElementById pero nada... pueden ayudarme? les dejo el código


--- Código: Text ---<html> <head><title>Selecciona elementos en lista</title> <script LANGUAGE="JavaScript"><!-- function moveVals(n, from, to) {    if (document.layers) {        fromObj = document.layers[from];        to = document.layers[to];    } else if (document.all) {        fromObj = document.all(from);        to = document.all(to);    }    if (n == 1 || n == 2) {        var indTo = to.length-1;        for (i=fromObj.length-1; i>=0; i--) {            if (n==1 || fromObj.options[i].selected) {                indTo++;                to.options[indTo] = new Option(fromObj.options[i].text, fromObj.options[i].value);                fromObj.options[i] = null;            }        }    } else if (n == 3 || n == 4) {        var indFrom = fromObj.length-1;        for (i=to.length-1; i>=0; i--) {            if (n==4 || to.options[i].selected) {                indFrom++;                fromObj.options[indFrom] = new Option(to.options[i].text, to.options[i].value);                to.options[i] = null;            }        }    }} function frmButtons() {    var select = "chosen";    var avail = "avail";    if (document.layers) {        var sel = document.layers[select];        var av = document.layers[avail];    } else if (document.all) {        var sel = document.all(select);        var av = document.all(avail);    }    if (sel.length <= 0) {        document.frmAddPro.btnR.disabled = true;        document.frmAddPro.btnRR.disabled = true;    } else {        document.frmAddPro.btnR.disabled = false;        document.frmAddPro.btnRR.disabled = false;    }    if (av.length <= 0) {        document.frmAddPro.btnL.disabled = true;        document.frmAddPro.btnLL.disabled = true;    } else {        document.frmAddPro.btnL.disabled = false;        document.frmAddPro.btnLL.disabled = false;    }} function deleteFrom() {    for (i=0; i<document.frmAddPro.elements.length-1; i++) {        if  (document.frmAddPro.elements[i].tagName.indexOf("SELECT") && document.frmAddPro.elements[i].id.indexOf("av")) {            alert("Cislo: "+i+" Name: "+document.frmAddPro.elements[i].tagName);        }    }}--></script></head><body>   <center><form NAME="frmAddPro">  <table height="172">    <tr>      <td WIDTH="170" CLASS="selCell" style="background-color: #FFFFFF" height="14">      Ciudades disponibles:</td>      <td bgcolor="#FFFFFF" height="14"></td>      <td WIDTH="170" CLASS="selCell" style="background-color: #FFFFFF" height="14">      Tu favorita:</td>    </tr>    <tr>      <td height="150"><select MULTIPLE  NAME="avail[]" ID="avail">      <option>Berlín</option>      <option>Londres</option>      <option>Luxemburgo</option>      <option>Nueva York</option>      <option>Paris</option>      <option>Praga</option>      <option>Tokyo</option>      </select> </td>      <td ALIGN="CENTER" VALIGN="CENTER" height="150">      <input TYPE="button" VALUE=">>"  NAME="btnLL" onClick="moveVals(1, 'avail', 'chosen'); frmButtons(); return false;"><br>      <input TYPE="button" VALUE=">"  NAME="btnL" onClick="moveVals(2, 'avail', 'chosen'); frmButtons(); return false;"><br>      <input TYPE="button" VALUE="<"  NAME="btnR" onClick="moveVals(3, 'avail', 'chosen'); frmButtons(); return false;"><br>      <input TYPE="button" VALUE="<<"  NAME="btnRR" onClick="moveVals(4, 'avail', 'chosen'); frmButtons(); return false;">      </td>      <td height="150"><select MULTIPLE  NAME="chosen[]" id="chosen"></select>      </td>    </tr>  </table></form></center><br></body></html> 

shadow_rev:
Si no estoy mal, en la función moveVals, ni document.layers ni document.all son un estándar; por eso no es raro que sólo funcione con IE. Comienza buscando un sustituto para esta parte.

En cuanto al funcionamiento del document.getElementById(), tienes que poner a tus elementos un id y llamarlos por medio de ese id, de esa forma accedés a ese elemento por medio de esa función. Te pongo el ejemplo:

--- Código: Text ---<script language="javascript"><!--function imprimirContenidoCampo(id_campo_texto) {  document.getElementById("resultado").innerHTML = document.getElementById(id_campo_texto).value;}--></script><body>    <input id="campo_texto" type="text" /><br />    <input type="button" value="imprimir" onclick="imprimirContenidoCampo('campo_texto')" />    <div id="resultado"></div></body> 
Nota: La propiedad innerHTML no es un estándar W3C (aunque funciona en muchos navegadores, incluidos Opera y Firefox), pero es más sencillo de emplear que usando la estructura del DOM (crear nodos y luego agregarlos)

:suerte:

xNeCrOx:
Gracias, entendí bien que document.layers y document.all para nada son estándar y como IE nunca los ha respetado deseché la posibilidad de usar ese código ahora trabaje en otro que funcionará con mis necesidades. por suerte tenía este código que no recuerdo de donde lo había sacado.


--- Código: Text ---<html><head><title>Selecciona elementos en la lista</title> </head> <BODY style="font-family: Verdana"><p align="center"><b>Selecciona elementos en lista 2</b></p> <SCRIPT LANGUAGE="JavaScript"> function moveOver()  {var boxLength = document.choiceForm.choiceBox.length;var selectedItem = document.choiceForm.available.selectedIndex;var selectedText = document.choiceForm.available.options[selectedItem].text;var selectedValue = document.choiceForm.available.options[selectedItem].value;var i;var isNew = true;if (boxLength != 0) {for (i = 0; i < boxLength; i++) {thisitem = document.choiceForm.choiceBox.options[i].text;if (thisitem == selectedText) {isNew = false;break;      }   }} if (isNew) {newoption = new Option(selectedText, selectedValue, false, false);document.choiceForm.choiceBox.options[boxLength] = newoption;}document.choiceForm.available.selectedIndex=-1;}function removeMe() {var boxLength = document.choiceForm.choiceBox.length;arrSelected = new Array();var count = 0;for (i = 0; i < boxLength; i++) {if (document.choiceForm.choiceBox.options[i].selected) {arrSelected[count] = document.choiceForm.choiceBox.options[i].value;}count++;}var x;for (i = 0; i < boxLength; i++) {for (x = 0; x < arrSelected.length; x++) {if (document.choiceForm.choiceBox.options[i].value == arrSelected[x]) {document.choiceForm.choiceBox.options[i] = null;   }}boxLength = document.choiceForm.choiceBox.length;   }}function saveMe() {var strValues = "";var boxLength = document.choiceForm.choiceBox.length;var count = 0;if (boxLength != 0) {for (i = 0; i < boxLength; i++) {if (count == 0) {strValues = document.choiceForm.choiceBox.options[i].value;}else {strValues = strValues + "," + document.choiceForm.choiceBox.options[i].value;}count++;   }}if (strValues.length == 0) {alert("No has hecho ninguna selección");}else {      onSubmit();   }}//  End --></script></HEAD> <html><head><title>Selección de elementos</title> </head>  <BODY style="font-family: Verdana"> <center><form name="choiceForm" method="post" action="lista.php"><table border=0 width="414"><tr><td valign="top" width=227><font size="2">Contenido disponible: </font><br><select name="available" size=10 onchange="moveOver();"><option value="funcionarios">Funcionarios<option value="cargo_trabajador">Cargo Trabajador<option value="actualizar">Actualizaciones de productos<option value="especificacion">Especificaciones de productos<option value="historia">Historia de pedidos<option value="estado_pedido">Estado del pedido<option value="contactos">Contactos<option value="calendario">Calendario de eventos<option value="planificaciones">Planificación<option value="notas">Notas</select></td>        <td width="177" valign="top" bordercolor="#CCCCFF"> <font size="2">Tu           selección: </font> <br><select multiple name="choiceBox[]" id="choiceBox" style="width:150;" size="10"></select></td></tr><tr><td height=10 width="390"><input type="button" value="Eliminar seleccionados" onclick="removeMe();" style="font-size: 8pt"><br><input type="submit" value="Obtener valores seleccionados" onclick="saveMe();" style="font-size: 8pt"><br><input type="button" value="Seleccionar todos" onclick="selAll(true)" style="font-size: 8pt"><br><input type="button" value="Quitar selección" onclick="selAll(false)" style="font-size: 8pt"><br></td></tr></table></form></center><script>function selAll(_v) {for(var i=0;i<document.choiceForm.choiceBox.length;i++)  document.choiceForm.choiceBox[i].selected=_v;}</script></body></html> 
El asunto ahora es que es solo un ejemplo, ya que quiero que los elementos que vaya a seleccionar sean campos para consultar a una base de datos en MySQL: Por ejemplo, selecciono funcionarios y cargo trabajador... el option value serian las tablas que yo quiero consultar a la base de datos.. o sea funcionarios y cargo_trabajador, al enviarlo a php no se como poder realizar la consulta para que me muestre los datos de dichas tablas que quiero ver...

Esto es lo que tengo en el PHP.


--- Código: Text ---<?php  foreach ($_POST['choiceBox'] as $indice => $valor){ echo "indice: ".$indice." => ".$valor."<br>";  ?> 
Con esto demuestro que puedo obtener los valores del select multiple del formulario anterior, pero como hacer para que esos valores, pueda realizarlos en una consulta SQL y que sean las tablas de dicha consulta y asi obtener los datos de esas tablas, asi poder mostrarlas con un echo?...

xNeCrOx:
Me auto respondo.. aquí tengo el código funcional para Opera y Firefox... se los dejó.. pero aun quisiera saber como obtener esos datos para procesarlos en MySQL teniendo encuenta que cada dato que escoja del select multiple sean necesariamente tablas de una base de datos.. espero que me puedan ayudar...


--- Código: Text ---Código PHP <html> <head><title>Selecciona elementos en lista</title> <script type="text/javascript"><!-- function moveVals(n, from, to) {        fromObj = document.getElementById(from);        to =  document.getElementById(to);    if (n == 1 || n == 2) {        var indTo = to.length-1;        for (ii=fromObj.length-1; ii>=0; ii--) {            if (n==1 || fromObj.options[ii].selected) {                indTo++;                to.options[indTo] = new Option(fromObj.options[ii].text, fromObj.options[ii].value);                fromObj.options[ii] = null;            }        }    } else if (n == 3 || n == 4) {        var indFrom = fromObj.length-1;        for (ii=to.length-1; ii>=0; ii--) {            if (n==4 || to.options[ii].selected) {                indFrom++;                fromObj.options[indFrom] = new Option(to.options[ii].text, to.options[ii].value);                to.options[ii] = null;            }        }    }} function frmButtons() {        var sel = document.getElementById("chosen");        var av = document.getElementById("avail");    if (sel.length <= 0) {        document.frmAddPro.btnR.disabled = true;        document.frmAddPro.btnRR.disabled = true;    } else {        document.frmAddPro.btnR.disabled = false;        document.frmAddPro.btnRR.disabled = false;    }    if (av.length <= 0) {        document.frmAddPro.btnL.disabled = true;        document.frmAddPro.btnLL.disabled = true;    } else {        document.frmAddPro.btnL.disabled = false;        document.frmAddPro.btnLL.disabled = false;    }} function deleteFrom() {    for (ii=0; ii<document.frmAddPro.elements.length-1; ii++) {        if  (document.frmAddPro.elements[ii].tagName.indexOf("SELECT") && document.frmAddPro.elements[ii].id.indexOf("av")) {            alert("Cislo: "+ii+" Name: "+document.frmAddPro.elements[ii].tagName);        }    }}--></script></head><body>   <center><form NAME="frmAddPro">  <table height="172">    <tr>      <td WIDTH="170" CLASS="selCell" style="background-color: #FFFFFF" height="14">      Ciudades disponibles:</td>      <td bgcolor="#FFFFFF" height="14"></td>      <td WIDTH="170" CLASS="selCell" style="background-color: #FFFFFF" height="14">      Tu favorita:</td>    </tr>    <tr>      <td height="150"><select MULTIPLE  NAME="avail[]" ID="avail">      <option>Berlín</option>      <option>Londres</option>      <option>Luxemburgo</option>      <option>Nueva York</option>      <option>Paris</option>      <option>Praga</option>      <option>Tokyo</option>      </select> </td>      <td ALIGN="CENTER" VALIGN="CENTER" height="150">      <input TYPE="button" VALUE=">>"  NAME="btnLL" onClick="moveVals(1, 'avail', 'chosen'); frmButtons(); return false;"><br>      <input TYPE="button" VALUE=">"  NAME="btnL" onClick="moveVals(2, 'avail', 'chosen'); frmButtons(); return false;"><br>      <input TYPE="button" VALUE="<"  NAME="btnR" onClick="moveVals(3, 'avail', 'chosen'); frmButtons(); return false;"><br>      <input TYPE="button" VALUE="<<"  NAME="btnRR" onClick="moveVals(4, 'avail', 'chosen'); frmButtons(); return false;">      </td>      <td height="150"><select MULTIPLE  NAME="chosen[]" id="chosen"></select>      </td>    </tr>  </table></form></center><br></body></html> 

shadow_rev:
La verdad no entendí muy bien que es lo que quieres hacer; si el value de los option son los nombres de las tablas, pues con el uso de $_POST[nombre_checkbox][indice] deberías obtenerlos. Te sugiero que traslades la pregunta al foro de PHP, ya que aquí ese tema es offtopic y allá puedes encontrar más ayuda.

:suerte:

Navegación

[0] Índice de Mensajes

[#] Página Siguiente

Ir a la versión completa