Foros del Web » Programando para Internet » Javascript »

Multiples selects dinámicos

Estas en el tema de Multiples selects dinámicos en el foro de Javascript en Foros del Web. Saludos corillo, Estoy trabajando con una aplicación que requiere de multiples selects y que todos se formen de acuerdo a un valor seleccionado. Lo logré ...
  #1 (permalink)  
Antiguo 08/03/2011, 09:56
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Multiples selects dinámicos

Saludos corillo,

Estoy trabajando con una aplicación que requiere de multiples selects y que todos se formen de acuerdo a un valor seleccionado. Lo logré pero es un poco complicado trabajarlo. Esta es la forma como lo hago al momento.

Nota: Estos los formo con PHP por lo que se me hace menos difícil formarlos
Código HTML:
Ver original
  1. <script type="text/javascript">
  2. function nullOptions(obj){
  3.     var n=obj.options.length
  4.     for (i=0;i<n;i++){
  5.         obj.options[i]=null
  6.     }
  7.     obj.options.length=0;
  8. }
  9.  
  10.  
  11. /**
  12. * Seconds elements
  13. */
  14. function secondElements1(obj){
  15.     nullOptions(obj);
  16.     var n=0;
  17.     with(obj){
  18.         options[n++]=new Option("Selecciona bar","");
  19.         options[n++]=new Option(20, 20);
  20.         options[n++]=new Option(30, 30);
  21.         options[n++]=new Option(40, 40);
  22.     }
  23. }
  24. function secondElements2(obj){
  25.     nullOptions(obj);
  26.     var n=0;
  27.     with(obj){
  28.         options[n++]=new Option("Selecciona bar","");
  29.         options[n++]=new Option(200, 200);
  30.         options[n++]=new Option(300, 300);
  31.         options[n++]=new Option(400, 400);
  32.     }
  33. }
  34. function secondElements3(obj){
  35.     nullOptions(obj);
  36.     var n=0;
  37.     with(obj){
  38.         options[n++]=new Option("Selecciona bar","");
  39.         options[n++]=new Option(2000, 2000);
  40.         options[n++]=new Option(3000, 3000);
  41.         options[n++]=new Option(4000, 4000);
  42.     }
  43. }
  44.  
  45. /**
  46. * Thirds elements
  47. */
  48.  
  49. /**
  50. * Elementos para el valor 20, 30 y 40 de bar
  51. */
  52. function thirdElements1000(obj){
  53.     nullOptions(obj);
  54.     var n=0;
  55.     with(obj){
  56.         options[n++]=new Option("Selecciona candy","");
  57.         options[n++]=new Option(21, 21);
  58.         options[n++]=new Option(22, 22);
  59.         options[n++]=new Option(23, 23);
  60.     }
  61. }
  62. function thirdElements1001(obj){
  63.     nullOptions(obj);
  64.     var n=0;
  65.     with(obj){
  66.         options[n++]=new Option("Selecciona candy","");
  67.         options[n++]=new Option(31, 31);
  68.         options[n++]=new Option(32, 32);
  69.         options[n++]=new Option(33, 33);
  70.     }
  71. }
  72. function thirdElements1002(obj){
  73.     nullOptions(obj);
  74.     var n=0;
  75.     with(obj){
  76.         options[n++]=new Option("Selecciona candy","");
  77.         options[n++]=new Option(41, 41);
  78.         options[n++]=new Option(42, 42);
  79.         options[n++]=new Option(43, 43);
  80.     }
  81. }
  82.  
  83. /**
  84. * Elementos para los valores 200, 300 y 400 de bar
  85. */
  86. function thirdElements1003(obj){
  87.     nullOptions(obj);
  88.     var n=0;
  89.     with(obj){
  90.         options[n++]=new Option("Selecciona candy","");
  91.         options[n++]=new Option(210, 210);
  92.         options[n++]=new Option(220, 220);
  93.         options[n++]=new Option(230, 230);
  94.     }
  95. }
  96. function thirdElements1004(obj){
  97.     nullOptions(obj);
  98.     var n=0;
  99.     with(obj){
  100.         options[n++]=new Option("Selecciona candy","");
  101.         options[n++]=new Option(310, 310);
  102.         options[n++]=new Option(320, 320);
  103.         options[n++]=new Option(330, 330);
  104.     }
  105. }
  106. function thirdElements1005(obj){
  107.     nullOptions(obj);
  108.     var n=0;
  109.     with(obj){
  110.         options[n++]=new Option("Selecciona candy","");
  111.         options[n++]=new Option(410, 410);
  112.         options[n++]=new Option(420, 420);
  113.         options[n++]=new Option(430, 430);
  114.     }
  115. }
  116.  
  117. /**
  118. * Elementos para los valores 2000, 3000 y 4000 de bar
  119. */
  120. function thirdElements1006(obj){
  121.     nullOptions(obj);
  122.     var n=0;
  123.     with(obj){
  124.         options[n++]=new Option("Selecciona candy","");
  125.         options[n++]=new Option(2100, 2100);
  126.         options[n++]=new Option(2200, 2200);
  127.         options[n++]=new Option(2300, 2300);
  128.     }
  129. }
  130. function thirdElements1007(obj){
  131.     nullOptions(obj);
  132.     var n=0;
  133.     with(obj){
  134.         options[n++]=new Option("Selecciona candy","");
  135.         options[n++]=new Option(3100, 3100);
  136.         options[n++]=new Option(3200, 3200);
  137.         options[n++]=new Option(3300, 3300);
  138.     }
  139. }
  140. function thirdElements1008(obj){
  141.     nullOptions(obj);
  142.     var n=0;
  143.     with(obj){
  144.         options[n++]=new Option("Selecciona candy","");
  145.         options[n++]=new Option(4100, 4100);
  146.         options[n++]=new Option(4200, 4200);
  147.         options[n++]=new Option(4300, 4300);
  148.     }
  149. }
  150.  
  151. function firstFunction(obj){
  152.     var firstElement = obj.first;
  153.     var secondElement = obj.second;
  154.     var thirdElement = obj.third;
  155.     switch(firstElement.selectedIndex){
  156.         case 0:
  157.             secondElement.options.length=0;
  158.             secondElement.options[0]=new Option("[Selecciona foo]","");
  159.             secondElement.options[0].selected=true;
  160.  
  161.             thirdElement.options.length=0;
  162.             thirdElement.options[0]=new Option("[Selecciona foo]","");
  163.             thirdElement.options[0].selected=true;
  164.             break;
  165.         case 1:
  166.             secondElements1(secondElement);
  167.             secondElement.options[0].text="[Selecciona bar]";
  168.  
  169.             thirdElement.options.length=0;
  170.             thirdElement.options[0]=new Option("[Selecciona bar]","");
  171.             thirdElement.options[0].selected=true;
  172.             break;
  173.         case 2:
  174.             secondElements2(secondElement);
  175.             secondElement.options[0].text="[Selecciona bar]";
  176.  
  177.             thirdElement.options.length=0;
  178.             thirdElement.options[0]=new Option("[Selecciona bar]","");
  179.             thirdElement.options[0].selected=true;
  180.             break;
  181.         case 3:
  182.             secondElements3(secondElement);
  183.             secondElement.options[0].text="[Selecciona bar]";
  184.  
  185.             thirdElement.options.length=0;
  186.             thirdElement.options[0]=new Option("[Selecciona bar]","");
  187.             thirdElement.options[0].selected=true;
  188.             break;
  189.     }
  190. }
  191.  
  192. function secondFunction(obj){
  193.     var firstElement = obj.first;
  194.     var secondElement = obj.second;
  195.     var thirdElement = obj.third;
  196.     switch(firstElement.selectedIndex){
  197.         case 0:
  198.             secondElement.options.length=0;
  199.             secondElement.options[0]=new Option("[Selecciona foo]","");
  200.             secondElement.options[0].selected=true;
  201.  
  202.             thirdElement.options.length=0;
  203.             thirdElement.options[0]=new Option("[Selecciona foo]","");
  204.             thirdElement.options[0].selected=true;
  205.             break;
  206.         case 1:
  207.             switch(secondElement.selectedIndex){
  208.                 case 0:
  209.                     thirdElement.options.length=0;
  210.                     thirdElement.options[0]=new Option("[Selecciona bar]","");
  211.                     thirdElement.options[0].selected=true;
  212.                     break;
  213.                 case 1:
  214.                     thirdElements1000(thirdElement);
  215.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  216.                     thirdElement.options[0].selected=true;
  217.                     break;
  218.                 case 2:
  219.                     thirdElements1001(thirdElement);
  220.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  221.                     thirdElement.options[0].selected=true;
  222.                     break;
  223.                 case 3:
  224.                     thirdElements1002(thirdElement);
  225.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  226.                     thirdElement.options[0].selected=true;
  227.                     break;
  228.             }
  229.             break;
  230.         case 2:
  231.             switch(secondElement.selectedIndex){
  232.                 case 0:
  233.                     thirdElement.options.length=0;
  234.                     thirdElement.options[0]=new Option("[Selecciona bar]","");
  235.                     thirdElement.options[0].selected=true;
  236.                     break;
  237.                 case 1:
  238.                     thirdElements1003(thirdElement);
  239.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  240.                     thirdElement.options[0].selected=true;
  241.                     break;
  242.                 case 2:
  243.                     thirdElements1004(thirdElement);
  244.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  245.                     thirdElement.options[0].selected=true;
  246.                     break;
  247.                 case 3:
  248.                     thirdElements1005(thirdElement);
  249.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  250.                     thirdElement.options[0].selected=true;
  251.                     break;
  252.             }
  253.             break;
  254.         case 3:
  255.             switch(secondElement.selectedIndex){
  256.                 case 0:
  257.                     thirdElement.options.length=0;
  258.                     thirdElement.options[0]=new Option("[Selecciona bar]","");
  259.                     thirdElement.options[0].selected=true;
  260.                     break;
  261.                 case 1:
  262.                     thirdElements1006(thirdElement);
  263.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  264.                     thirdElement.options[0].selected=true;
  265.                     break;
  266.                 case 2:
  267.                     thirdElements1007(thirdElement);
  268.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  269.                     thirdElement.options[0].selected=true;
  270.                     break;
  271.                 case 3:
  272.                     thirdElements1008(thirdElement);
  273.                     thirdElement.options[0]=new Option("[Selecciona candy]","");
  274.                     thirdElement.options[0].selected=true;
  275.                     break;
  276.             }
  277.             break;
  278.     }
  279. }
  280. <form action="#">
  281.     Foo:
  282.     <select name="first" onchange="firstFunction(this.form)">
  283.         <option value="">[Selecciona uno]</option>
  284.         <option value="1">1</option>
  285.         <option value="100">100</option>
  286.         <option value="1000">1000</option>
  287.     </select><br />
  288.  
  289.     Bar:
  290.     <select name="second" onchange="secondFunction(this.form)">
  291.         <option value="">[Selecciona Foo]</option>
  292.     </select><br />
  293.  
  294.     Candy:
  295.     <select name="third">
  296.         <option value="">[Selecciona Foo]</option>
  297.     </select>
  298. </form>

Lo que me interesa saber es alguna otra forma de lograrlo pero sin un framework y sin ajax que también creo que es otra forma sencilla. Lo dejo por si le ayuda a alguien, aunque está demasiado grande el código para lograr lo que yo quiero. La razón por la pregunta es que luego voy a tener que trabajar que el último valor modifique otro valor y va a ser un código muy grande para trabajar. Bueno me dejan saber

¡Muchas gracias!
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #2 (permalink)  
Antiguo 08/03/2011, 12:09
Avatar de goteen_mx  
Fecha de Ingreso: abril-2005
Ubicación: D.F.
Mensajes: 403
Antigüedad: 19 años
Puntos: 37
Respuesta: Multiples selects dinámicos

Yo creo que para no tener cada una de las funciones puedes hacer una generica que reciba que select va a llenar y todas tus opciones guardarlas en un arreglo a manera de matriz y recorres el arreglo cada que quieres llenar un select por ej.

Código Javascript:
Ver original
  1. <html>
  2. <head>
  3. <script>
  4. var aOpciones = new Array();
  5. //esto se llenaria con PHP
  6. // se me ocurre esta estructura [idOpcion, icPadre, opcionTexto] a fin de llenarlo a manera de un árbol con sus hijos
  7.  
  8. aOpciones[0]=[1,0,'primerSelect1'];
  9. aOpciones[1]=[2,0,'primerSelect2'];
  10. //las dependientes del hijo
  11. aOpciones[2]=[3,1,'hijo1 primer select opcion 0'];
  12. aOpciones[3]=[4,1,'hijo 2  primer select opcion 0'];
  13. //dependientes del segundo hijo
  14. aOpciones[4]=[4,2,'hijo1 primeer select opcion1'];
  15. aOpciones[5]=[5,2,'hijo2 primer select opcin1'];
  16. //...........
  17. //...........N hijos
  18.  
  19.  
  20.  //primer parametro la forma, segundo el select a llenar
  21. function f_llenaSlect(forma, slectPos){
  22.         //si es -1 es el ultimo select para llenar
  23.         if(slectPos==-1)
  24.             return;
  25.          else{//limpio select a llenar
  26.                 (document.getElementById("slect"+slectPos).options.length=0;
  27.                 for(var i=0;i<aOpciones.length:i++){//for para recorrer el arreglo
  28.                       if(aOpciones[i][1]==document.getElementById("slect"+slectPos-1).options.selectedIndex){  // obtengo la opcion seleccionada del padre y comparo el arreglo
  29.                               document.getElementById("slect"+slectPos).options.length++;
  30.                               document.getElementById("slect"+slectPos).options[document.getElementById("slect"+slectPos).options.length-1].value=aOpciones[i][0];
  31.                               document.getElementById("slect"+slectPos).options[document.getElementById("slect"+slectPos).options.length-1].text=aOpciones[i][2];
  32.                         }
  33.               }
  34.      }
  35. }
  36. </script>
  37. </head>
  38. <body onload="f_llenaSlect(document.forms[0],1)">
  39. <form action="#">
  40.  
  41.     Foo:
  42.  
  43.     <select name="slect1" onchange="firstFunction(this.form,2);">
  44.  
  45.         <option value="">[Selecciona uno]</option>
  46.  
  47.     </select><br />
  48.  
  49.  
  50.  
  51.     Bar:
  52.  
  53.     <select id="slct2" onchange="f_llenaSlect(this.form,3);">
  54.  
  55.         <option value="">[Selecciona Foo]</option>
  56.  
  57.     </select><br />
  58.  
  59.  
  60.  
  61.     Candy:
  62.  
  63.     <select id="slect3" onchange="f_llenaSlect(this.form,-1);">
  64.  
  65.         <option value="">[Selecciona Foo]</option>
  66.  
  67.     </select>
  68.  
  69. </form>
  70. </body>
  71. </html>

Y ya si necesitas que cada opcion o select tenga una función en especifico, la puedes agregar al arreglo y asignarla con js al select que necesites.

Saludos.
  #3 (permalink)  
Antiguo 08/03/2011, 12:41
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Multiples selects dinámicos

Ohhhh, es verdad que se puede trabajar con arreglos. Muy bueno
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #4 (permalink)  
Antiguo 08/03/2011, 19:07
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: Multiples selects dinámicos

que tal corillo!

solo como una observacion acerca de la estructura de datos. tambien puedes usar formato json. algo parecido a como firefox y chrome guarda los bookmarks. es decir, no solo arrays, sino objetos y propiedades para lograr una mejor estructuracion. alguna vez habia comenzado hacer uno pero nunca lo termine.

saludos!
__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #5 (permalink)  
Antiguo 08/03/2011, 21:58
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Multiples selects dinámicos

Si lo pensé, el de crearlos con php y luego pasarlo usando json, lo tendré en cuenta
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos
  #6 (permalink)  
Antiguo 14/03/2011, 12:36
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Multiples selects dinámicos

Bueno, dejo la forma como lo estoy trabajando (sinceramente no me siento orgulloso, pero para que otro se beneficie). Cuando crezca y sea grande y pueda hacer las cosas que hacen muchos de este foro, lo posteo como aporte, pero mientras tanto lo dejo en este tema

Cuando el valor y el texto es igual lo pueden hacer así
Código HTML:
Ver original
  1. <script type="text/javascript">
  2. var arrOpt = new Array();
  3. arrOpt[1] = new Array();
  4. arrOpt[1][20] = new Array();
  5. arrOpt[1][20][21] = new Array();
  6. arrOpt[1][20][22] = new Array();
  7. arrOpt[1][20][23] = new Array();
  8. arrOpt[1][30] = new Array();
  9. arrOpt[1][30][31] = new Array();
  10. arrOpt[1][30][32] = new Array();
  11. arrOpt[1][30][33] = new Array();
  12. arrOpt[1][40] = new Array();
  13. arrOpt[1][40][41] = new Array();
  14. arrOpt[1][40][42] = new Array();
  15. arrOpt[1][40][43] = new Array();
  16.  
  17. arrOpt[100] = new Array();
  18. arrOpt[100][110] = new Array();
  19. arrOpt[100][110][111] = new Array();
  20. arrOpt[100][110][112] = new Array();
  21. arrOpt[100][110][113] = new Array();
  22. arrOpt[100][120] = new Array();
  23. arrOpt[100][120][121] = new Array();
  24. arrOpt[100][120][122] = new Array();
  25. arrOpt[100][120][123] = new Array();
  26. arrOpt[100][130] = new Array();
  27. arrOpt[100][130][131] = new Array();
  28. arrOpt[100][130][132] = new Array();
  29. arrOpt[100][130][133] = new Array();
  30.  
  31. arrOpt[1000] = new Array();
  32. arrOpt[1000][1100] = new Array();
  33. arrOpt[1000][1100][1110] = new Array();
  34. arrOpt[1000][1100][1120] = new Array();
  35. arrOpt[1000][1100][1130] = new Array();
  36. arrOpt[1000][1200] = new Array();
  37. arrOpt[1000][1200][1210] = new Array();
  38. arrOpt[1000][1200][1220] = new Array();
  39. arrOpt[1000][1200][1230] = new Array();
  40. arrOpt[1000][1300] = new Array();
  41. arrOpt[1000][1300][1310] = new Array();
  42. arrOpt[1000][1300][1320] = new Array();
  43. arrOpt[1000][1300][1330] = new Array();
  44.  
  45. var fIndexSession = 0;
  46. var sIndexSession = 0;
  47. var tIndexSession = 0;
  48.  
  49. function nullOptions(obj){
  50.     var n=obj.options.length
  51.     for (i=0;i<n;i++){
  52.         obj.options[i]=null
  53.     }
  54.     obj.options.length=0;
  55. }
  56.  
  57. function getOpt(objs){
  58.     var f = objs[0];
  59.     var fIndex = f.selectedIndex;
  60.  
  61.     var s = objs[1];
  62.     var sIndex = fIndexSession == fIndex ? s.selectedIndex : 0;
  63.     nullOptions(s);
  64.     sText = fIndex > 0
  65.         ? "Bar"
  66.         : "Foo";
  67.     s.options[0] = new Option("[Selecciona " + sText + "]", "", true);
  68.  
  69.     var t = objs[2];
  70.     var tIndex = sIndexSession == sIndex ? t.selectedIndex : 0;
  71.     nullOptions(t);
  72.     tText = fIndex > 0
  73.         ? (sIndex > 0
  74.             ? "Candy"
  75.             : "Bar")
  76.         : "Foo";
  77.     t.options[0] = new Option("[Selecciona " + tText + "]", "", true);
  78.  
  79.     fIndexSession = fIndex;
  80.     sIndexSession = sIndex;
  81.     tIndexSession = tIndex;
  82.  
  83.     for(var i in arrOpt){
  84.         if(i == f.value){
  85.             var n = 1;
  86.             for(var ii in arrOpt[i]){
  87.                 bool = sIndex == n ? true : false;
  88.                 s.options[n++] = new Option(ii, ii, false, bool);
  89.                 if(ii == s.value){
  90.                     var nn = 1;
  91.                     for(var iii in arrOpt[i][ii]){
  92.                         bool = tIndex == nn ? true : false;
  93.                         t.options[nn++] = new Option(iii, iii, false, bool);
  94.                     }
  95.                 }
  96.             }
  97.         }
  98.     }
  99. }
  100. <form action="#">
  101.     Foo:
  102.     <select name="first" onchange="getOpt({0:this.form.first, 1:this.form.second, 2:this.form.third})">
  103.         <option value="">[Selecciona uno]</option>
  104.         <option value="1">1</option>
  105.         <option value="100">100</option>
  106.         <option value="1000">1000</option>
  107.     </select><br />
  108.  
  109.     Bar:
  110.     <select name="second" onchange="getOpt({0:this.form.first, 1:this.form.second, 2:this.form.third})">
  111.         <option value="">[Selecciona Foo]</option>
  112.     </select><br />
  113.  
  114.     Candy:
  115.     <select name="third">
  116.         <option value="">[Selecciona Foo]</option>
  117.     </select>
  118. </form>


Cuando el valor es diferente al texto, lo pueden hacer así
Código HTML:
Ver original
  1. <script type="text/javascript">
  2. var arrOpt = new Array();
  3. arrOpt[1] = new Array();
  4. arrOpt[1]["20_veinte"] = new Array();
  5. arrOpt[1]["20_veinte"]["21_veintiuno"] = new Array();
  6. arrOpt[1]["20_veinte"]["22_veintidos"] = new Array();
  7. arrOpt[1]["20_veinte"]["23_veintitres"] = new Array();
  8. arrOpt[1]["30_treinta"] = new Array();
  9. arrOpt[1]["30_treinta"]["31_treinta y uno"] = new Array();
  10. arrOpt[1]["30_treinta"]["32_treinta y dos"] = new Array();
  11. arrOpt[1]["30_treinta"]["33_treinta y tres"] = new Array();
  12. arrOpt[1]["40_cuarenta"] = new Array();
  13. arrOpt[1]["40_cuarenta"]["41_cuarenta y uno"] = new Array();
  14. arrOpt[1]["40_cuarenta"]["42_cuarenta y dos"] = new Array();
  15. arrOpt[1]["40_cuarenta"]["43_cuarenta y tres"] = new Array();
  16.  
  17. arrOpt[100] = new Array();
  18. arrOpt[100]["110_ciento diez"] = new Array();
  19. arrOpt[100]["110_ciento diez"]["111_ciento once"] = new Array();
  20. arrOpt[100]["110_ciento diez"]["111_ciento doce"] = new Array();
  21. arrOpt[100]["110_ciento diez"]["111_ciento trece"] = new Array();
  22. arrOpt[100]["120_ciento veinte"] = new Array();
  23. arrOpt[100]["120_ciento veinte"]["121_ciento veintiuno"] = new Array();
  24. arrOpt[100]["120_ciento veinte"]["122_ciento veintidos"] = new Array();
  25. arrOpt[100]["120_ciento veinte"]["123_ciento veintitres"] = new Array();
  26. arrOpt[100]["130_ciento treinta"] = new Array();
  27. arrOpt[100]["130_ciento treinta"]["131_ciento treinta y uno"] = new Array();
  28. arrOpt[100]["130_ciento treinta"]["131_ciento treinta y dos"] = new Array();
  29. arrOpt[100]["130_ciento treinta"]["131_ciento treinta y tres"] = new Array();
  30.  
  31. arrOpt[1000] = new Array();
  32. arrOpt[1000]["1100_mil cien"] = new Array();
  33. arrOpt[1000]["1100_mil cien"]["1110_mil ciento diez"] = new Array();
  34. arrOpt[1000]["1100_mil cien"]["1120_mil ciento veinte"] = new Array();
  35. arrOpt[1000]["1100_mil cien"]["1130_mil ciento treinta"] = new Array();
  36. arrOpt[1000]["1200_mil docientos"] = new Array();
  37. arrOpt[1000]["1200_mil docientos"]["1210_mil docientos diez"] = new Array();
  38. arrOpt[1000]["1200_mil docientos"]["1220_mil docientos veinte"] = new Array();
  39. arrOpt[1000]["1200_mil docientos"]["1230_mil docientos treinta"] = new Array();
  40. arrOpt[1000]["1300_mil trecientos"] = new Array();
  41. arrOpt[1000]["1300_mil trecientos"]["1310_mil trecientos diez"] = new Array();
  42. arrOpt[1000]["1300_mil trecientos"]["1320_mil trecientos veinte"] = new Array();
  43. arrOpt[1000]["1300_mil trecientos"]["1330_mil trecientos treinta"] = new Array();
  44.  
  45. var fIndexSession = 0;
  46. var sIndexSession = 0;
  47. var tIndexSession = 0;
  48.  
  49. function nullOptions(obj){
  50.     var n=obj.options.length
  51.     for (i=0;i<n;i++){
  52.         obj.options[i]=null
  53.     }
  54.     obj.options.length=0;
  55. }
  56.  
  57. function getOpt(objs){
  58.     var f = objs[0];
  59.     var fIndex = f.selectedIndex;
  60.  
  61.     var s = objs[1];
  62.     var sIndex = fIndexSession == fIndex ? s.selectedIndex : 0;
  63.     nullOptions(s);
  64.     sText = fIndex > 0
  65.         ? "Bar"
  66.         : "Foo";
  67.     s.options[0] = new Option("[Selecciona " + sText + "]", "", true);
  68.  
  69.     var t = objs[2];
  70.     var tIndex = sIndexSession == sIndex ? t.selectedIndex : 0;
  71.     nullOptions(t);
  72.     tText = fIndex > 0
  73.         ? (sIndex > 0
  74.             ? "Candy"
  75.             : "Bar")
  76.         : "Foo";
  77.     t.options[0] = new Option("[Selecciona " + tText + "]", "", true);
  78.  
  79.     fIndexSession = fIndex;
  80.     sIndexSession = sIndex;
  81.     tIndexSession = tIndex;
  82.  
  83.     for(var i in arrOpt){
  84.         if(i == f.value){
  85.             var n = 1;
  86.             for(var ii in arrOpt[i]){
  87.                 sKey = ii.split("_");
  88.                 bool = sIndex == n ? true : false;
  89.                 s.options[n++] = new Option(sKey[1], sKey[0], false, bool);
  90.                 if(sKey[0] == s.value){
  91.                     var nn = 1;
  92.                     for(var iii in arrOpt[i][ii]){
  93.                         tKey = iii.split("_");
  94.                         bool = tIndex == nn ? true : false;
  95.                         t.options[nn++] = new Option(tKey[1], tKey[0], false, bool);
  96.                     }
  97.                 }
  98.             }
  99.         }
  100.     }
  101. }
  102. <form action="#">
  103.     Foo:
  104.     <select name="first" onchange="getOpt({0:this.form.first, 1:this.form.second, 2:this.form.third})">
  105.         <option value="">[Selecciona uno]</option>
  106.         <option value="1">uno</option>
  107.         <option value="100">cien</option>
  108.         <option value="1000">mil</option>
  109.     </select><br />
  110.  
  111.     Bar:
  112.     <select name="second" onchange="getOpt({0:this.form.first, 1:this.form.second, 2:this.form.third})">
  113.         <option value="">[Selecciona Foo]</option>
  114.     </select><br />
  115.  
  116.     Candy:
  117.     <select name="third">
  118.         <option value="">[Selecciona Foo]</option>
  119.     </select>
  120. </form>

De estas dos formas eliminé más de 150 lineas de código.
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos

Última edición por abimaelrc; 15/03/2011 a las 06:30 Razón: quitar un parametro innecesario en las funciones
  #7 (permalink)  
Antiguo 14/03/2011, 20:45
Avatar de goteen_mx  
Fecha de Ingreso: abril-2005
Ubicación: D.F.
Mensajes: 403
Antigüedad: 19 años
Puntos: 37
Respuesta: Multiples selects dinámicos

Hola abimaelrc, viendo tu código me entro una duda que espero me puedan ayudar a resolver.

¿¿Los array en JS reservan memoria??

me puse a investigar y no hay una respuesta muy clara,unos dicen que si, otros que no :S otros que el length es virtual, la verdad es que no encontre algo que me convenciera al 100%

Pero bueno en el caso de que si ocupe memoria, creo que el código pudirera mejorarse dado que si estaría reservando 1000x1300x1330 espacios en memoria y estos podrian pasar a ser elementos del arreglo y no índices y tendrías un array de escasos 35 elementos, por otra parte en caso de que no, pues no habría por que preocuparse jejejeje y en el segundo caso al ser índices asociativos pues no habria problema en el peor de los casos se ocuparían 1001 elementos y los demás estarían referenciados.

Saludos.
__________________
Born to be free.
  #8 (permalink)  
Antiguo 14/03/2011, 21:25
 
Fecha de Ingreso: marzo-2011
Ubicación: Veracruz
Mensajes: 92
Antigüedad: 13 años, 1 mes
Puntos: 3
Respuesta: Multiples selects dinámicos

Muy bueno, por cierto yo tengo que hacer algo parecido, tres selects dependientes pero con datos de tres tablas de mysql.

Como lleno esos datos de javascript con consultas de mysql?

Tengo que abrir un nuevo tema?
  #9 (permalink)  
Antiguo 14/03/2011, 22:53
Avatar de abimaelrc
Colaborador
 
Fecha de Ingreso: mayo-2009
Ubicación: En el planeta de Puerto Rico
Mensajes: 14.734
Antigüedad: 14 años, 10 meses
Puntos: 1517
Respuesta: Multiples selects dinámicos

Bueno según lo que leí
http://stackoverflow.com/questions/1...t-in-this-case
http://stackoverflow.com/questions/1...ascript-object
http://andrewdupont.net/2006/05/18/j...dered-harmful/
http://stackoverflow.com/questions/4...n-and-deletion

Y siguen, indica que no es preocupante. Alguien con más experiencia te podría indicar.
__________________
Verifica antes de preguntar.
Los verdaderos amigos se hieren con la verdad, para no perderlos con la mentira. - Eugenio Maria de Hostos

Última edición por abimaelrc; 14/03/2011 a las 23:02
  #10 (permalink)  
Antiguo 15/03/2011, 01:07
Avatar de zerokilled
Javascripter
 
Fecha de Ingreso: abril-2009
Ubicación: Isla del Encanto, La Borinqueña [+>==]
Mensajes: 8.050
Antigüedad: 15 años
Puntos: 1485
Respuesta: Multiples selects dinámicos

buenas...

de lo que recuerdo haber leido... los arrays -al igual que los objetos- son datos compuesto. lo que significa que la cantidad de memoria que ocupa es variable segun la cantidad y tipos de datos. en el siguiente ejemplo, es de mi opinion que ambos arrays ocupan casi lo mismo. tambien depende mucho del algoritmo interno del interprete al ocupar memoria, o sea el mecanismo del garbage collector.
Código:
foo = new Array(10);
bar = new Array(10000);
en el ejemplo anterior todos los elementos carecen de valor (undefined). undefined es un valor interno fijo -que supongo yo- no ocupa memoria o en el caso de ocupar seguramente seria una cantidad de bits bien reducido.

__________________
la maldad es una virtud humana,
y la espiritualidad es la lucha del hombre contra su maldad.
  #11 (permalink)  
Antiguo 15/03/2011, 09:20
 
Fecha de Ingreso: marzo-2011
Ubicación: Veracruz
Mensajes: 92
Antigüedad: 13 años, 1 mes
Puntos: 3
Respuesta: Multiples selects dinámicos

Cita:
Iniciado por abimaelrc Ver Mensaje
Bueno según lo que leí
[url]http://stackoverflow.com/questions/1460427/does-the-array-size-matter-in-javascript-in-this-case[/url]
[url]http://stackoverflow.com/questions/1247116/which-takes-less-memory-a-javascript-array-or-javascript-object[/url]
[url]http://andrewdupont.net/2006/05/18/javascript-associative-arrays-considered-harmful/[/url]
[url]http://stackoverflow.com/questions/4567002/javascript-array-random-index-insertion-and-deletion[/url]

Y siguen, indica que no es preocupante. Alguien con más experiencia te podría indicar.
Gracias. Voy a seguir los links que me dejaste cuando me disponga a hacer esa parte. Saludos.
  #12 (permalink)  
Antiguo 15/03/2011, 10:12
Avatar de goteen_mx  
Fecha de Ingreso: abril-2005
Ubicación: D.F.
Mensajes: 403
Antigüedad: 19 años
Puntos: 37
Respuesta: Multiples selects dinámicos

Pues si al parecer los arreglos se tratan de diferente forma en js, y apenas lo voy sabiendo :S, creo que tendré que cambiar mis códigos pq manejo muchos arreglos y arreglos de objetos pero segun yo para optimizar los guargaba como elementos e implementaba métodos de búsqueda y ordenamiento por ser índices muy grandes auch.

Gracias y Saludos
__________________
Born to be free.

Etiquetas: multiples, selects
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 22:15.