Retroceder   Foros del Web > Programación para sitios web > AJAX

Respuesta
 
Herramientas Desplegado
Antiguo 06-mar-2008, 14:53   #1 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web

Última edición por GatorV; 10-abr-2008 a las 16:09.
GatorV está desconectado   Responder Citando
Antiguo 07-mar-2008, 14:11   #2 (permalink)
MaBoRaK llegará a ser famoso muy prontoMaBoRaK llegará a ser famoso muy pronto
 
Avatar de MaBoRaK
 
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 1.749
Enviar un mensaje por MSN a MaBoRaK
Re: APORTE: Selects Dependientes con Prototype (AJAX)

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

Mas claro agua, realmente util.

Gracias

connection closed.
__________________
maborak@maborak.com
http://www.maborak.com
Maborak technologies
MaBoRaK está desconectado   Responder Citando
Antiguo 07-mar-2008, 15:04   #3 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web
GatorV está desconectado   Responder Citando
Antiguo 08-mar-2008, 11:55   #4 (permalink)
^engonga^ está en el buen camino
 
Avatar de ^engonga^
 
Fecha de Ingreso: noviembre-2002
Mensajes: 696
Enviar un mensaje por Yahoo  a ^engonga^
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
^engonga^ está desconectado   Responder Citando
Antiguo 08-mar-2008, 12:03   #5 (permalink)
^engonga^ está en el buen camino
 
Avatar de ^engonga^
 
Fecha de Ingreso: noviembre-2002
Mensajes: 696
Enviar un mensaje por Yahoo  a ^engonga^
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
^engonga^ está desconectado   Responder Citando
Antiguo 08-mar-2008, 12:08   #6 (permalink)
^engonga^ está en el buen camino
 
Avatar de ^engonga^
 
Fecha de Ingreso: noviembre-2002
Mensajes: 696
Enviar un mensaje por Yahoo  a ^engonga^
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
^engonga^ está desconectado   Responder Citando
Antiguo 08-mar-2008, 23:52   #7 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web
GatorV está desconectado   Responder Citando
Antiguo 10-mar-2008, 12:11   #8 (permalink)
MaBoRaK llegará a ser famoso muy prontoMaBoRaK llegará a ser famoso muy pronto
 
Avatar de MaBoRaK
 
Fecha de Ingreso: abril-2003
Ubicación: La Paz - Bolivia
Mensajes: 1.749
Enviar un mensaje por MSN a MaBoRaK
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@maborak.com
http://www.maborak.com
Maborak technologies
MaBoRaK está desconectado   Responder Citando
Antiguo 10-abr-2008, 15:11   #9 (permalink)
netoec84 está en el buen camino
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 119
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...
__________________
PortalQuito
ecuadorMusical.com
netoec84 está desconectado   Responder Citando
Antiguo 10-abr-2008, 16:10   #10 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web
GatorV está desconectado   Responder Citando
Antiguo 11-abr-2008, 09:28   #11 (permalink)
netoec84 está en el buen camino
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 119
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?
__________________
PortalQuito
ecuadorMusical.com
netoec84 está desconectado   Responder Citando
Antiguo 11-abr-2008, 10:42   #12 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web
GatorV está desconectado   Responder Citando
Antiguo 16-jun-2008, 14:18   #13 (permalink)
netoec84 está en el buen camino
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 119
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,
__________________
PortalQuito
ecuadorMusical.com
netoec84 está desconectado   Responder Citando
Antiguo 16-jun-2008, 14:43   #14 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web
GatorV está desconectado   Responder Citando
Antiguo 17-jun-2008, 10:18   #15 (permalink)
netoec84 está en el buen camino
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 119
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;
	}
});
__________________
PortalQuito
ecuadorMusical.com
netoec84 está desconectado   Responder Citando
Antiguo 18-jun-2008, 11:34   #16 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
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.
__________________
Blog Web
GatorV está desconectado   Responder Citando
Antiguo 18-jun-2008, 12:07   #17 (permalink)
netoec84 está en el buen camino
 
Fecha de Ingreso: julio-2004
Ubicación: Quito
Mensajes: 119
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
__________________
PortalQuito
ecuadorMusical.com
netoec84 está desconectado   Responder Citando
Antiguo 18-jun-2008, 12:29   #18 (permalink)
Moderador
GatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy prontoGatorV llegará a ser famoso muy pronto
 
Avatar de GatorV
 
Fecha de Ingreso: mayo-2006
Ubicación: Queretaro, Mexico
Mensajes: 11.616
Respuesta: APORTE: Selects Dependientes con Prototype (AJAX)

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

Saludos.
__________________
Blog Web
GatorV está desconectado   Responder Citando