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

Textbox dependiente con Ajax y ASP

Estas en el tema de Textbox dependiente con Ajax y ASP en el foro de Frameworks JS en Foros del Web. Buenas amigos de foros del web....tengo el siguiente problema que no se como solucionar. Tengo un formulario donde necesito hacer que al escribir en un ...
  #1 (permalink)  
Antiguo 08/02/2010, 09:56
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 16 años, 6 meses
Puntos: 0
Textbox dependiente con Ajax y ASP

Buenas amigos de foros del web....tengo el siguiente problema que no se como solucionar. Tengo un formulario donde necesito hacer que al escribir en un campo de texto, me despliegue sugerencias leidas desde la BD y de acuerdo a la opcion escogida se rellene automáticamente otro campo, osea por ejemplo voy escribiendo un modelo de producto y al momento de seleccionarlo se rellena el campo de tipo de producto me entienden?

Bueno, junto a Adler en un post anterior logramos (bueno Adler....jejeje) que funcione correctamente el autocompletar pero sigo sin hacer funcionar el relleno del segundo campo.

Este es el formulario:

SelectUsuariosAjax.asp
Código ASP:
Ver original
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  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. #contenedor div.seleccionado {font-weight:bold; background:#F0F0F0; color:#black;}
  7. #contenedor div.deseleccionado {background:#FFFFFF; color:#000000;}
  8. #contenedor 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: 150px;
  14. _width: 250px;
  15. text-align: left;
  16. position: absolute;
  17. top: 30px;
  18. _top:38px;
  19. left: 117px;
  20. _left: 119px;
  21. }
  22. </STYLE>
  23. <script type="text/javascript">
  24. var familia = "";
  25. var SelUsuario = {
  26.  
  27. Evento: function (elemento,nomevento,funcion) {
  28.   if (elemento.attachEvent)
  29.   {
  30.       var f=function(){
  31.         funcion.call(elemento,window.event);
  32.     }
  33.     elemento.attachEvent('on'+nomevento,f);
  34.     return true;
  35.   }
  36.   else  
  37.     if (elemento.addEventListener)
  38.     {
  39.       elemento.addEventListener(nomevento,funcion,false);
  40.       return true;
  41.     }
  42.     else
  43.       return false;
  44. },
  45.  
  46. init: function(){
  47. var elem1 = document.getElementById("txt");
  48. var elem2 = document.getElementById("contenedor");
  49.         SelUsuario.Evento(elem1, 'keyup', SelUsuario.Empieza);
  50.         SelUsuario.Evento(elem2, 'mouseover', SelUsuario.Seleccionar);
  51.         SelUsuario.Evento(elem1, 'keydown', SelUsuario.Pegar2);
  52.         SelUsuario.Evento(window, 'click', SelUsuario.Cerrar);
  53.     },
  54.  
  55.  
  56. creaAjax: function (){
  57.     var ajaxs = ["Msxml2.XMLHTTP","Msxml2.XMLHTTP.4.0","Msxml2.XMLH TTP.5.0","Msxml2.XMLHTTP.3.0","Microsoft.XMLHTTP"];
  58.     var ajax = false;
  59.     for(var i=0 ; !ajax && i<ajaxs.length ; i++){
  60.         try{
  61.             ajax = new ActiveXObject(ajaxs[i]);   // Internet Explorer
  62.         }
  63.         catch(e) {
  64.             ajax = false;
  65.         }
  66.     }
  67.     if(!ajax && typeof XMLHttpRequest!='undefined') {
  68.         ajax = new XMLHttpRequest();  // Firefox, Opera 8.0+, Safari
  69.     }
  70.     return ajax;
  71. },
  72.  
  73. Empieza: function (ev) {
  74. var str = document.getElementById(this.id).value;
  75. var obj = document.getElementById("contenedor");
  76. var obj2 = document.getElementById("stock").options[document.getElementById("stock").selectedIndex].value;
  77. var ref = obj.getElementsByTagName('DIV');
  78. var keyCode = document.layers ? ev.which : document.all ? event.keyCode : document.getElementById ? ev.keyCode : 0;
  79.  
  80.  
  81.  if (keyCode == 40) {
  82. //alert("flecha abajo")
  83.     SelUsuario.BajaOpt ()
  84.  } else if (keyCode == 38) {
  85. //alert("flecha arriba")
  86.     SelUsuario.SubeOpt ()
  87.  
  88.  
  89.  
  90.  
  91. } else if (keyCode == 13) {
  92.  
  93. for (var i = 0; i <= ref.length-1; i++) {
  94. if (ref[i].className == "seleccionado") {
  95.  
  96.         document.getElementById("txt").value = ref[i].id;
  97.         if (obj.style.display == "block"); obj.style.display= "none";
  98.         break;
  99.         }
  100.  
  101.     }
  102.  
  103.     try{ // DOM;
  104.         ev.preventDefault();
  105.         }catch(e){ // iexplore;
  106.         ev.returnValue = false;
  107.         }
  108.  
  109. } else {
  110.  
  111.     if (str.length < 2) {
  112.         //obj.innerHTML = "";
  113.         if (obj.style.display == "none")  obj.style.display= "none";
  114.                 else obj.style.display= "none";
  115.         return;
  116.     }
  117.     ajax = SelUsuario.creaAjax()
  118.     if (ajax==null) {
  119.         alert ("Tu navegador no soporta Ajax");
  120.         return;
  121.      }
  122. var url="SelecUsuarios.asp?q="+escape(str) + "&variable=" +escape(obj2);
  123. //var url="SelecUsuarios.asp?variable=" +obj2 + "&q=" +escape(str);
  124.  
  125.     ajax.open("GET",url,true);
  126.     ajax.onreadystatechange = SelUsuario.Despliega;
  127.     //ajax.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  128.             ajax.send(null);
  129.             return
  130. }
  131. },
  132.  
  133.  
  134.  
  135. Despliega: function () {
  136. var obj = document.getElementById("contenedor");
  137.    
  138. if (ajax.readyState==1 || ajax.readyState==2 || ajax.readyState==3) {
  139. obj.innerHTML = "<p align='center'><img src='../images/cargando.gif' border='0px' widht='15px' height='15px'/></p>";
  140.             obj.style.display= "block";
  141.                 }
  142.  
  143.                 else if (ajax.readyState==4) {
  144.             if (ajax.status==200) {
  145.            
  146. var division = unescape(ajax.responseText);
  147. obj.innerHTML = division.split("-")[0];
  148. familia = division.split("-")[1];
  149.            
  150.            
  151.             obj.innerHTML = unescape(ajax.responseText);
  152.  
  153.             }else {
  154.              obj.innerHTML = "<p>Se ha producido un error</p>";
  155.             }
  156.  
  157.         if (obj.style.display == "none")  obj.style.display= "block";
  158.         }
  159. },
  160.  
  161.  
  162.  
  163. Seleccionar: function () {
  164. var ref = document.getElementById(this.id).getElementsByTagName('DIV');
  165. //alert(ref);
  166. for (var i = 0; i < ref.length; i++) {
  167.  
  168. SelUsuario.Evento(ref[i], 'click', function() {
  169. SelUsuario.Pegar(this.id, familia);
  170. //alert(this.id);
  171. })  
  172.  
  173.  
  174. SelUsuario.Evento(ref[i], 'mouseover',  function() {
  175. SelUsuario.Marcar(this.id);
  176. })
  177.  
  178. //SelUsuario.Evento(ref[i], 'mouseout',  function() {
  179. //SelUsuario.DesMarcar(this.id);
  180. //})
  181. }
  182. },
  183.  
  184. Pegar: function (valor, f) {
  185. //alert("el val " +valor);
  186. var obj = document.getElementById("contenedor")
  187. document.getElementById("txt").value = valor;
  188. document.getElementById("fam").value = f;
  189.                 if (obj.style.display == "block"); obj.style.display= "none";      
  190. },
  191.  
  192.  
  193. Pegar2: function (ev) {
  194. var obj = document.getElementById("contenedor")
  195. var ref = obj.getElementsByTagName('DIV');
  196. var keyCode = document.layers ? ev.which : document.all ? event.keyCode : document.getElementById ? ev.keyCode : 0;
  197.  
  198. // enter 13 tab 9
  199. if ((keyCode == 13) || (keyCode == 9)) {
  200. //alert("enter")
  201.  
  202. for (var i = 0; i <= ref.length-1; i++) {
  203. if (ref[i].className == "seleccionado") {
  204.  
  205.         document.getElementById("txt").value = ref[i].id;
  206.         //window.focus();
  207.         if (obj.style.display == "block"); obj.style.display= "none";
  208. break;
  209. //alert(ref[i].id);
  210.  
  211.  
  212. }
  213. }
  214.  
  215. if (keyCode == 13) {
  216.     try{ // DOM;
  217.         ev.preventDefault();
  218.         }catch(e){ // iexplore;
  219.         ev.returnValue = false;
  220.         }
  221. }
  222.  
  223.  
  224. }  
  225. },
  226.  
  227.  
  228. BajaOpt: function() {
  229. var ref = document.getElementById("contenedor").getElementsByTagName('DIV');
  230. for (var i = 0; i <= ref.length-1; i++) {
  231. if (ref[i].className == "seleccionado") {
  232. ref[i].className = "deseleccionado";
  233. if (i < ref.length-1){
  234. i++;
  235. }else{
  236. i = 0;
  237. }
  238. //alert("Largo: " +(ref.length-1)+ " Valor: " +i);
  239. ref[i].className = "seleccionado"
  240. }
  241. }
  242. },
  243.  
  244.  
  245. SubeOpt: function() {
  246. var ref = document.getElementById("contenedor").getElementsByTagName('DIV');
  247. for (var i = 0; i <= ref.length-1; i++) {
  248. if (ref[i].className == "seleccionado") {
  249. ref[i].className = "deseleccionado";
  250. if (i < ref.length && i > 0){
  251. i--;
  252. }else{
  253. i = ref.length-1;
  254. }
  255. //alert("Largo: " +(ref.length-1)+ " Valor: " +i);
  256. ref[i].className = "seleccionado"
  257. }
  258. }
  259. },
  260.  
  261.  
  262.  
  263. Marcar: function (id) {
  264. var selecionado = document.getElementById(id);
  265. var ref = document.getElementById("contenedor").getElementsByTagName('DIV');
  266. for (var i = 0; i <= ref.length-1; i++) {
  267. if (ref[i].id != id) {
  268. ref[i].className = "deseleccionado";
  269. selecionado.className = "seleccionado";
  270. }
  271. }
  272. },
  273.  
  274. //DesMarcar: function (id) {
  275. //var ref = document.getElementById(id);
  276. //alert(ref);
  277. //ref.className = "deseleccionado"
  278. //alert("el " +id);        
  279. //},
  280.  
  281.  
  282. Cerrar: function () {  
  283. var obj = document.getElementById("contenedor")
  284.             if (obj.style.display == "block"); obj.style.display= "none";  
  285.    
  286. }
  287. }
  288.  
  289. SelUsuario.Evento(window, 'load', SelUsuario.init);
  290. </script>
  291. </head>
  292. <body>
  293. <form method="post" action="">
  294. Nombre Usuario: <input name="txt" type="text" id="txt" tabindex="1" value="" size="40" autocomplete="off" />
  295. <div class="vink" style="margin:5px 0px 0px 10px">
  296. <div id="contenedor" class="capa" style="display:none;"></div></div>
  297. Filtrar: <select id="stock" name="stock">
  298. <option value="constock" selected>Solo con Stock</option>
  299. <option value="sinstock">Sin Stock</option>
  300. </select><br>
  301. <div class="vink" style="margin:5px 0px 0px 10px">
  302. <div id="campo" class="capa" style="display:none;"></div></div>
  303. Familia: <input type="text" name="fam" id="fam" /><br />
  304. <input type="submit" value="Enviar">
  305. </form>
  306. </body>
  307. </html>
  #2 (permalink)  
Antiguo 08/02/2010, 09:57
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 16 años, 6 meses
Puntos: 0
Respuesta: Textbox dependiente con Ajax y ASP

Y este es el que realiza la consulta a la bd:

SelecUsuarios.asp:
Código ASP:
Ver original
  1. <%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
  2. <%' Option Explicit %>
  3. <% Response.Buffer=True %>
  4. <% On Error Resume Next  %>
  5. <%Response.charset="utf-8"%>
  6. <%
  7. Response.addHeader "pragma", "no-cache"
  8. Response.CacheControl = "Private"
  9. Response.Expires = -1000
  10. %>
  11. <%
  12. Dim SQL, rs, oConn, registros, i
  13. Dim usuario
  14. Dim nombre
  15. nombre = 0
  16. Dim familia
  17. familia = ""
  18.  
  19. usuario = CStr(Request.QueryString("q"))
  20. combox = CStr(Request.QueryString("variable"))
  21. 'response.write ("'"&combox&"'")
  22.  
  23.  
  24. IF Len(usuario) >= 2 then
  25. ' CONEXIÓN
  26.  
  27.     set Cnn = Server.CreateObject("ADODB.Connection")
  28.     set rs = Server.CreateObject ("ADODB.Recordset")
  29.     Cnn.Open Session("cnx")
  30.  
  31. SQL="select descrip, familia from producto inner join familias on codi_fami = codi_familia "
  32.  
  33.     se_encuentra = False
  34.        
  35.      if combox = "constock" then
  36.             if se_encuentra then
  37.             SQL=SQL & " AND stock > 0"
  38.                 else
  39.             SQL=SQL & "WHERE stock > 0"
  40.             se_encuentra=True
  41.                   end if
  42.                 end if
  43.                    
  44.         if combox = "sinstock" then
  45.             if se_encuentra then
  46.             SQL=SQL & " AND stock = 0"
  47.                 else
  48.             SQL=SQL & "WHERE  stock = 0"
  49.           se_encuentra=True
  50.                   end if
  51.                     end if
  52.                    
  53.             if usuario <> "" then
  54.               if se_encuentra then
  55.     SQL=SQL & " AND descrip LIKE '"&usuario&"%'"
  56.         else
  57.         SQL=SQL & " WHERE descrip LIKE '"&usuario&"%'"
  58.           se_encuentra=True
  59.                      end if
  60.                      end if
  61.                    
  62.  
  63.  
  64. set rs = Cnn.Execute(SQL)
  65.         If not rs.eof then
  66.         registros = rs.getrows()
  67.         familia = rs.Fields("familia")
  68.             Else
  69.             Response.Write "<p class=""deseleccionado""><strong>Sin resultados</strong></p>"
  70.             Response.End ()
  71.         End If
  72.     rs.Close
  73.     set rs = nothing
  74.     Cnn.Close
  75.     set Cnn = nothing
  76. END IF
  77.  
  78. For i = 0 to Ubound(registros,2)
  79. If i = 0 then
  80. Response.Write "<div id="""& registros(nombre,i) &""" class=""seleccionado"">"& ResaltarSubStr(registros(nombre,i)) & "</div>"
  81. Else
  82. Response.Write "<div id="""& registros(nombre,i) &""" class="""">" & ResaltarSubStr(registros(nombre,i)) & "</div>"
  83. End If
  84. Next
  85.  
  86. Response.Write "-" & familia
  87.  
  88. ' ========= Funciones ===========
  89. Function ResaltarSubStr(texto)
  90. Dim objRegExp
  91.  
  92.     Set objRegExp= New RegExp
  93. objRegExp.IgnoreCase = True
  94. 'objRegExp.Global = True
  95.  
  96. objRegExp.Pattern = "\b("&usuario&")+(\w)"
  97. texto = objRegExp.Replace(texto, "<strong>$1</strong>$2")
  98.  
  99.     Set objRegExp = Nothing
  100.  
  101.     ResaltarSubStr = texto
  102.  
  103. End Function
  104. ' ========= Fin Funciones ===========
  105. %>

Eso seria.....
De antemano muchas gracias.
Hasta pronto
  #3 (permalink)  
Antiguo 08/02/2010, 10:51
Avatar de JuanRAPerez
Colaborador
 
Fecha de Ingreso: octubre-2003
Mensajes: 2.393
Antigüedad: 20 años, 6 meses
Puntos: 27
Respuesta: Textbox dependiente con Ajax y ASP

sera que te trasladan a ajax?
__________________
JuanRa Pérez
San Salvador, El Salvador
  #4 (permalink)  
Antiguo 08/02/2010, 10:58
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 16 años, 6 meses
Puntos: 0
Respuesta: Textbox dependiente con Ajax y ASP

Alguien me podría por favor orientar??

O tal vez no se, invocar un javascript que complete el campo o no??

De antemano muchas gracias

Última edición por darkmcloud; 08/02/2010 a las 13:19
  #5 (permalink)  
Antiguo 10/02/2010, 14:45
 
Fecha de Ingreso: octubre-2007
Mensajes: 191
Antigüedad: 16 años, 6 meses
Puntos: 0
Respuesta: Textbox dependiente con Ajax y ASP

Y alguien que me pueda ayudar por favor ???

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




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