Foros del Web » Programando para Internet » Javascript »

Utilizar las teclas direccionales para seleccionar un item

Estas en el tema de Utilizar las teclas direccionales para seleccionar un item en el foro de Javascript en Foros del Web. Buenas noches: Este es el panorama. Ojalá puedan ayudarme porque en verdad esto si ya escapa de mis conocimientos. Tengo un clásico código en ajax ...

  #1 (permalink)  
Antiguo 22/03/2012, 23:04
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Utilizar las teclas direccionales para seleccionar un item

Buenas noches:
Este es el panorama. Ojalá puedan ayudarme porque en verdad esto si ya escapa de mis conocimientos.

Tengo un clásico código en ajax de esos que muestran los resultados en un div según se va ingresando el dato a buscar. Por ejemplo, ingreso la letra A y aparecen todos los apellidos que empiezan con A, y si luego digito L pues filtra y me muestra los apellidos que empiezan con AL.

El código funciona bien. Para seleccionar el dato que se busca se usa el mouse. Sin embargo ahora me piden que se utilicen las teclas direccionales (las flechitas). Lo que se puede hacer en este momento es utilizar y navegar en la lista con la tecla TAB y seleccionar con ENTER.

¿Cómo puedo hacer esto?

Por si las dudas posteo el código que utilizo

Cita:
function nuevoAjax()
{
var xmlhttp=false;

try
{xmlhttp = new XMLHTTPRequest();}
catch(err1)
{
try
{xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");}
catch (err2)
{
try
{xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");}
catch (err3)
{xmlhttp = false;}
}
}
return xmlhttp;
}



var xmlHttp

function showHint(str,n)
{
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
document.getElementById("txtHint").style.visibilit y="hidden";
return;
}

xmlHttp=GetXmlHttpObject()
if (xmlHttp==null)
{
alert ("Su navegador no soporta AJAX");
return;
}

var url="consultar.asp";


url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}

function stateChanged()
{
if (xmlHttp.readyState==4)
{
document.getElementById("txtHint").innerHTML=xmlHt tp.responseText;
if(xmlHttp.responseText=="ND")
{document.getElementById("txtHint").style.visibili ty="hidden";}
else
{document.getElementById("txtHint").style.visibili ty="visible";}
}
}

function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}
catch (e)
{xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}
}
return xmlHttp;
}

function selectItem(ruc,empresa,id)
{
document.getElementById("txt1").value=ruc;
document.getElementById("txtHint").style.visibilit y="hidden";
document.getElementById("txt1").value="";

document.registros.ruc.value=ruc;

icono(1);
}
El código de la página ASP me parece que no tiene nada que ver con mi consulta, pues simplemente realiza la consulta con la base de datos.

Este es el código que utilizo para invocar el Ajax

Cita:
<input type="text" ID="txt1" onKeyUp="showHint(this.value,1);">
<div id="txtHint" align="left"></div>
Reitero, ojalá puedan ayudarme porque en verdad esto si ya escapa de mis conocimientos.

Muchas muchas gracias por el apoyo.
Un saludo desde Lima, Perú
  #2 (permalink)  
Antiguo 23/03/2012, 07:05
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

has de usar el objeto event y esta es la representación ascii
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #3 (permalink)  
Antiguo 23/03/2012, 07:43
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Gracias por la respuesta IsaBelM pero el asunto es ¿cómo?. Ya había intuido que intervendría el objeto event pero no se como integrarlo al código que tengo para que se direccione al div en que se muestra el resultado de la consulta. Porque ya estoy usando el evento onKeyUp para capturar el dato a buscar y por ahí traté de agregar algo al código ajax para que "si es flecha para arriba o flecha para abajo" se mueva en el div, pero no lo he logrado hasta ahora. ¿Podrías ayudarme por favor?

Muchas gracias
  #4 (permalink)  
Antiguo 23/03/2012, 08:52
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

suerte a que programas en asp y es un lenguaje al que tengo especial cariño, haré una excepción y te daré el código
Cita:
<!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"lang="es" xml:lang="es">
<head>
<meta http-equiv="Content-Type" content="application/xhtml; charset=utf-8" />
<title></title>
<style type="text/css">
#contenedor div.seleccionado {font-weight:bold; background:#F0F0F0; color:#FF6600;}
#contenedor div.deseleccionado {background:#FFFFFF; color:#000000;}
#contenedor div{font:11px verdana; color:#000000; cursor:pointer; text-align:left; padding:2px 5px;}

.capa {
background: #FFFFFF;
border:1px solid rgb(120,120,120);
width: 144px;
*width: 146px;
text-align: left;
position: absolute;
top: 30px;
*top:38px;
left: 117px;
*left: 119px;
}
</style>
<script type="text/javascript">
var SelUsuario = {

Evento: function (elemento,nomevento,funcion) {
if (elemento.attachEvent)
{
var fnc=function(){
funcion.call(elemento,window.event);
}
elemento.attachEvent('on'+nomevento,fnc);
return true;
}
else
if (elemento.addEventListener)
{
elemento.addEventListener(nomevento,funcion,false) ;
return true;
}
else
return false;
},



init: function(){
var elem1 = document.getElementById("txt");
var elem2 = document.getElementById("contenedor");
SelUsuario.Evento(elem1, 'keyup', SelUsuario.Empieza);
SelUsuario.Evento(elem2, 'mouseover', SelUsuario.Seleccionar);
SelUsuario.Evento(elem1, 'keydown', SelUsuario.Pegar2);
SelUsuario.Evento(window, 'click', SelUsuario.Cerrar);
},




creaAjax: function (){
ajax = new XMLHttpRequest();
}
},



Empieza: function (evt) {
var str = document.getElementById(this.id).value;
var obj = document.getElementById("contenedor");
var ref = obj.getElementsByTagName('DIV');
var keyCode = (evt) ? evt.keyCode : evt.charCode;

if (keyCode == 40) {
//alert("flecha abajo")
SelUsuario.BajaOpt ()
} else if (keyCode == 38) {
//alert("flecha arriba")
SelUsuario.SubeOpt ()

} else if (keyCode == 13) {

for (var i = 0; i <= ref.length-1; i++) {
if (ref[i].className == "seleccionado") {

document.getElementById("txt").value = ref[i].id;
if (obj.style.display == "block"); obj.style.display= "none";
break;
}

}

try{
ev.preventDefault();
}catch(e){
ev.returnValue = false;
}

} else {

if (str.length < 2) {
if (obj.style.display == "none") obj.style.display= "none";
lse obj.style.display= "none";
return;
}
ajax = SelUsuario.creaAjax();
if (ajax==null) {
alert ("Tu navegador no soporta Ajax");
return;
}
var url="selecusuarios.asp?q="+escape(str);
ajax.open("GET",url,true);
ajax.onreadystatechange = SelUsuario.Despliega;
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(null);
return;
}
},


Despliega: function () {
var obj = document.getElementById("contenedor");

if (ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3) {
obj.innerHTML = "<p align='center'><img src='precarga.gif' border='0px' widht='15px' height='15px'/></p>";
obj.style.display= "block";
}

else if (ajax.readyState==4) {
if (ajax.status==200) {
obj.innerHTML = unescape(ajax.responseText);
}

if (obj.style.display == "none") obj.style.display= "block";
}
},



Seleccionar: function () {
var ref = document.getElementById(this.id).getElementsByTagN ame('DIV');
for (var i = 0; i < ref.length; i++) {

SelUsuario.Evento(ref[i], 'click', function() {
SelUsuario.Pegar(this.id);
})


SelUsuario.Evento(ref[i], 'mouseover', function() {
SelUsuario.Marcar(this.id);
})
}
},



Pegar: function (valor) {
var obj = document.getElementById("contenedor")
document.getElementById("txt").value = valor;
if (obj.style.display == "block"); obj.style.display= "none";
},


Pegar2: function (evt) {
var obj = document.getElementById("contenedor")
var ref = obj.getElementsByTagName('DIV');
var keyCode = (evt) ? evt.keyCode : evt.charCode;

// enter 13 tab 9
if ((keyCode == 13) || (keyCode == 9)) {

for (var i = 0; i <= ref.length-1; i++) {
if (ref[i].className == "seleccionado") {

document.getElementById("txt").value = ref[i].id;
if (obj.style.display == "block"); obj.style.display= "none";
break;
}
}

if (keyCode == 13) {
try{
ev.preventDefault();
}catch(e){
ev.returnValue = false;
}
}

}
},


BajaOpt: function() {
var ref = document.getElementById("contenedor").getElementsB yTagName('DIV');
for (var i = 0; i <= ref.length-1; i++) {
if (ref[i].className == "seleccionado") {
ref[i].className = "deseleccionado";
if (i < ref.length-1){
i++;
}else{
i = 0;
}
ref[i].className = "seleccionado"
}
}
},


SubeOpt: function() {
var ref = document.getElementById("contenedor").getElementsB yTagName('DIV');
for (var i = 0; i <= ref.length-1; i++) {
if (ref[i].className == "seleccionado") {
ref[i].className = "deseleccionado";
if (i < ref.length && i > 0){
i--;
}else{
i = ref.length-1;
}
ref[i].className = "seleccionado"
}
}
},


Marcar: function (id) {
var selecionado = document.getElementById(id);
var ref = document.getElementById("contenedor").getElementsB yTagName('DIV');
for (var i = 0; i <= ref.length-1; i++) {
if (ref[i].id != id) {
ref[i].className = "deseleccionado";
selecionado.className = "seleccionado";
}
}
},


Cerrar: function () {
var obj = document.getElementById("contenedor")
if (obj.style.display == "block"); obj.style.display= "none";

}
}


SelUsuario.Evento(window, 'load', SelUsuario.init);
</script>
</head>
<body>

<form>
Nombre Usuario: <input type="text" name="txt" id="txt" value="" autocomplete="off" tabindex="1" />
<div id="contenedor" class="capa" style="display:none;"></div>
</form>

</body>
</html>
selecusuarios.asp
Cita:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<% Option Explicit %>
<% Response.Buffer=True %>
<% On Error Resume Next %>
<%Response.charset="utf-8"%>
<%
Response.addHeader "pragma", "no-cache"
Response.CacheControl = "Private"
Response.Expires = -1000 'Hace que el explorador no cree cache de esta pagina
%>
<%
Dim SQL, rs, oConn, registros, i
Dim usuario
Dim nombre
nombre = 0
usuario = CStr(Request.QueryString("q"))


IF Len(usuario) >= 2 then
'conexión a bd
SQL="Select nombre FROM Usuarios WHERE nombre LIKE '"&usuario&"%' ORDER BY nombre asc"
set rs = oConn.Execute(SQL)
If not rs.eof then
registros = rs.getrows()
Else
Response.Write "<p class=""deseleccionado""><strong>Sin resultados</strong></p>"
Response.End ()
End If
rs.Close
set rs = nothing
oConn.Close
set oConn = nothing
END IF

For i = 0 to Ubound(registros,2)
If i = 0 then
Response.Write "<div id="""& registros(nombre,i) &""" class=""seleccionado"">"& ResaltarSubStr(registros(nombre,i)) & "</div>"
Else
Response.Write "<div id="""& registros(nombre,i) &""" class="""">" & ResaltarSubStr(registros(nombre,i)) & "</div>"
End If
Next


' ========= funciones ===========
Function ResaltarSubStr(texto)
Dim objRegExp

Set objRegExp= New RegExp
objRegExp.IgnoreCase = True
'objRegExp.Global = True

objRegExp.Pattern = "\b("&usuario&")+(\w)"
texto = objRegExp.Replace(texto, "<strong>$1</strong>$2")

Set objRegExp = Nothing

ResaltarSubStr = texto

End Function
' ====================
%>
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #5 (permalink)  
Antiguo 23/03/2012, 08:58
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Muchas gracias (en buena hora que soy fan de ASP jejeje). Voy a revisar el código primero para entenderlo y luego para adaptarlo a mi código y te comento como me fue.

Mil gracias de verdad.
  #6 (permalink)  
Antiguo 23/03/2012, 09:20
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

No quiero pecar de cargoso o abusivo pero simplemente agregué a tu código la siguiente línea (para la conexión con la base de datos que tengo)

Cita:
Set oConn = Server.CreateObject("ADODB.Recordset")
oConn.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\inetpub\proyecto\basededatos.mdb"
antes del primer IF, luego de la declaración de variables, y claro, la conecte con una tabla que tengo con varios datos, que también tiene un campo llamado NOMBRE. Solamente cambie el hombre de la tabla en la línea de la variable SQL (luego del from claro) pero no sucede nada en absoluto.

Tengo las 2 páginas en la misma carpeta y la 2da con el nombre que has publicado. ¿Que podría estar pasando?
  #7 (permalink)  
Antiguo 23/03/2012, 09:27
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

probablemente lo que ocurre es que se han de insertar dos carecteres en el control
Cita:
// condicional en el js
if (str.length < 2) {

// condicional en el asp
IF Len(usuario) >= 2 then
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #8 (permalink)  
Antiguo 23/03/2012, 10:48
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Pues nada, inclusive probé ingresar los carácteres iniciales tal cual están escritos en la base de datos (la primera en mayúsculas). En tú código se había perdido una letra "e" de "else" justo en la condicional que me indicas (si te fijas aparece lse obj.style en vez de else obj.style)

Sigo sin poder hacerlo andar y no encuentro más fallas en el código. No he modificado nada excepto lo que te he indicado. Disculpa tanta molestia pero estoy empezando hace poco con esto de ASP y javascript que me pierdo a veces en tanto código.
  #9 (permalink)  
Antiguo 23/03/2012, 11:04
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Una consulta .... en tu código js pones

Cita:
creaAjax: function (){
ajax = new XMLHttpRequest();
}
},
¿no esta sobrando o faltando una }?

Otra.... al final de ese código pones

Cita:
SelUsuario.Evento(window, 'load', SelUsuario.init);
pero al inicio del mismo no hay ninguna referencia para el caso de "load", sólo para keyup, mouseover, keydown y click.... ¿es así el código?

Sorry por mis limitados conocimientos en Javascript pero en el input final, el del formulario ¿cómo invocas a las funciones si no hay evento alguno?

Última edición por freesoftwarrior; 23/03/2012 a las 14:27
  #10 (permalink)  
Antiguo 23/03/2012, 14:47
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

has cambiado la url??
Cita:
var url="selecusuarios.asp?q="+escape(str);
lo de "else" ha sido a limpiarte el código de alertas

con respecto a tu último post todo es correcto. no te preocupes

edito: tienes razón. aquí hay un error. ha de quedar así
Cita:
creaAjax: function (){
ajax = new XMLHttpRequest();
return ajax;
},
edito: busca esta porción de código (está repetido en dos ocasiones) y cambia "ev" por "evt"
Cita:
try{
ev.preventDefault();
}catch(e){
ev.returnValue = false;
}
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}

Última edición por IsaBelM; 23/03/2012 a las 15:02
  #11 (permalink)  
Antiguo 23/03/2012, 16:20
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Mil gracias por tu paciencia.
Respondiendo tu pregunta, no, he cambiado la URL, pues es más, cree un archivo asp con ese mismo nombre.

También encontré en el catch el mismo problema que con el try, de ev en vez de evt.

Yo tengo la costumbre de tabular todo el código que uso y bueno, quedaron así los 2 archivos:

selecusuarios00.asp
Cita:
<!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"lang="es" xml:lang="es">

<head>
<meta http-equiv="Content-Type" content="application/xhtml; charset=utf-8" />
<title></title>

<style type="text/css">
#contenedor div.seleccionado {font-weight:bold; background:#F0F0F0; color:#FF6600;}
#contenedor div.deseleccionado {background:#FFFFFF; color:#000000;}
#contenedor div{font:11px verdana; color:#000000; cursor:pointer; text-align:left; padding:2px 5px;}

.capa
{
background: #FFFFFF;
border:1px solid rgb(120,120,120);
width: 144px;
*width: 146px;
text-align: left;
position: absolute;
top: 30px;
*top:38px;
left: 117px;
*left: 119px;
}
</style>

<script type="text/javascript">
var SelUsuario = {

Evento: function (elemento,nomevento,funcion)
{
if (elemento.attachEvent)
{
var fnc=function()
{
funcion.call(elemento,window.event);
}
elemento.attachEvent('on'+nomevento,fnc);
return true;
}
else
if (elemento.addEventListener)
{
elemento.addEventListener(nomevento,funcion,false) ;
return true;
}
else
return false;
},


init: function()
{
var elem1 = document.getElementById("txt");
var elem2 = document.getElementById("contenedor");

SelUsuario.Evento(elem1, 'keyup', SelUsuario.Empieza);
SelUsuario.Evento(elem2, 'mouseover', SelUsuario.Seleccionar);
SelUsuario.Evento(elem1, 'keydown', SelUsuario.Pegar2);
SelUsuario.Evento(window, 'click', SelUsuario.Cerrar);
SelUsuario.Evento(window, 'load', SelUsuario.Cerrar2);
},


creaAjax: function ()
{
ajax = new XMLHttpRequest();
return ajax;
},


Empieza: function (evt)
{
var str = document.getElementById(this.id).value;
var obj = document.getElementById("contenedor");
var ref = obj.getElementsByTagName('DIV');
var keyCode = (evt) ? evt.keyCode : evt.charCode;

if (keyCode == 40)
{
//alert("flecha abajo")
SelUsuario.BajaOpt ()
}
else if (keyCode == 38)
{
//alert("flecha arriba")
SelUsuario.SubeOpt ()
}
else if (keyCode == 13)
{
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].className == "seleccionado")
{
document.getElementById("txt").value = ref[i].id;
if (obj.style.display == "block"); obj.style.display= "none";
break;
}
}

try
{evt.preventDefault();}
catch(e)
{evt.returnValue = false;}
}
else
{
if (str.length < 2)
{
if (obj.style.display == "none") obj.style.display= "none";
else obj.style.display= "none";
return;
}
ajax = SelUsuario.creaAjax();
if (ajax==null)
{
alert ("Tu navegador no soporta Ajax");
return;
}
var url="selecusuarios.asp?q="+escape(str);
ajax.open("GET",url,true);
ajax.onreadystatechange = SelUsuario.Despliega;
ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
ajax.send(null);
return;
}
},


Despliega: function ()
{
var obj = document.getElementById("contenedor");

if (ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3)
{
obj.innerHTML = "<p align='center'><img src='precarga.gif' border='0px' widht='15px' height='15px'/></p>";
obj.style.display= "block";
}
else if (ajax.readyState==4)
{
if (ajax.status==200)
{
obj.innerHTML = unescape(ajax.responseText);
}
if (obj.style.display == "none") obj.style.display= "block";
}
},


Seleccionar: function ()
{
var ref = document.getElementById(this.id).getElementsByTagN ame('DIV');
for (var i = 0; i < ref.length; i++)
{
SelUsuario.Evento(ref[i], 'click', function()
{
SelUsuario.Pegar(this.id);
})

SelUsuario.Evento(ref[i], 'mouseover', function()
{
SelUsuario.Marcar(this.id);
})
}
},


Pegar: function (valor)
{
var obj = document.getElementById("contenedor")
document.getElementById("txt").value = valor;
if (obj.style.display == "block"); obj.style.display= "none";
},


Pegar2: function (evt)
{
var obj = document.getElementById("contenedor")
var ref = obj.getElementsByTagName('DIV');
var keyCode = (evt) ? evt.keyCode : evt.charCode;

// enter 13 tab 9
if ((keyCode == 13) || (keyCode == 9))
{
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].className == "seleccionado")
{
document.getElementById("txt").value = ref[i].id;
if (obj.style.display == "block"); obj.style.display= "none";
break;
}
}

if (keyCode == 13)
{
try
{
evt.preventDefault();
}
catch(e)
{
evt.returnValue = false;
}
}
}
},


BajaOpt: function()
{
var ref = document.getElementById("contenedor").getElementsB yTagName('DIV');
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].className == "seleccionado")
{
ref[i].className = "deseleccionado";
if (i < ref.length-1)
{
i++;
}
else
{
i = 0;
}
ref[i].className = "seleccionado"
}
}
},


SubeOpt: function()
{
var ref = document.getElementById("contenedor").getElementsB yTagName('DIV');
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].className == "seleccionado")
{
ref[i].className = "deseleccionado";
if (i < ref.length && i > 0)
{
i--;
}
else
{
i = ref.length-1;
}
ref[i].className = "seleccionado"
}
}
},


Marcar: function (id)
{
var selecionado = document.getElementById(id);
var ref = document.getElementById("contenedor").getElementsB yTagName('DIV');
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].id != id)
{
ref[i].className = "deseleccionado";
selecionado.className = "seleccionado";
}
}
},


Cerrar2: function ()
{
alert("hey");
},


Cerrar: function ()
{
var obj = document.getElementById("contenedor")
if (obj.style.display == "block"); obj.style.display= "none";
}

}

SelUsuario.Evento(window, 'load', SelUsuario.init);
</script>

</head>

<body>

<form>
Nombre Usuario: <input type="text" name="txt" id="txt" value="" autocomplete="off" tabindex="1" />
<div id="contenedor" class="capa" style="display:none;"></div>
</form>

</body>
</html>


selecusuarios.asp
Cita:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<% Option Explicit %>
<% Response.Buffer=True %>
<% On Error Resume Next %>
<%Response.charset="utf-8"%>

<%
Response.addHeader "pragma", "no-cache"
Response.CacheControl = "Private"
Response.Expires = -1000 'Hace que el explorador no cree cache de esta pagina
%>

<%
Dim SQL, rs, oConn, registros, i
Dim usuario
Dim nombre
nombre = 0
usuario = CStr(Request.QueryString("q"))

Set oConn = Server.CreateObject("ADODB.Recordset")
oConn.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=c:\inetpub\base de datos\auditek.mdb"

IF Len(usuario) >= 2 then
'conexión a bd
SQL="Select Razon_Social FROM Clientes WHERE Razon_Social LIKE '" & usuario & "%' ORDER BY Razon_Social asc"
set rs = oConn.Execute(SQL)
If not rs.eof then
registros = rs.getrows()
Else
Response.Write "<p class=""deseleccionado""><strong>Sin resultados</strong></p>"
Response.End ()
End If
rs.Close
set rs = nothing
oConn.Close
set oConn = nothing
END IF

For i = 0 to Ubound(registros,2)
If i = 0 then
Response.Write "<div id="""& registros(1,i) &""" class=""seleccionado"">"& ResaltarSubStr(registros(1,i)) & "</div>"
Else
Response.Write "<div id="""& registros(1,i) &""" class="""">" & ResaltarSubStr(registros(1,i)) & "</div>"
End If
Next


' ========= funciones ===========
Function ResaltarSubStr(texto)
Dim objRegExp

Set objRegExp= New RegExp
objRegExp.IgnoreCase = True
'objRegExp.Global = True

objRegExp.Pattern = "\b("&usuario&")+(\w)"
texto = objRegExp.Replace(texto, "<strong>$1</strong>$2")

Set objRegExp = Nothing

ResaltarSubStr = texto

End Function
' ====================
%>
He probado utilizar esta sentencia

Cita:
SQL="Select * From Clientes Where (RUC Like'" + usuario + "%') Order By Razon_Social"
RUC es un campo texto.
También probé eliminar con comentarios (//) la sección de código en el primer archivos ASP para que funcione ni bien ingrese 1 carácter (no un mínimo de 2 como indica) y claro, también deshabilite el equivalente en el otro ASP con las condicionales IF, y nada.

Sigo intrigado que en

Cita:
Nombre Usuario: <input type="text" name="txt" id="txt" value="" autocomplete="off" tabindex="1" />
No exista ningún evento del tipo onChange o onKeyUp que controle el ingreso de datos.

Sigo revisando el código y no le he encontrado nada raro sin embargo simplemente no quiere funcionar.

La forma en que has creado el código Ajax es totalmente nuevo para mi, y por eso estoy teniendo problemas para poder implementarlo en mi código. Esa forma de programas las funciones con nombre: funcition() me parece interesante y nuevo, no había visto algo así antes, pero sin embargo, como te digo, me llama la atención que en el INPUT del formulario no exista ninguna invocación a funciones, pues yo en mi código utilizo el evento onKeyUp.

En realidad estoy en deuda contigo por tu paciencia y preocupación por asistirme. Definitivamente estoy aprendiendo contigo.

Bendiciones.
Un saludo desde el Perú
  #12 (permalink)  
Antiguo 23/03/2012, 17:04
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

prueba ahora
Código Javascript:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml"lang="es" xml:lang="es">
  3. <head>
  4. <meta name="http-equiv" content="Content-type: text/html; charset=utf-8"/>
  5. <style type="text/css">
  6. * {
  7.     padding: 0;
  8.     margin: 0;
  9.     position: relative;
  10. }
  11.  
  12. input.autocomplete {
  13.     width: 200px;
  14.     font: 1em Verdana;
  15. }
  16.  
  17.  
  18.  
  19. #contenedorOpt {
  20.     min-width: 200px;
  21.     width: auto;
  22.     display: none;
  23.     background: rgb(255, 255, 255);
  24.     border: 1px solid rgb(120,120,120);
  25.     text-align: left;
  26.     position: absolute;
  27.     z-index: 100;
  28. }
  29.  
  30.  
  31.  
  32. #contenedorOpt {
  33.     list-style-type: none;
  34. }
  35.  
  36.  
  37.  
  38. #contenedorOpt li {
  39.     font: 1em verdana;
  40.     text-align: left;
  41.     padding: 4px;
  42.     margin: 1px;
  43.     border: 1px solid rgb(255, 255, 255);
  44.     color: rgb(0, 0, 0);
  45.     cursor: default;
  46. }
  47.  
  48.  
  49. #contenedorOpt li.seleccionado {
  50.     border: 1px solid rgb(95, 82, 82);
  51.     border-radius: 5px;
  52.     background: rgb(219, 215, 215);
  53.     color: rgb(9, 8, 8);
  54. }
  55. </style>
  56. <script type="text/javascript">
  57. document.addEventListener('DOMContentLoaded', function() {
  58.    
  59.     new autoCompletado();
  60.  
  61. }, false);
  62.  
  63.  
  64. function autoCompletado() {
  65.  
  66.     this.elTxtBox = null;
  67.     this.ajax = new XMLHttpRequest();
  68.     this.peticiones = 0;
  69.     this.keyUpTimeout = 0;
  70.     this.input = document.querySelectorAll('.autocomplete');
  71.     this.elDiv = document.querySelector('#contenedorOpt');
  72.     this.url = 'SelecUsuarios.php';
  73.     this.opt = null;
  74.     this.optSel = null;
  75.     var _this = this;
  76.  
  77.     Array.prototype.forEach.call(this.input, function(elem) {
  78.  
  79.         elem.addEventListener('keyup', function(event) {_this.autoCompletaPulsacion(event, this)}, false);
  80.         elem.addEventListener('paste', function() {_this.copypasteRaton(this)}, false);
  81.         elem.addEventListener('keydown', function() {_this.rellenarConEnteryTab(event)}, false);
  82.         elem.addEventListener('blur', function() {_this.Cerrar()}, false);
  83.         elem.addEventListener('cut', function() {_this.copypasteRaton(this, this.value)}, false);
  84.     });
  85.  
  86.     this.elDiv.addEventListener('click', function() {_this.rellenarConRaton()}, false);
  87. }
  88.  
  89.  
  90. autoCompletado.prototype.autoCompletaPulsacion = function(ev, elTxtBox) {
  91.  
  92.     this.elTxtBox = elTxtBox;
  93.  
  94.     if (this.elTxtBox.value.length <= 2) {
  95.  
  96.         return;
  97.     }
  98.  
  99.     var keyCode = ev.keyCode, _this = this;
  100.  
  101.     if (keyCode == 40) { // flecha abajo
  102.  
  103.         this.BajaOpt();
  104.  
  105.     } else if (keyCode == 38) { // flecha arriba
  106.  
  107.         this.SubeOpt();
  108.  
  109.     } else if (keyCode == 13) { // enter
  110.  
  111.         ev.preventDefault();
  112.  
  113.     } else {
  114.  
  115.         if (this.keyUpTimeout) clearTimeout(this.keyUpTimeout);
  116.  
  117.         this.keyUpTimeout = setTimeout(function() {
  118.  
  119.             _this.elTxtBox.insertAdjacentHTML('afterend', '<img src="./precarga.gif" />');
  120.  
  121.             _this.ajax.open('POST', _this.url, true);
  122.  
  123.             _this.ajax.onreadystatechange = function() {
  124.  
  125.                 if (_this.ajax.readyState == 4) {
  126.  
  127.                     if (_this.ajax.status == 200) {
  128.  
  129.                         _this.elDiv.innerHTML = _this.ajax.responseText;
  130.  
  131.                         _this.elTxtBox.nextElementSibling.remove();
  132.                         _this.opt = _this.elDiv.getElementsByTagName('li');
  133.  
  134.                         [].forEach.call(_this.opt, function(elem) {
  135.                                
  136.                             elem.addEventListener('mouseover',  function() {
  137.  
  138.                                 _this.Marcar(this);
  139.  
  140.                             }, false);
  141.                         });
  142.  
  143.  
  144.                         if (_this.peticiones++ == 0) {
  145.  
  146.                             var PosElemento = _this.elTxtBox.getBoundingClientRect(),
  147.                             posicionLeft = PosElemento.left,
  148.                             posicionTop = PosElemento.bottom;
  149.  
  150.                             _this.Desplieaga(posicionLeft, posicionTop);
  151.                         }
  152.  
  153.                         if (_this.elTxtBox.value.length <= 2) {
  154.  
  155.                             _this.Cerrar();
  156.                         }
  157.                     }
  158.                 }
  159.             }
  160.  
  161.             _this.ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  162.             _this.ajax.send('q='+_this.elTxtBox.value);
  163.             return;
  164.  
  165.         }, 700);
  166.     }
  167. }
  168.  
  169.  
  170.  
  171. autoCompletado.prototype.copypasteRaton = function(elTxtBox) {
  172.  
  173.     var _this = this;
  174.     setTimeout(function() {_this.autoCompletaRaton(elTxtBox)}, 0);
  175. }
  176.  
  177.  
  178. autoCompletado.prototype.autoCompletaRaton = function(elTxtBox) {
  179.  
  180.     this.elTxtBox = elTxtBox;
  181.  
  182.     if (this.elTxtBox.value.length <= 2) {
  183.  
  184.         return;
  185.     }
  186.  
  187.     var _this = this;
  188.  
  189.     this.elTxtBox.insertAdjacentHTML('afterend', '<img src="./precarga.gif" />');
  190.  
  191.     this.ajax.open('POST', _this.url, true);
  192.  
  193.     this.ajax.onreadystatechange = function() {
  194.  
  195.         if (!_this.ajax || _this.ajax == null) { return; }
  196.  
  197.         if (_this.ajax.readyState == 4) {
  198.  
  199.             if (_this.ajax.status == 200) {
  200.  
  201.                 _this.elDiv.innerHTML = _this.ajax.responseText;
  202.                
  203.                 _this.elTxtBox.nextElementSibling.remove();
  204.                 _this.opt = _this.elDiv.getElementsByTagName('li');
  205.  
  206.                 [].forEach.call(_this.opt, function(elem) {
  207.                        
  208.                     elem.addEventListener('mouseover',  function() {
  209.  
  210.                         _this.Marcar(this);
  211.  
  212.                     }, false);
  213.                 });
  214.  
  215.  
  216.                 if (_this.peticiones++ == 0) {
  217.  
  218.                     var PosElemento = _this.elTxtBox.getBoundingClientRect(),
  219.                     posicionLeft = PosElemento.left,
  220.                     posicionTop = PosElemento.bottom;
  221.  
  222.                     _this.Desplieaga(posicionLeft, posicionTop);
  223.                 }
  224.  
  225.                 if (_this.elTxtBox.value.length <= 2) {
  226.  
  227.                     _this.Cerrar();
  228.                 }  
  229.             }
  230.         }
  231.     }
  232.  
  233.     _this.ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  234.     _this.ajax.send('q='+_this.elTxtBox.value);
  235.     return;
  236. }
  237.  
  238.  
  239.  
  240. autoCompletado.prototype.Desplieaga = function(posLeft, posTop) {
  241.  
  242.     this.elDiv.style.left = posLeft + 'px';
  243.     this.elDiv.style.top = posTop + 'px';
  244.     this.elDiv.style.display = 'block';
  245. }
  246.  
  247.  
  248.  
  249.  
  250. autoCompletado.prototype.Marcar = function(sel) {
  251.  
  252.     this.optSel = sel;
  253.  
  254.     for (var i = 0; i < this.opt.length; i++) {
  255.  
  256.         if (this.opt[i].className == 'seleccionado') {
  257.  
  258.             this.opt[i].className = '';
  259.             sel.className = 'seleccionado';
  260.             break;
  261.         }
  262.     }
  263. }
  264.  
  265.  
  266.  
  267.  
  268. autoCompletado.prototype.BajaOpt = function() {
  269.  
  270.     for (var i = 0; i < this.opt.length; i++) {
  271.  
  272.         if (this.opt[i].className == 'seleccionado') {
  273.  
  274.             this.opt[i].className = '';
  275.  
  276.             i = (i < this.opt.length-1) ? ++i : 0;
  277.             this.optSel = this.opt[i];
  278.             this.opt[i].className = 'seleccionado';
  279.             break;
  280.         }
  281.     }
  282. }
  283.  
  284.  
  285.  
  286.  
  287. autoCompletado.prototype.SubeOpt = function() {
  288.  
  289.     for (var i = 0; i < this.opt.length; i++) {
  290.  
  291.         if (this.opt[i].className == 'seleccionado') {
  292.  
  293.             this.opt[i].className = '';
  294.  
  295.             i = (i < this.opt.length && i > 0) ? --i : this.opt.length-1;
  296.             this.optSel = this.opt[i];
  297.             this.opt[i].className = 'seleccionado';
  298.             break;
  299.         }
  300.     }
  301. }
  302.  
  303.  
  304.  
  305.  
  306. autoCompletado.prototype.rellenarConRaton = function() {
  307.  
  308.     this.elTxtBox.value = this.optSel.textContent;
  309.     this.Cerrar();
  310. }
  311.  
  312.  
  313.  
  314.  
  315. autoCompletado.prototype.rellenarConEnteryTab = function(ev) {
  316.  
  317.     var keyCode = ev.keyCode;
  318.  
  319.     if ((keyCode == 13) || (keyCode == 9)) {
  320.  
  321.         this.elTxtBox.value = this.optSel.textContent;
  322.         this.Cerrar();
  323.  
  324.         if (keyCode == 13) {
  325.  
  326.             ev.preventDefault();
  327.         }
  328.  
  329.     }  
  330. }
  331.  
  332.  
  333.  
  334.  
  335. autoCompletado.prototype.Cerrar = function() {
  336.  
  337.     var _this = this;
  338.  
  339.     setTimeout(function() {
  340.  
  341.         _this.elDiv.style.display = 'none';
  342.         _this.elDiv.innerHTML = '';
  343.         _this.peticiones = 0;
  344.  
  345.     }, 200);
  346.    
  347. }
  348. </script>
  349. </head>
  350. <body>
  351.  
  352. <form method="post" action="">
  353. Nombre: <input type="text" name="txt" id="txt1" class="autocomplete" value="" autocomplete="off" tabindex="1" />
  354. <br /><br />
  355. Nombre: <input type="text" name="txt" id="txt2" class="autocomplete" value="" autocomplete="off" tabindex="2" />
  356. </form>
  357.  
  358. <ul id="contenedorOpt"></ul>
  359.  
  360. </body>
  361. </html>
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}

Última edición por IsaBelM; 27/12/2016 a las 14:49 Razón: actualizar
  #13 (permalink)  
Antiguo 23/03/2012, 17:49
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Pues nada, y ya me estoy sintiéndo avergonzado como no tienes idea, porque si bien es cierto no tengo tú nivel en programación tampoco soy un novato en el tema (lo digo honestamente) y he revisado con cuidado toda la conexión y demás pero nada de nada.

He publicado estos archivos en Brikinster donde sólo he cambiado el nombre y ubicación de la base de datos y agregado luego del formulario una simple consulta para mostrar que si hay conexión con la base de datos

El código es este

Código Javascript:
Ver original
  1. nombre=0
  2.     SET oConn = Server.CreateObject("ADODB.Connection")
  3.     oConn.open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="&Server.MapPath("db/inmemoriam.mdb")&";"
  4.    
  5.     SQL="select archivo from archivos"
  6.     set rs = oConn.Execute(SQL)
  7.     If not rs.eof then
  8.         registros = rs.getrows()
  9.     Else
  10.         Response.Write "<p class=""deseleccionado""><strong>Sin resultados</strong></p>"
  11.         Response.End ()
  12.     End If
  13.     rs.Close
  14.     set rs = nothing
  15.     oConn.Close
  16.     set oConn = nothing
  17.    
  18.     For i = 0 to Ubound(registros,2)
  19.         Response.Write registros(nombre,i) & "<br />"
  20.     Next

por cierto en el anterior ejemplo al momento de recorrer el array había puesto 1,i pero en realidad lo tengo como tú lo has publicado con la variable nombre

El listado que verás en la página que te menciono es el mismo que utilizo para el Ajax que estamos viendo y como verás, ni aún ingresando 3 o más caracteres me muestra un resultado

Por cierto tampoco aparece el alert con "Hey" que has agregado a en la función Cerrar2.

La dirección es esta http://rmsd.brinkster.net/selecusuarios00.asp

Algo se esta pasando en todo esto pues las demás aplicaciones que estoy realizando (todo un sistema contable por cierto) funcionan perfectamente y esto lo tengo en una carpeta aparte.


Muchas gracias en verdad
  #14 (permalink)  
Antiguo 23/03/2012, 18:18
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Cita:
Iniciado por freesoftwarrior Ver Mensaje
Por cierto tampoco aparece el alert con "Hey" que has agregado a en la función Cerrar2.
esto es absurdo. de donde has sacado esa función?? en el script que yo te he pasado de inicio no está

Algo se esta pasando en todo esto pues las demás aplicaciones que estoy realizando (todo un sistema contable por cierto) funcionan perfectamente y esto lo tengo en una carpeta aparte.

usas consola de errores?? parece que no. te muestro 2 de las muchas veces que has añadido (?) en el javascript
Cita:
init: function()

{

var elem1 = document.getElementById("txt");

var elem2 = document.getElementById("contenedor");

?

SelUsuario.Evento(elem1, 'keyup', SelUsuario.Empieza);

SelUsuario.Evento(elem2, 'mouseover', SelUsuario.Seleccionar);

SelUsuario.Evento(elem1, 'keydown', SelUsuario.Pegar2);

SelUsuario.Evento(window, 'click', SelUsuario.Cerrar);

SelUsuario.Evento(window, 'load', SelUsuario.Cerrar2);

},

?
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #15 (permalink)  
Antiguo 23/03/2012, 18:59
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Es cierto, en el que me pasaste al inicio no lo has incluido pero en el último si

Cita:
Cerrar2: function ()
{
alert("hey");
},

Tal vez sea las etiquetas quote del foro porque yo no he utilizado ? en ningún momento

Si uso la consola de errores, y justo acabo de correr una y me muestra este error


Cita:
HTML1201: localhost es un sitio web que agregó a Vista de compatibilidad.
selecusuarios00.asp
SCRIPT1003: Se esperaba ':'
selecusuarios00.asp, Línea 67 Carácter 1
y la línea 67 es creaAjax: function ()

me desconcierta eso del ? que indicas porque, salvo que sea la etiqueta quote yo no tengo ese símbolo en ningún lado del código que estoy probando localmente.
  #16 (permalink)  
Antiguo 24/03/2012, 06:31
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Cita:
Iniciado por freesoftwarrior Ver Mensaje
Es cierto, en el que me pasaste al inicio no lo has incluido pero en el último si
eres tú el que lo has añadido en el post #11. al igual que esta invocación SelUsuario.Evento(window, 'load', SelUsuario.Cerrar2);

Si uso la consola de errores, y justo acabo de correr una y me muestra este error

y la línea 67 es creaAjax: function ()

en esa línea no hay error. no sé que consola estás usando. usa la de chrome. pulsa f12 ---> tab(console)
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #17 (permalink)  
Antiguo 24/03/2012, 06:56
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Ups tienes razón, fue una prueba que había realizado....... es que la verdad estoy con la mente hecha una pasta jejejee.... mil disculpas.... yo uso la del IE, voy a ver ahora con la de Chrome y te comento.... por cierto, buenos días jejeje (aquí en Perú son las 7:52 y recién despierto pues madrugué por trabajo)

Bueno, cargué la página selecusuarios00.asp (al cual ya le quité el cerrar2) en Chrome, pulse F12 y cargué la consola, hice una prueba en la página, refresqué y volví a probar, vi la consola y refresque por si las dudas (la consola) y esto me muestra:

Cita:
Uncaught SyntaxError: Unexpected token ILLEGAL

selecusuarios00.asp:58
y la línea 58 es esta

Cita:
var elem1 = document.getElementById("txt");

Última edición por freesoftwarrior; 24/03/2012 a las 07:02
  #18 (permalink)  
Antiguo 24/03/2012, 08:24
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

no sé que estás haciendo. exactamente el mismo código que tu (incluso con access) y no tiene errores. te adjunto un *zip con los dos archivos. sólo has de editar el archivo .asp (nombre de bd y campos de la tabla)
Archivos Adjuntos
Tipo de Archivo: zip fdw.zip (2,8 KB (Kilobytes), 14 visitas)
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #19 (permalink)  
Antiguo 24/03/2012, 12:29
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Gracias por el zip. Esperaré a que sea aprobado para poder descargarlo. Luego te comento. Mil gracias por todo en verdad.
  #20 (permalink)  
Antiguo 26/03/2012, 11:44
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Estoy en deuda contigo y no es una frase dicha por simple gratitud. Pocos son capaces de dedicar tanto tiempo e interés en ayudar a desconocidos. Admito que no pocas veces he perdido la paciencia y me he mostrado arrogante. Pero hoy contigo he aprendido el verdadero valor de lo que significa COMPARTIR. Hoy me has enseñado no sólo algo más en programación sino, y es lo más importante, me has enseñado algo más como persona. Y eso que es claro que soy mucho mayor que tú pero, y eso le da más valor a esto, me has enseñado adicionalmente que Internet logra mejorar mucho a las personas y a las relaciones entre ellas.

Ojalá en algún momento pueda demostrarte pálidamente mi gratitud, pues es tan grande que dudo que algún día pueda saldar cuentas.

Un saludo desde Lima, Perú
  #21 (permalink)  
Antiguo 26/03/2012, 13:52
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

no hay nada que agradecer. simplemente con esas palabras es más que suficiente

un saludo
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #22 (permalink)  
Antiguo 26/03/2012, 18:07
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Sigo haciendo pruebas.... ya te comentaré

Última edición por freesoftwarrior; 26/03/2012 a las 18:14
  #23 (permalink)  
Antiguo 27/03/2012, 01:26
 
Fecha de Ingreso: enero-2012
Ubicación: Santiago de Surco, Lima - Perú
Mensajes: 266
Antigüedad: 12 años, 3 meses
Puntos: 57
De acuerdo Respuesta: Utilizar las teclas direccionales para seleccionar un item

Hola IsaBelM, que tal.

Yo también quiero desplazarme por los resultados de una búsqueda que tengo hecha aquí una imagen Y me basaré en tu ejemplo, aunque no uso ASP, igual lo revisaré.

Yo uso Ajax de la siguiente forma:
Creando una función nuevoAjax()
(Dejo todo el código por si alguien que pasa le es útil)
Código Javascript:
Ver original
  1. function nuevoAjax(){
  2.     var xmlhttp=false;
  3.     try{
  4.         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
  5.     }catch(e){
  6.         try {
  7.             xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
  8.         }catch(E){
  9.             xmlhttp = false;
  10.         }
  11.     }
  12.     if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
  13.         xmlhttp = new XMLHttpRequest();
  14.     }
  15.     return xmlhttp;
  16. }
  17.  
  18. var AjaxPost = function(){
  19.     this.ejecutar = ejecutar;
  20.     this.mostrar= mostrar;
  21. }
  22. function ejecutar(elemento,direccion,parametro){
  23.     this.elemento = elemento;
  24.     this.direccion = direccion;
  25.     this.parametro = parametro;
  26.     resulPedido = document.getElementById(this.elemento);
  27.     ajaxPedido = nuevoAjax();
  28.     ajaxPedido.open("POST",this.direccion,true);
  29.     ajaxPedido.onreadystatechange=function() {
  30.         if (ajaxPedido.readyState == 4) {
  31.             resulPedido.innerHTML = ajaxPedido.responseText
  32.         }
  33.     }
  34.     ajaxPedido.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
  35.     ajaxPedido.send(this.parametro);
  36. }
Y para usarlo solo envió los 3 parámetros que necesita.
Código Javascript:
Ver original
  1. function Cualquiera(){//valores de ejemplo
  2.     ajaxPost= new AjaxPost();
  3.     ajaxPost.ejecutar('div','file.php',"v=valor");
  4. }

Puedo simplificar de alguna manera la programación javascript que haz compartido con la manera en que uso ajax? o de lleno me enfoco en comprender completamente tu codigo? (Con el debido respeto que ud se merece)

Por favor explícame esta linea completamente:
Código Javascript:
Ver original
  1. var keyCode = (evt) ? evt.keyCode : evt.charCode;

Gracias
  #24 (permalink)  
Antiguo 27/03/2012, 04:56
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

la función nuevoAjax() lo que te garantiza es que el objeto pueda ser creado en navegadores antiguos (ie7-). mientras que para los navegadores modernos se usa solamente new XMLHttpRequest()

por otro lado, estás usando el constructor en lugar de literal, no hay ningún problema en ello. y no, no va simplifircalo

con respecto a la línea que señalas, se usa para obtenre el código ascii de la tecla pulsada. la lucha entre ie y los demás navegadores
Cita:
ie ---> charCode
demás ---> keyCode
pd: veo que el envio lo haces con post. normalmente post se usa para hacer un insert, delete o update. y get para select
pd2: asp o php es la parte menos importante de todo esto
Código PHP:
Ver original
  1. <?php
  2. header('Content-Type: text/html; charset=UTF-8');
  3. $param = $_GET["q"];
  4.  
  5. if (strlen($param) >= 2) {
  6.  
  7.     $mysqli = new mysqli("localhost", "root", "", "bd");
  8.  
  9.     if (mysqli_connect_errno()) {
  10.         echo("Ha ocurrido un error.");
  11.         exit();
  12.     }
  13.  
  14.  
  15.     $mysqli->set_charset("utf8");
  16.  
  17.  
  18.     $sentencia = "SELECT nombre FROM tabla WHERE nombre LIKE '%".$param."%' ORDER BY nombre asc";
  19.     $resultado = $mysqli->query($sentencia);
  20.  
  21.     $contador = 0;
  22.  
  23.     if ($resultado->num_rows > 0) {
  24.  
  25.         while ($row = $resultado->fetch_array(MYSQLI_ASSOC)) {
  26.  
  27.             if($contador == 0) {
  28.  
  29.                 echo '<ol><li class="seleccionado">' .ResaltarSubStr($row['nombre'], $param). '</li>';
  30.  
  31.             } else {
  32.  
  33.                 echo '<li class="noseleccionado">' .ResaltarSubStr($row['nombre'], $param). '</li>';
  34.             }
  35.  
  36.             $contador += 1;
  37.         }
  38.  
  39.         echo "</ol>";
  40.  
  41.     } else {
  42.  
  43.         echo '<span>Sin resultados</span>';
  44.     }
  45.  
  46.  
  47. $resultado->free();
  48.  
  49.  
  50. $mysqli->close();
  51.  
  52. }
  53.  
  54.  
  55. // ========= funciones ===========
  56.  
  57. function ResaltarSubStr($texto, $param) {
  58.  
  59.     $patron = "/\b($param)+(\w)/i";
  60.     $marca = preg_replace($patron, "<strong>$1</strong>$2", $texto);
  61.     return $marca;
  62. }
  63.  
  64. // ====================
  65. ?>

no sé si he respondido a lo que preguntas, de no ser así, ......
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}

Última edición por IsaBelM; 24/10/2013 a las 15:57
  #25 (permalink)  
Antiguo 27/03/2012, 06:16
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Buenos días....... ya casito he terminado de comprender el código y ya me entró el bichito de modificar algunas cosas en mi proyecto. Antes por ejemplo, al crear un array con GetRows() creaba dos variables (de ser aplicable): iRecFirst=LBound(array,2) y iRecLast=UBound(array,2) lo cual me creaba en el 99% de los casos excesos de línea de código pues el For casi siempre es 0 To UBound(array,2).

Sin embargo tengo 2 dudas. Una es la forma en que agrupas las funciones. Se que es por evento (Evento: function (elemento,nomevento,funcion)) y las agrupas en la "categoría" var SelUsuario = { pero entonces , si quisiera aplicar estas rutinas para otro select, ¿tendría que cambiar el nombre sólo al contenedor de las funciones (en este caso SelUsuario)?, es obvio que si debo hacerlo con el ID del DIV y del INPUT. ¿Estoy en lo correcto al asumir como has agrupado las funciones?

La otra consulta es que en algunos casos, y aún con un filtro inicial de 2 caracteres, el listado inicial de coincidencias es significativamente largo, y en esos casos, en mi script original, utilizo la propiedad overflow: scroll; y overflow-x: hidden; en el archivo CSS, pero he notado que aún utilizandolo en este caso, al seguir eligiendo y navegando con las teclas direccionales, pues no funciona el escroll, se pasa de largo y eso representa, en algunos casos (según los resultados de la consulta) un poco incómodo dado que uno de los campos esta al final de un iframe y como imaginarás esto descuadra toda la presentación. ¿Cómo podría solucionar ese detalle?

Cita:
else if (keyCode == 32)
{
document.getElementById("txt1").value="";
if (obj.style.display == "block"); obj.style.display= "none";
}
¿Que estoy haciendo mal?



Un saludo cordial desde Lima, Perú

Última edición por freesoftwarrior; 27/03/2012 a las 08:59 Razón: Había generalizado en un concepto de manera errónea
  #26 (permalink)  
Antiguo 27/03/2012, 16:26
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Cita:
Iniciado por freesoftwarrior Ver Mensaje
si quisiera aplicar estas rutinas para otro select, ¿tendría que cambiar el nombre sólo al contenedor de las funciones (en este caso SelUsuario)?
es algo mas complejo
Código Javascript:
Ver original
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml"lang="es" xml:lang="es">
  3. <head>
  4. <meta name="http-equiv" content="Content-type: text/html; charset=utf-8"/>
  5. <STYLE TYPE="text/css">
  6. #contenedorOpt div.seleccionado {font-weight:bold; background:#F0F0F0; color:#FF6600;}
  7. #contenedorOpt div.deseleccionado {background:#FFFFFF; color:#000000;}
  8. #contenedorOpt div {font:11px verdana; color:#000000; cursor:pointer; text-align:left; padding:2px 5px;}
  9.  
  10. .capa {
  11. background: #FFFFFF;
  12. border:1px solid rgb(120,120,120);
  13. width: 144px;
  14. _width: 146px;
  15. text-align: left;
  16. position: absolute;
  17. }
  18. </STYLE>
  19. <script type="text/javascript">
  20. var TxtId = ''; // el texbox desde donde se lanza la consulta y donde ha de imprimirse la opción cuando se usa la función Pegar()
  21.  
  22. var SelUsuario = {
  23.  
  24. captura_objeto : function(idnombre) {
  25.     return document.getElementById(idnombre);
  26. },
  27.  
  28.  
  29. Evento: function (elemento,nomevento,funcion) {
  30.     if (elemento.attachEvent) {
  31.             var f=function() {
  32.                 funcion.call(elemento,window.event);
  33.             }
  34.             elemento.attachEvent('on'+nomevento,f);
  35.             return true;
  36.     } else if (elemento.addEventListener) {
  37.             elemento.addEventListener(nomevento,funcion,false);
  38.             return true;
  39.         }else{
  40.             return false;
  41.     }
  42. },
  43.  
  44.  
  45. creaAjax: function (){
  46. ajax = new XMLHttpRequest();
  47. return ajax;
  48. },
  49.  
  50.  
  51. init: function(){
  52. var tablas = document.body.getElementsByTagName('table');
  53.     for (i=0; i < tablas.length; i++) {
  54.         var inpt = tablas[i].getElementsByTagName('input');
  55.                 SelUsuario.Evento(SelUsuario.captura_objeto(inpt[2].id), 'keyup', SelUsuario.Empieza);
  56.                 SelUsuario.Evento(SelUsuario.captura_objeto('contenedorOpt'), 'mouseover', SelUsuario.Seleccionar);
  57.             SelUsuario.Evento(SelUsuario.captura_objeto(inpt[2].id), 'keydown', SelUsuario.Pegar2);
  58.                 SelUsuario.Evento(SelUsuario.captura_objeto(inpt[2].id), 'blur', SelUsuario.Cerrar);
  59.     }
  60. },
  61.  
  62.  
  63.  
  64. PosicionAbsolutaElemento: function(elTxtBox)  {
  65.     if (typeof elTxtBox == "string")
  66.         var elTxtBox = SelUsuario.captura_objeto(elTxtBox);
  67.             if (!elTxtBox) return { top:0,left:0 };
  68.         var y = 0;
  69.         var x = 0;
  70.             while (elTxtBox.offsetParent) {
  71.                     x += elTxtBox.offsetLeft;
  72.                     y += elTxtBox.offsetTop;
  73.                 elTxtBox = elTxtBox.offsetParent;
  74.             }
  75.         return {top:y,left:x};
  76.  
  77. },
  78.  
  79.  
  80. Desplieaga: function(posLeft,posTop) {
  81. var elDiv = SelUsuario.captura_objeto('contenedorOpt');
  82. //alert(elDiv.id+ " - " +posLeft+ " - " +posTop);
  83.     elDiv.style.left = posLeft+'px';
  84.     elDiv.style.top = parseInt(posTop+21) +'px';
  85.             elDiv.style.display = 'block';
  86.     elDiv.style.zIndex = 100;
  87. },
  88.  
  89.  
  90. Empieza: function (ev) {
  91. TxtId = SelUsuario.captura_objeto(this.id).id;
  92. var elTxtBox = SelUsuario.captura_objeto(this.id);
  93. var str = elTxtBox.value;
  94. var elDiv = SelUsuario.captura_objeto('contenedorOpt');
  95. var opt = elDiv.getElementsByTagName('DIV');
  96. var keyCode = (ev) ? et.keyCode : ev.charCode;
  97.  
  98.      if (keyCode == 40) { // flecha abajo
  99.         SelUsuario.BajaOpt ('contenedorOpt')
  100.  
  101.      } else if (keyCode == 38) { // flecha arriba
  102.         SelUsuario.SubeOpt ('contenedorOpt')
  103.  
  104.     } else if (keyCode == 13) { // enter
  105.         for (var i = 0; i <= opt.length-1; i++) {
  106.             if (opt[i].className == "seleccionado") {
  107.                 str = opt[i].id;
  108.                 if (elDiv.style.display == "block"); elDiv.style.display= "none";
  109.         break;
  110.             }
  111.         }
  112.  
  113.         try{
  114.             ev.preventDefault();
  115.         }catch(e){
  116.             ev.returnValue = false;
  117.         }
  118.     } else {
  119.  
  120.         if (str.length < 2) {
  121.             //elDiv.innerHTML = "";
  122.             if (elDiv.style.display == "none")  elDiv.style.display= "none";
  123.                     else elDiv.style.display= "none";  
  124.             return;
  125.         }
  126.  
  127.         ajax = SelUsuario.creaAjax()
  128.         if (ajax==null) {
  129.             alert ("Tu navegador no soporta Ajax");
  130.         return;
  131.         }
  132.  
  133. var url="SelecUsuarios.php?q="+escape(str);
  134. ajax.open("GET",url,true);
  135. ajax.onreadystatechange = function () {
  136. var PosElemento = SelUsuario.PosicionAbsolutaElemento(elTxtBox);
  137. var posicionInicialLeft = parseInt(PosElemento.left);
  138. var posicionInicialTop = parseInt(PosElemento.top);
  139.  
  140.         if (ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3) {
  141.                                         elDiv.innerHTML = "<p align='center'><img src='precarga.gif' border='0px' widht='15px' height='15px'/></p>";
  142.             elDiv.style.display= "block";
  143.                 }
  144.  
  145.                 else if (ajax.readyState==4) {
  146.             if (ajax.status==200) {
  147.                 elDiv.innerHTML = unescape(ajax.responseText);
  148.             }else {
  149.                                         elDiv.innerHTML = "<p>Se ha producido un error</p>";
  150.             }
  151.  
  152.         if (elDiv.style.display == "none")  elDiv.style.display= "block";
  153.         }
  154. SelUsuario.Desplieaga(posicionInicialLeft, posicionInicialTop);
  155.     }
  156.     //ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  157.             ajax.send(null);
  158.             return
  159. }
  160. },
  161.  
  162.  
  163.  
  164.  
  165.  
  166. Seleccionar: function () {
  167. var opt = SelUsuario.captura_objeto('contenedorOpt').getElementsByTagName('DIV');
  168.  
  169.     for (var i = 0; i < opt.length; i++) {
  170.         SelUsuario.Evento(opt[i], 'click', function() {
  171. //alert(this.id);
  172.         SelUsuario.Pegar(this.id);
  173.         })  
  174.  
  175.  
  176.         SelUsuario.Evento(opt[i], 'mouseover',  function() {
  177. //alert(this.id);
  178.         SelUsuario.Marcar(this.id);
  179.         })
  180.  
  181.  
  182.         //SelUsuario.Evento(opt[i], 'mouseout',  function() {
  183.         //SelUsuario.DesMarcar(this.id);
  184.         //})
  185.     }
  186. },
  187.  
  188.  
  189.  
  190. Pegar: function (valor) {
  191. //alert(TxtId);
  192. var elDiv = SelUsuario.captura_objeto('contenedorOpt')
  193.     SelUsuario.captura_objeto(TxtId).value = valor;
  194.             if (elDiv.style.display == "block"); elDiv.style.display= "none";      
  195. },
  196.  
  197.  
  198.  
  199. Marcar: function (valor) {
  200. //alert(valor.id);
  201. var selecionado = SelUsuario.captura_objeto(valor);
  202. var opt = SelUsuario.captura_objeto('contenedorOpt').getElementsByTagName('DIV');
  203.     for (var i = 0; i < opt.length; i++) {
  204.         if (opt[i].className == "seleccionado") {
  205. //alert(opt[i].id + " - " + valor.id);
  206.             opt[i].className = "deseleccionado";
  207.             selecionado.className = "seleccionado";
  208.     break;
  209.         }
  210.     }
  211. },
  212.  
  213. //DesMarcar: function (valor) {
  214. //var opt = SelUsuario.captura_objeto(valor);
  215. //alert(opt);
  216. //opt.className = "deseleccionado"
  217. //alert("el " +valor);         
  218. //},
  219.  
  220.  
  221. Pegar2: function (ev) {
  222. var elDiv = SelUsuario.captura_objeto('contenedorOpt')
  223. var opt = elDiv.getElementsByTagName('DIV');
  224. var keyCode = (ev) ? et.keyCode : ev.charCode;
  225.  
  226. // enter 13 tab 9
  227.     if ((keyCode == 13) || (keyCode == 9)) {
  228. //alert("enter")
  229.         for (var i = 0; i <= opt.length-1; i++) {
  230.  
  231.             if (opt[i].className == "seleccionado") {
  232.                 SelUsuario.captura_objeto(this.id).value = opt[i].id;
  233.                 //window.focus();
  234.                     if (elDiv.style.display == "block"); elDiv.style.display= "none";
  235.         break;
  236. //alert(opt[i].id);
  237.             }
  238.         }
  239.  
  240.     if (keyCode == 13) {
  241.         try{
  242.             ev.preventDefault();
  243.         }catch(e){
  244.             ev.returnValue = false;
  245.         }
  246.     }
  247.  
  248.  
  249.     }  
  250. },
  251.  
  252.  
  253.  
  254. BajaOpt: function() {
  255. var opt = SelUsuario.captura_objeto('contenedorOpt').getElementsByTagName('DIV');
  256.     for (var i = 0; i <= opt.length-1; i++) {
  257.         if (opt[i].className == "seleccionado") {
  258.             opt[i].className = "deseleccionado";
  259.             if (i < opt.length-1){
  260.                 i++;
  261.             }else{
  262.                 i = 0;
  263.             }
  264. //alert("Largo: " +(opt.length-1)+ " Valor: " +i);
  265.             opt[i].className = "seleccionado"
  266.         }
  267.     }
  268. },
  269.  
  270.  
  271. SubeOpt: function() {
  272. var opt = SelUsuario.captura_objeto('contenedorOpt').getElementsByTagName('DIV');
  273.     for (var i = 0; i <= opt.length-1; i++) {
  274.         if (opt[i].className == "seleccionado") {
  275.             opt[i].className = "deseleccionado";
  276.             if (i < opt.length && i > 0){
  277.                 i--;
  278.             }else{
  279.                 i = opt.length-1;
  280.             }
  281. //alert("Largo: " +(opt.length-1)+ " Valor: " +i);
  282.             opt[i].className = "seleccionado"
  283.         }
  284.     }
  285. },
  286.  
  287.  
  288. Cerrar: function () {
  289. //alert(this.id)
  290. setTimeout("var elDiv = SelUsuario.captura_objeto('contenedorOpt'); if (elDiv.style.display == 'block'); elDiv.style.display= 'none';", 1000);
  291. }
  292.  
  293. }
  294. SelUsuario.Evento(window, 'load', SelUsuario.init);
  295. </script>
  296. </head>
  297. <body>
  298. <form method="post" action="">
  299.  
  300. <table width="351" border="1" align="center" bordercolor="#0000FF" id="idt_1">
  301.  <tr>
  302. <td>Sel</td>  
  303. <td width="36">Csr:</td>
  304.  
  305. <td width="70">Modelo:</td>
  306. <td width="47">Serie:</td>
  307. <td width="170">Comentarios:</td>
  308. </tr>
  309. <tr>
  310. <td width="21"><input type="checkbox" name="cod" value="" tabindex="1" ></td>
  311. <td height="55"><input type="text" name="csr" readonly="readonly" size="3" value="2345" tabindex="2"></td>
  312. <td>Nombre Usuario: <input type="text" name="txt" id="txt1" value="" autocomplete="off" tabindex="3"></td>
  313. <td><input type="text" name="serie" tabindex="4"></td>
  314. <td><textarea name="comentarios" cols="30" rows="3" wrap="VIRTUAL" tabindex="5"></textarea></td>
  315. </tr>
  316.  </table>
  317.  
  318.  
  319.  
  320. <table width="351" border="1" align="center" bordercolor="#0000FF" id="idt_2">
  321.  <tr>
  322. <td>Sel</td>  
  323. <td width="36">Csr:</td>
  324. <td width="70">Modelo:</td>
  325. <td width="47">Serie:</td>
  326. <td width="170">Comentarios:</td>
  327. </tr>
  328.  
  329. <tr>
  330. <td width="21"><input type="checkbox" name="cod" value="" tabindex="6" ></td>
  331. <td height="55"><input type="text" name="csr" readonly="readonly" size="3" value="2346" tabindex="7"></td>
  332. <td>Nombre Usuario: <input type="text" name="txt" id="txt2" value="" autocomplete="off" tabindex="8"></td>
  333. <td><input type="text" name="serie" tabindex="9"></td>
  334. <td><textarea name="comentarios" cols="30" rows="3" wrap="VIRTUAL" tabindex="10"></textarea></td>
  335. </tr>
  336.  </table>
  337.  
  338. <div id="contenedorOpt" class="capa" style="display:none;"></div>
  339. </form>
  340. </body>
  341. </html>
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #27 (permalink)  
Antiguo 27/03/2012, 16:27
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Cita:
Iniciado por freesoftwarrior Ver Mensaje
¿Cómo podría solucionar ese detalle?
en BajaOpt() y SubeOpt() puede que funcione el método scrollIntoView

Cita:
BajaOpt()
ref[i].scrollIntoView(true);
ref[i].className = "deseleccionado";

SubeOpt()
ref[i].scrollIntoView(false);
ref[i].className = "deseleccionado";
pd: en el anterior post está respondida tu primera pregunta
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #28 (permalink)  
Antiguo 27/03/2012, 18:28
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Muchas gracias por ambas respuestas. Ya había logrado deducir los cambios que tengo que hacer para poder utilizar el script en distintos select. Lo último no lo conocía (lo del método scrollIntoView) lo que me hace preguntarte ¿dónde aprendiste todo esto de javascript?. Lo de ASP me resulta más familiar pero en lo de JavaScript he visto ahora muchas cosas interesante y que desconocía.

Un saludo desde el Perú
  #29 (permalink)  
Antiguo 28/03/2012, 06:01
Avatar de IsaBelM
Colaborador
 
Fecha de Ingreso: junio-2008
Mensajes: 5.032
Antigüedad: 15 años, 10 meses
Puntos: 1012
Respuesta: Utilizar las teclas direccionales para seleccionar un item

ha funcionado??

leyendo tutoriales e intentando resolver dudas de usuarios de este foro, no siempre con mucho acierto
__________________
if(ViolenciaDeGénero) {alert('MUJER ASESINADA');}
  #30 (permalink)  
Antiguo 28/03/2012, 06:25
Avatar de freesoftwarrior  
Fecha de Ingreso: marzo-2006
Mensajes: 362
Antigüedad: 18 años, 1 mes
Puntos: 10
Respuesta: Utilizar las teclas direccionales para seleccionar un item

Y si, pero le hice un pequeño cambio porque así como lo publicaste, al llegar al final de la lista, obvio se va al inicio PERO demora 2 clics para visualizarlo bien, pues se va al inicio pero se ubica en el 2do. registro. Además hay como una especie de "parpadeo". Lo solucioné de esta forma:

Cita:
BajaOpt: function()
{
var ref = document.getElementById("contenedor1").getElements ByTagName('DIV');
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].className == "seleccionado")
{
ref[i].className = "deseleccionado";
ref[i].scrollIntoView(true);
if (i < ref.length-1)
{i++;}
else
{i = 0;}
ref[i].className = "seleccionado"
ref[i].scrollIntoView(false);
}
}
},



SubeOpt: function()
{
var ref = document.getElementById("contenedor1").getElements ByTagName('DIV');
for (var i = 0; i <= ref.length-1; i++)
{
if (ref[i].className == "seleccionado")
{
ref[i].className = "deseleccionado";
ref[i].scrollIntoView(false);
if (i < ref.length && i > 0)
{i--;}
else
{i = ref.length-1;}
ref[i].className = "seleccionado"
ref[i].scrollIntoView(true);
}
}
},

Etiquetas: ajax
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 1 personas




La zona horaria es GMT -6. Ahora son las 17:23.