Foros del Web » Programando para Internet » Javascript » Frameworks JS »

APORTE: Selects Dependientes con Prototype (AJAX)

Estas en el tema de APORTE: Selects Dependientes con Prototype (AJAX) en el foro de Frameworks JS en Foros del Web. Hola a todos, Les comparto esta pequeña librería que hice para hacer Selects Dependientes de N niveles con AJAX. Su uso es bastante simple, solo ...
  #1 (permalink)  
Antiguo 06/03/2008, 15:53
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
APORTE: Selects Dependientes con Prototype (AJAX)

Hola a todos,

Les comparto esta pequeña librería que hice para hacer Selects Dependientes de N niveles con AJAX.

Su uso es bastante simple, solo es instanciar el select y pasar quien es el que depende y el URL para cargar los datos, posteriormente en ese URL van a recibir por GET dos datos, controlName (el nombre del control) y selectedId (el valor que selecciono).

La clase espera recibir un arreglo codificado en JSON, donde cada elemento es un objeto, con una propiedad text, y otra value, de esta forma:
Código:
[
    { text: "Texto a mostrar", value: "valor del option" },
    { text: "Texto 2", value: "valor2" },
    ....
    { text: "Texto n", value: "ValorN" }
]
La forma de uso es bastante simple, basta con tener un HTML:
Código HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
	<head>
		<script type="text/javascript" src="prototype.js"></script>
		<script type="text/javascript" src="dependant.js"></script>
		<title>Demo Selects Dependientes</title>
	</head>
	<body>
		<select name="sel1" id="sel1">
			<option value="">- Selecciona -</option>
			<option>Mascotas</option>
			<option>Carros</option>
		</select>
		<select name="sel2" id="sel2"><option></option></select>
		<select name="sel3" id="sel3"><option></option></select>
		<script type="text/javascript">
			Event.observe(window, 'load', function() {
				var sel3 = new HTMLSelect( 'sel3' );
				var sel2 = new dependantSelectAJAX( 'sel2', sel3, 'loader.php' );
				var sel1 = new dependantSelectAJAX( 'sel1', sel2, 'loader.php' );
			});
		</script>
	</body>
</html> 
Creamos los Selects en el evento load de la ventana, y estos objetos automáticamente registran cuando haces un cambio en cada select.

Dejo un pequeño ejemplo de como cargar los datos via PHP, aunque es independiente del lenguaje, el único requisito es que los datos vengan en JSON y con la estructura mencionada mas arriba:
Código PHP:
<?php

$mascotas 
= array( array( "text" => "Gato""value" => "cat" ), array( "text" => "Perro""value" => "dog" ), array( "text" => "Pajaro""value" => "bird" ) );
$carros = array( array( "text" => "BMW""value" => "bmw" ), array( "text" => "Lamborghini""value" => "lamb" ), array( "text" => "Ferrari""value" => "ferr" ) );

$mascotas_acc_cat = array( array( "text" => "Collar" ), array( "text" => "Estambre" ), array( "text" => "Arena" ) );
$mascotas_acc_dog = array( array( "text" => "Collar" ), array( "text" => "Correa" ), array( "text" => "Pelota" ) );
$mascotas_acc_bird = array( array( "text" => "Jaula" ), array( "text" => "Alpiste" ) );
$carros_color_bmw = array( array( "text" => "Azul" ), array( "text" => "Negro" ) );
$carros_color_lamb = array( array( "text" => "Azul" ), array( "text" => "Amarillo" ), array( "text" => "Rojo" ) );
$carros_color_ferr = array( array( "text" => "Rojo" ) );

switch( 
$_GET['controlName'] ) {
case 
'sel1':
    switch( 
$_GET['selectedId'] ) {
    case 
'Mascotas':
        
$result $mascotas;
        break;
    case 
'Carros':
        
$result $carros;
        break;
    }
    break;
case 
'sel2':
    switch( 
$_GET['selectedId'] ) {
    case 
'cat':
        
$result $mascotas_acc_cat;
        break;
    case 
'dog':
        
$result $mascotas_acc_dog;
        break;
    case 
'bird':
        
$result $mascotas_acc_bird;
        break;
    case 
'bmw':
        
$result $carros_color_bmw;
        break;
    case 
'lamb':
        
$result $carros_color_lamb;
        break;
    case 
'ferr':
        
$result $carros_color_ferr;
        break;
    }


echo 
json_encode$result );
exit();
?>
Finalmente la clase dependant.js que es necesaria para funcionar todo, le falta documentación pero leyendo un poco el código podrán ver los métodos que ocupa:
Código:
var DataStore = Class.create(Enumerable, {
	initialize: function( store ) {
		if( store == null ) {
			store = [];
		}
		
		this._store = store;
	},
	
	addItem: function( text, value ) {
		if( value == null ) {
			value = text;
		}
		
		this._store.push( {text: text, value: value } );
	},
	
	removeItem: function( idx ) {
		this._store.splice( idx, 1 );
	},
	
	clear: function() {
		this._store = [];
	},
	
	size: function() {
		return this._store.length;
	},
	
	inspect: function() {
		alert( this._store.inspect() );
	},
	
	_each: function(iterator) {
		for (var i = 0; i < this._store.length; i++) {
			var value = this._store[i];
			
			iterator(value);
		}
	}
});

var HTMLSelect = Class.create({
	initialize: function( element ) {
		this.element = $(element);
		this.element.onchange = this.onChange.bindAsEventListener(this);
		this.element.onclick = this.onClick.bindAsEventListener(this);
		this.element.onfocus = this.onFocus.bindAsEventListener(this);
		
		var store = new DataStore();
		var opts = this.element.options;
		for(var i = 0; i < opts.length; i++ ) {
			var el = opts[i];
			store.addItem( el.text, el.value );
		}
		
		this.store = store;
	},
	
	setStore: function( ds ) {
		this.store = ds;
	},
	
	reload: function() {
		this.empty();
		
		var num = 0;
		this.store.each(function(item) {
			this.addOption(item.text, item.value);
			num++;
		}.bind(this));
	},
	
	onChange: function(e) {},
	onClick: function(e) {},
	onFocus: function(e) {},
	onEmpty: function() { return true; },
	
	selectIndex: function( index ) {
		this.element.selectedIndex = index;
	},
	
	selectOption: function( option ) {
		var size = this.element.length;
		var found = false;
		for(i = 0; i < size; i++) {
			var el = this.element.options[i].text;
			if( el == option ) {
				found = true;
				break;
			}
		}
		
		if( found ) {
			this.selectIndex(i);
			this.onChange();
		}
	},
	
	countOptions: function() {
		return this.element.length;
	},
	
	getSelectedOption: function() {
		var op = this.element.options[this.element.selectedIndex];
		return { value: op.value, text: op.text };
	},
	
	getValue: function() {
		var op = this.element.options[this.element.selectedIndex];
		var ret = "";
		
		ret = op.value;
		if( ret == "" ) {
			ret = op.text;
		}
		
		return ret;
	},
	
	empty: function() {
		if( this.onEmpty() ) {
			this._empty();
		}
	},
	
	addOption: function( text, value ) {
		if( value == null ) {
			value = text;
		}
		
		var op = new Option( text, value );
		var idx = this.element.length;
		this.element.options[idx] = op;
		
		return idx;
	},
	
	deleteOption: function( index ) {
		if( this.element.length > 0 && index > 0 ) {
			this.element.options[index] = null;
		}
	},
	
	selectAllOptions: function() {
		var size = this.element.length - 1;
		for(i = size; i>=0; i--) {
			this.element.options[i].selected = true;
		}
	},
	
	getSelectedOptions: function() {
		var texts = [];
		var size = this.element.length - 1;
		for(i = size; i>=0; i--) {
			if( this.element.options[i].selected === true ) {
				texts.push(this.element.options[i].text);
			}
		}
		
		return texts;
	},
	
	_empty: function() {
		this.element.options.length = 0;
	}
});

var dependantSelectAJAX = Class.create(HTMLSelect, {
	initialize: function( $super, select, child, url ) {
		$super( select );
		if( typeof( select ) == "string" ) {
			this.name = select;
		} else {
			this.name = select.name;
		}
		
		this.child = child;
		this.url = url;
	},
	
	onChange: function(e) {
		this.child.empty();
		var value = this.getValue();
		
		if( value != "" ) {
			var request = new Ajax.Request( this.url, {
				method: 'get',
				parameters: {controlName: this.name, selectedId: value},
				onSuccess: function( transport ) {
					var store = transport.responseText.evalJSON(true);
					if( typeof store.error != "undefined" ) {
						alert( store.error );
					} else {
						this.child.setStore(new DataStore(store));
						this.child.reload();
						var size = this.child.countOptions();
						if( size == 1 ) {
							this.child.onChange(); 
						}
					}
				}.bind(this),
				onFalure: function(t) {
					alert( "Error in request" );
				}
			});
		}
	},
	
	onEmpty: function() {
		this.child.empty();
		
		return true;
	}
});
Requiere de la libreria Prototype versión 1.6 minimo debido a la nueva forma de declarar clases.

Saludos y espero les sea de utilidad.

Última edición por GatorV; 10/04/2008 a las 16:09
  #2 (permalink)  
Antiguo 07/03/2008, 15:11
Avatar de MaBoRaK  
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 2.003
Antigüedad: 21 años
Puntos: 35
Re: APORTE: Selects Dependientes con Prototype (AJAX)

loading.............

Mas claro agua, realmente util.

Gracias

connection closed.
__________________

Maborak Technologies
  #3 (permalink)  
Antiguo 07/03/2008, 16:04
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: APORTE: Selects Dependientes con Prototype (AJAX)

Gracias, aunque luego subiré una versión con documentación, es importante documentar todo el api disponible.

Saludos.
  #4 (permalink)  
Antiguo 08/03/2008, 12:55
Avatar de engonga
Usuario no validado
 
Fecha de Ingreso: marzo-2002
Ubicación: Buenos Aires
Mensajes: 1.300
Antigüedad: 22 años, 1 mes
Puntos: 8
Re: APORTE: Selects Dependientes con Prototype (AJAX)

pues a mi no me funciona

si ejecuto el loader.php solo me escupe null aunque le pase las variables


y si ejecuto el inex.html con el form me da un error de javascript

"
se esperava un identificador, una cadena o un numero

linea 137
"

otro error

"Linea 30
Error 'HTML select' no esta definido
"

En quanto me funcione traducire el loader.php a asp
  #5 (permalink)  
Antiguo 08/03/2008, 13:03
Avatar de engonga
Usuario no validado
 
Fecha de Ingreso: marzo-2002
Ubicación: Buenos Aires
Mensajes: 1.300
Antigüedad: 22 años, 1 mes
Puntos: 8
Re: APORTE: Selects Dependientes con Prototype (AJAX)

PERDON!!!


en internet explorer me da los errores y en firefox funciona a la primera

versiones:
internet explorer 6.0
firefox = 2.0
  #6 (permalink)  
Antiguo 08/03/2008, 13:08
Avatar de engonga
Usuario no validado
 
Fecha de Ingreso: marzo-2002
Ubicación: Buenos Aires
Mensajes: 1.300
Antigüedad: 22 años, 1 mes
Puntos: 8
Re: APORTE: Selects Dependientes con Prototype (AJAX)

este aporte esta bien (todo y que solo funciona en Firefox)

pero para aplicarlo como autocompletar campos (imputs) que no sean selects?

como este script

http://www.guwahatiwebhosting.com/gu...x/dynamiclist/

gracias
  #7 (permalink)  
Antiguo 09/03/2008, 00:52
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: APORTE: Selects Dependientes con Prototype (AJAX)

Tenia una coma de mas, jeje, asi que ya he arreglado el codigo y funciona tanto en IE, como en FF y Opera, no he podido probar en Safari porque no tengo acceso, pero no deberia de dar problema.

Saludos.
  #8 (permalink)  
Antiguo 10/03/2008, 12:11
Avatar de MaBoRaK  
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 2.003
Antigüedad: 21 años
Puntos: 35
Re: APORTE: Selects Dependientes con Prototype (AJAX)

loading...........

se esperaba un identificador, una cadena o un numero <--- es un error en f...ing IE que solo un experto podría dectectar :p felicidades GatorV y en Safari ... mmm, paso a probarlo.

connection closed.
__________________

Maborak Technologies
  #9 (permalink)  
Antiguo 10/04/2008, 15:11
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 123
Antigüedad: 19 años, 9 meses
Puntos: 0
Pregunta Re: APORTE: Selects Dependientes con Prototype (AJAX)

Muy bueno.... pero una pregunta... como funcionaria si ya deseo establecer una opcion seleccionada por defecto? Cual seria la forma de hacerlo funcionar?

Saludos...
__________________
Guia Telefonica
ecuadorMusical.com
  #10 (permalink)  
Antiguo 10/04/2008, 16:10
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: APORTE: Selects Dependientes con Prototype (AJAX)

Cierto, he agregado la opción para preseleccionar una opción, lo haces así:
Código:
var select = new dependantSelectAJAX( 'id_select', select_que_depende, url );
select.selectOption( "La opcion a pre-elegir" );
// o
select.selectIndex( index_a_elegir );
Saludos.
  #11 (permalink)  
Antiguo 11/04/2008, 09:28
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 123
Antigüedad: 19 años, 9 meses
Puntos: 0
Re: APORTE: Selects Dependientes con Prototype (AJAX)

Genial... lo voy a probar.......

ahora otra pregunta, resulta que en las listas desplegables no siempre existen todos los niveles, por ejemplo:


Código:
- Nivel 1
  - Nivel 1.1
    -  Nivel 1.1.1
    -  Nivel 1.1.2
  - Nivel 1.2
- Nivel 2
  - Nivel 2.1
  - Nivel 2.2
- Nivel 3
Entonces en ese punto, los como podria hacerse para que unicamente aprezcan los combos en el caso que exista opciones dispobles para ese nivel? Y mejor aun almacenar ese resultado en un campo oculo <input type="hidden"> pues al no ser siempre el ultimo nivel el mismo select seria mucho mas sencillo tomar el valor del campo oculto.... es posible?
__________________
Guia Telefonica
ecuadorMusical.com
  #12 (permalink)  
Antiguo 11/04/2008, 10:42
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Re: APORTE: Selects Dependientes con Prototype (AJAX)

Yo creo si se podría hacer fácilmente, fíjate en esta parte del código (del método onChange):
Código:
if( size == 1 ) {
	this.child.onChange(); 
}
Puedes regresar un parámetro extra en el json que indique ya no hay más datos y que debe de guardarlo en un input. Ocultar o mostrar capas, etc.

Saludos.
  #13 (permalink)  
Antiguo 16/06/2008, 14:18
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 123
Antigüedad: 19 años, 9 meses
Puntos: 0
Pregunta Respuesta: Re: APORTE: Selects Dependientes con Prototype (AJAX)

Cita:
Iniciado por GatorV Ver Mensaje
Cierto, he agregado la opción para preseleccionar una opción, lo haces así:
Código:
var select = new dependantSelectAJAX( 'id_select', select_que_depende, url );
select.selectOption( "La opcion a pre-elegir" );
// o
select.selectIndex( index_a_elegir );
Saludos.
Hola Gastor, sabes ahora estaba chequeando y me encontre con un error (o mal uso, no lo se). Sucede que hago algo asi:

Código:
<script type="text/javascript">
			Event.observe(window, 'load', function() {
				var mnuFecha = new HTMLSelect('mnuFecha');
	var mnuEtapa = new dependantSelectAJAX('mnuEtapa', mnuFecha, 'index.php?module=Torneos&type=ajax&func=getChildrens' );
	mnuEtapa.selectOption( "Primera" );
	var mnuTorneo= new dependantSelectAJAX('mnuTorneo', mnuEtapa, 'index.php?module=Torneos&type=ajax&func=getChildrens' );
	mnuTorneo.selectOption( "Copa Pilsener I" );
});
		</script>
Y unicamente me selecciona la primera lista, la segunda lista no selecciona la opcion a pesar que si existe.

Se trata de un mal uso? o algun error? que puede ser?

Saludos,
__________________
Guia Telefonica
ecuadorMusical.com
  #14 (permalink)  
Antiguo 16/06/2008, 14:43
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Hola netoec84,

Primero te pido si escribes correctamente mi nombre, segundo, para pre-seleccionar dos opciones, yo extendería la clase dependantSelectAJAX para que aceptara un tercer parámetro al cargar los datos, ya que si usas directamente selectOption va a tratar de seleccionar el valor cuando no tiene datos, es por eso que debes esperar al evento onreadystatechange de AJAX para preseleccionar los datos.

Saludos.
  #15 (permalink)  
Antiguo 17/06/2008, 10:18
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 123
Antigüedad: 19 años, 9 meses
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Cita:
Iniciado por GatorV Ver Mensaje
Hola netoec84,

Primero te pido si escribes correctamente mi nombre, segundo, para pre-seleccionar dos opciones, yo extendería la clase dependantSelectAJAX para que aceptara un tercer parámetro al cargar los datos, ya que si usas directamente selectOption va a tratar de seleccionar el valor cuando no tiene datos, es por eso que debes esperar al evento onreadystatechange de AJAX para preseleccionar los datos.

Saludos.
Mil disculpas GatorV, voy a prestar mas atención al momento de escribir. Ahora te cuento que no hice precisamente lo que me comentas pero la clase quedo algo asi: incluyendo los cambios anteriores... lo que no se si es da algun problema al no seguir tus sugerencias... lo dejo para ver si le puedes dar una mirada y mas que todo para la gente si le sirve

Código:
var DataStore = Class.create(Enumerable, {
	initialize: function( store ) {
		if( store == null ) {
			store = [];
		}
		
		this._store = store;
	},
	
	addItem: function( text, value ) {
		if( value == null ) {
			value = text;
		}
		
		this._store.push( {text: text, value: value } );
	},
	
	removeItem: function( idx ) {
		this._store.splice( idx, 1 );
	},
	
	clear: function() {
		this._store = [];
	},
	
	size: function() {
		return this._store.length;
	},
	
	inspect: function() {
		alert( this._store.inspect() );
	},
	
	_each: function(iterator) {
		for (var i = 0; i < this._store.length; i++) {
			var value = this._store[i];
			
			iterator(value);
		}
	}
});

var HTMLSelect = Class.create({
	initialize: function( element ) {
		this.element = $(element);
		this.element.onchange = this.onChange.bindAsEventListener(this);
		this.element.onclick = this.onClick.bindAsEventListener(this);
		this.element.onfocus = this.onFocus.bindAsEventListener(this);
		
		var store = new DataStore();
		var opts = this.element.options;
		for(var i = 0; i < opts.length; i++ ) {
			var el = opts[i];
			store.addItem( el.text, el.value );
		}
		
		this.store = store;
	},
	
	setStore: function( ds ) {
		this.store = ds;
	},
	
	reload: function() {
		this.empty();
		
		var num = 0;
		this.store.each(function(item) {
			this.addOption(item.text, item.value);
			num++;
		}.bind(this));
	},
	
	onChange: function(e) {},
	onClick: function(e) {},
	onFocus: function(e) {},
	onEmpty: function() { 
		this.element.style.display = 'none';
		return true; 
	},
	
	selectIndex: function( index ) {
		this.element.selectedIndex = index;
	},
	
	selectOption: function( option ) {
		var size = this.element.length;
		var found = false;
		for(i = 0; i < size; i++) {
			var el = this.element.options[i].text;
			if( el == option ) {
				found = true;
				break;
			}
		}
		
		if( found ) {
			this.selectIndex(i);
			this.onChange();
		}
	},
	
	countOptions: function() {
		return this.element.length;
	},
	
	getSelectedOption: function() {
		var op = this.element.options[this.element.selectedIndex];
		return { value: op.value, text: op.text };
	},
	
	getValue: function() {
		var op = this.element.options[this.element.selectedIndex];
		var ret = "";
		
		ret = op.value;
		if( ret == "" ) {
			ret = op.text;
		}
		
		return ret;
	},
	
	empty: function() {
		if( this.onEmpty() ) {
			this._empty();
		}
	},
	
	addOption: function( text, value ) {
		if( value == null ) {
			value = text;
		}
		
		var op = new Option( text, value );
		var idx = this.element.length;
		this.element.options[idx] = op;
		
		return idx;
	},
	
	deleteOption: function( index ) {
		if( this.element.length > 0 && index > 0 ) {
			this.element.options[index] = null;
		}
	},
	
	selectAllOptions: function() {
		var size = this.element.length - 1;
		for(i = size; i>=0; i--) {
			this.element.options[i].selected = true;
		}
	},
	
	getSelectedOptions: function() {
		var texts = [];
		var size = this.element.length - 1;
		for(i = size; i>=0; i--) {
			if( this.element.options[i].selected === true ) {
				texts.push(this.element.options[i].text);
			}
		}
		
		return texts;
	},
	
	_empty: function() {
		this.element.style.display = 'none';
		this.element.options.length = 0;
	}
});

var dependantSelectAJAX = Class.create(HTMLSelect, {
	initialize: function( $super, select, child, url, selected) {
		$super( select );
		if( typeof( select ) == "string" ) {
			this.name = select;
		} else {
			this.name = select.name;
		}
		
		this.child = child;
		this.url = url;
		this.selected = selected;
	},
	
	onChange: function(e) {
		this.child.empty();
		var value = this.getValue();
		
		if( value != "" ) {
			var request = new Ajax.Request( this.url, {
				method: 'get',
				parameters: {controlName: this.name, selectedId: value},
				onSuccess: function( transport ) {
					var store = transport.responseText.evalJSON(true);
					if( typeof store.error != "undefined" ) {
						alert( store.error );
					} else {
						this.child.setStore(new DataStore(store));
						this.child.reload();
						var size = this.child.countOptions();
						if( size == 1 ) {
							//this.child.onChange(); 
							this.child.element.style.display = 'inline';
						}
						else if (size == 0) {
							this.child.element.style.display = 'none';
						}
						else
						{
							if (typeof this.child.selected != 'undefined' )
							{
								this.child.selectOption(this.child.selected);								
							}
							this.child.element.style.display = 'inline';
						} 
					}
				}.bind(this),
				
				onFalure: function(t) {
					alert( "Error in request" );
				}
			});
		}
	},

	onEmpty: function() {
		this.child.empty();
		this.child.element.style.display = 'none';
		return true;
	}
});
__________________
Guia Telefonica
ecuadorMusical.com
  #16 (permalink)  
Antiguo 18/06/2008, 11:34
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Hola netoec84,

Me parece bien la forma que lo hiciste, aunque yo creo para eso esta el poder de extender una clase con prototype, para no afectar directo la primera clase , pero de cualquier forma, sirve correctamente.

Saludos.
  #17 (permalink)  
Antiguo 18/06/2008, 12:07
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 123
Antigüedad: 19 años, 9 meses
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

tienes razon solo que no manejo mucho prototype y no se la manera de hacer de extendiendo... ahora talvez otra guia... funciona perfecto para todos los niveles pero no para el ultimo pues utiliza directamente la otra clase... como seria para este caso?

Saludos
__________________
Guia Telefonica
ecuadorMusical.com
  #18 (permalink)  
Antiguo 18/06/2008, 12:29
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Agrégale otra opción a HTMLSelect para pasarle el valor pre-seleccionado por defecto.

Saludos.
  #19 (permalink)  
Antiguo 19/04/2009, 10:50
 
Fecha de Ingreso: abril-2009
Mensajes: 2
Antigüedad: 15 años
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Saludos GatorV, dices que tenias una coma de mas en tu codigo que no permitia ejecutarlo en el IE. Yo tengo un codigo distinto pero que me da el mismo error: "se esperaba un identificador, una cadena o un numero". No he podido ubicar el problema y quisiera tratar de ubicar mi solucion a traves de tu ejemplo.

Mi codigo (por si acaso ayuda) es el siguiente:

Código:
function moreFields() {
			for(i = 0; ; i++) {
				var state = document.getElementById('tr-'+i).style.display;
				if (state == 'none') {
					document.getElementById('tr-'+i).style.display = '';					
					break;
				}
			}
		}
Crees que podrias ayudarme a identificar lo que no permite que funcione en IE?

Gracias de antemano por tu tiempo y ayuda.

Saludos!
  #20 (permalink)  
Antiguo 28/04/2009, 11:11
 
Fecha de Ingreso: agosto-2002
Mensajes: 32
Antigüedad: 21 años, 8 meses
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

y como seria para hacerlo funcionar en coldfusion
  #21 (permalink)  
Antiguo 28/04/2009, 15:02
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Es el mismo proceso solo asegurate que tu pagina en Coldfusion te regrese el formato adecuado en JSON y funciona.

Saludos.
  #22 (permalink)  
Antiguo 09/07/2009, 16:05
 
Fecha de Ingreso: noviembre-2008
Mensajes: 19
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Hola
GatorV

Soy principiante en AJAX y el ejemplo me parece excelente, estuve buscando mucho sobre como mostrar 3 select dependientes con AJAX. En el ejemplo se crean 3 arrays de manera predeterminada, pero como seria para crear los select dependientes desde una BD mysql, usando PHP?. Expongo mi caso:
Tengo un select 1 con la lista de "departamentos" cargados y al seleccionar alguno debe activar select 2 y listar las "provincias" del departamento, y despues, una vez elegido una "provincia" listar en el select3 los "distritos".
Los elementos estan en una tabla mysql y siempre necesito pasarle un parametro como el codigo para mostrar cada select. Tengo 3 archivos PHP independientes y funciona, pero como implementarlo en AJAX.

Gracias por tu ayuda y paciencia con los novatos como YO.
  #23 (permalink)  
Antiguo 09/07/2009, 21:08
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Si te fijas el ejemplo viene para 3 selects aunque es 100% configurable, tu lo puedes usar para 1, 2, 3, n selects.

Lo que tienes que hacer es asegurarte de regresar la salida correcta, el script te envia dos variables el nombre del control y el valor
  #24 (permalink)  
Antiguo 13/07/2009, 15:43
 
Fecha de Ingreso: noviembre-2008
Mensajes: 19
Antigüedad: 15 años, 5 meses
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Hola
GatorV

Nuevamente mi pregunta como novato, en el ejemplo se muestra que el archivo "loader.php" define un array para cada select en el supuesto de que se conocen los valores de forma predefinida, pero como seria, si los elementos del select 2 esta en funcion del select 1, osea a veces podran contener 5 elementos, otras veces 10, otras 20 y asi sucesivamente. Depende de lo que elija en el select 1.
De igual forma el select 3 tambien depende de lo que elija en el select 2 y ambos cambian en tiempo de ejecucion. Los elementos del select 2 y 3 no se saben a priori. En mi caso debo leerlos desde una tabla siempre con Select y una clausula where...Gracias por tu respuesta y paciencia.
  #25 (permalink)  
Antiguo 13/07/2009, 19:43
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 17 años, 11 meses
Puntos: 2135
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Exacto eso es por conveniencia lo esta haciendo en el mismo archivo pero tu puedes cambiar ese script y que sean 3 scripts separados, luego compruebas el valor de selectedId que viene por GET, y en base a eso regresas los valores que necesites.

Saludos.
  #26 (permalink)  
Antiguo 02/06/2010, 01:42
 
Fecha de Ingreso: mayo-2010
Mensajes: 17
Antigüedad: 13 años, 11 meses
Puntos: 0
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Hola.

Siento revivir el hilo pero no he encontrado mas informacion sobre esto.

¿Sabes si hay forma de cargar las listas desde una base de datos? Con tu ejemplo me refiero.

Necesito dos listas, seleccionar una y que en la otra se carguen los valores. Luego necesito poder enviarlos a una pagina web para que se los mande a otro archivo php que se ejecutara luego. Aunque eso igual es mas facil escribirlos en un fichero y leerlos cuando me interese desde el otro fichero php...


Gracias y un saludo
  #27 (permalink)  
Antiguo 01/08/2011, 09:58
 
Fecha de Ingreso: junio-2010
Mensajes: 4
Antigüedad: 13 años, 10 meses
Puntos: 2
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

Me gustaria que funcionara con Base de Datos hare el intento integrarlo...

Luego les cuento!
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

SíEste tema le ha gustado a 2 personas




La zona horaria es GMT -6. Ahora son las 01:41.