Foros del Web » Programando para Internet » Javascript »

como obtener la etiqueta de un <select> generado con ajax y asp?

Estas en el tema de como obtener la etiqueta de un <select> generado con ajax y asp? en el foro de Javascript en Foros del Web. Gracias X leerlo amigos hace rato ando tratando de averiguar como se hace esto. lo que pasa es que necesito obtener la etiqueta del elemento ...
  #1 (permalink)  
Antiguo 24/11/2008, 10:51
Avatar de ACX_POISON  
Fecha de Ingreso: abril-2008
Ubicación: Talca-Chile
Mensajes: 750
Antigüedad: 16 años
Puntos: 7
Pregunta como obtener la etiqueta de un <select> generado con ajax y asp?

Gracias X leerlo

amigos hace rato ando tratando de averiguar como se hace esto.

lo que pasa es que necesito obtener la etiqueta del elemento seleccionado de un <select>. me explico

tengo el sgte codigo

Código PHP:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!
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>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>Consulta Alumnos</title>
<
style type="text/css">
<!--
#Layer1 {
    
position:absolute;
    
width:595px;
    
height:115px;
    
z-index:1;
    
left69px;
    
top81px;
}
-->
</
style>
<
script language="javascript">
<!--

//-->
function nuevoAjax()
{
    var 
xmlhttp=false;
     try 
    {
          
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
     } 
    catch (
e
    {
          try 
        {
               
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
          }
        catch (
E
    {
   
xmlhttp false;
  }
 }
if (!
xmlhttp && typeof XMLHttpRequest!='undefined'
{
  
xmlhttp = new XMLHttpRequest();
}
return 
xmlhttp;
}
function 
cargarContenido()
{
    var 
rutnombreapellidocontenedor;
    
    
contenedor document.getElementById('contenidoX');
    
rut=document.getElementById('frut').value;
    
nombre=document.getElementById('fnombre').value;
    
apellido=document.getElementById('fapellido').value;
    
    
ajax=nuevoAjax();
    
ajax.open("GET""carga_alumno.asp?rut="+rut+"&nombre="+nombre+"&apellido="+apellido,true);
    
ajax.onreadystatechange=function(){
        if (
ajax.readyState==4)
        {
            
contenedor.innerHTML ajax.responseText
        
}
        if(
ajax.readyState!=4)
        {
            
contenedor.innerHTML='<img src="../Images/loading.gif" alt="cargando..." width="50" height="50" />';
        }
    }
    
ajax.send(null)
}

function 
Actualiza()
{
    
valor=document.getElementById('fbusqueda').value;//obtengo valor de select
    //etiqueta=document.getElementById('fbusqueda')[selectedindex].innerHTML;  
    
    //document.write(valor);
    
document.getElementById('frut').value=valor;//asigno valor a textbox
    //document.getElementById('fnombre').value=etiqueta;
    
}
</script>
</head>
<body>
<div id="Layer1">
  <table width="603" border="1">
    <tr>
      <td width="146">Rut</td>
      <td width="159">Nombre</td>
      <td width="146">Apellido</td>
      <td colspan="2">&nbsp;</td>
    </tr>
    <tr>
    <form method="post" name="frm" id="frm" >
      <td><label>
        <input name="frut" type="text" id="frut" />
      </label></td>
      <td><label>
        <input name="fnombre" type="text" id="fnombre" />
      </label></td>
      <td><label>
        <input name="fapellido" type="text" id="fapellido" />
      </label></td>
      <td width="58"><label>
        <input type="button" name="Submit" value="Buscar"  onclick="cargarContenido();"/>
      </label></td>
      <td width="60"><label>
        <input type="reset" name="Submit2" value="Borrar" />
      </label></td>
    </form>
    </tr>
    <tr>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td colspan="2">&nbsp;</td>
    </tr>
    <tr>
      <td colspan="3"><div id="contenidoX">Ingese Datos del Alumno </div></td>
      <td colspan="2">&nbsp;</td>
    </tr>
  </table>
</div>
</body>
</html> 
con esto llamo a un archivo carga_alumnos.asp el cual con los datos ingresados en los textbox me genera un select.

este es carga_alumno.asp
Código PHP:
<html>
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<!--
#include file="../funciones/conexion.asp" -->
</head>
<
body>
<%
    if (
Request.ServerVariables("REQUEST_METHOD") = "GET"then
        
'viene de GET
        rut=ucase(replace(request.QueryString("rut"),"'",""))
        nombre=ucase(replace(request.QueryString("
nombre"),"'",""))
        apellido=ucase(replace(request.QueryString("apellido"),"'",""))
        
        response.write("
nombre"&nombre&"<brapellido"&apellido&"<brrut"&rut&"<br><br>")
        if(rut="")and(nombre="")and(apellido="")then
            response.write("
Debe ingresar al menos un parametros...<br>")
        else
        
        condicion=" 
WHERE "
        'si rut no es vacio
        if(rut<>"")then
            condicion=condicion&"
Rut LIKE('"&rut&"%')AND "
        end if
        'si nombre no es vacio 
        if (nombre<>"")then
            condicion=condicion&"
Nombres LIKE('"&nombre&"%')AND "
        end if
        'si apellido no es vacio
        if(apellido<>"")then
            condicion=condicion&"
Apellidos LIKE('"&apellido&"%')AND "
        end if
        
        condicion=mid(condicion,1,len(condicion)-4)
        
        cons="
SELECT RutNombresApellidos FROM Alumno "&condicion&"ORDER by ApellidosNombres ASC"
        
        response.write(cons&"
<br>")
        
         set rs = Server.CreateObject("
ADODB.Recordset")
         rs.Open cons, Conn, 2 , 3, 1
         aux=1
         'en esta seccionescribo el select 
              response.write("
<select size=""5"" onchange=""Actualiza();"" name=""fbusqueda"" id=""fbusqueda"">")
              while(not rs.eof)
                 alumno=server.HTMLEncode(rs("
Nombres")&".."&rs("Apellidos"))
                  rutX=rs("
RUT")
                response.Write("
<option value="&rutX&">"&alumno&"</option>")
                rs.movenext
                aux=aux+1
             wend
             if(aux>1)then
                 response.Write("
</select>")
            else
                
                response.Write("
<option>Sin Resultados...</option></select>")
            end if    
             rs.Close
          Set RS = Nothing
        
    'cierra conexion    
    Conn.close
    set Conn=Nothing
    end if
    else
    'no viene de GET
        url="
../varios/error.asp"
        response.Redirect(url)
    'cierra conexion sin get
    Conn.close
    set Conn=Nothing
    end if    
%>
</body>
</html> 
luego cuando el select aparece en el index.asp (primer codigo)

si selecciono un elemento se activa la funcion Actualizar()

la cual obtiene el valor del elemento y lo asigna a un textobox, pero necesito obtener la estiqueta de ese elemento para asignarlo a otro textbox y utilizo

Cita:
etiqueta=document.getElementById('fbusqueda')[selectedindex].innerHTML;
de la funcion Actualizar(); pero no me funciona me dice que no esta definido selectedindex, sin embargo si reemplazo selectedindex por un numero directamente , en ese caso si funciona.

asi
Cita:
etiqueta=document.getElementById('fbusqueda')[0].innerHTML;
Agradeceria cualquier ayuda y/o sugerencia pues me hace mucha falta resolver esto.

Gracias---->
__________________
Me junto con los que Saben, Queriendo Saber.
  #2 (permalink)  
Antiguo 24/11/2008, 15:32
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: como obtener la etiqueta de un <select> generado con ajax y asp?

El problema es debido a que selectedIndex no existe, tienes que llamar a la propiedad selectedIndex de tu select, no a una variable sola. Por otro lado la forma correcta de obtenerla es usar la propiedad label.

Saludos.
  #3 (permalink)  
Antiguo 25/11/2008, 08:18
Avatar de ACX_POISON  
Fecha de Ingreso: abril-2008
Ubicación: Talca-Chile
Mensajes: 750
Antigüedad: 16 años
Puntos: 7
Respuesta: como obtener la etiqueta de un <select> generado con ajax y asp?

primero gracias por responder, en segundo lugar no te entiendo eso de que selectedindex no existe hice esta prueba (me la pasaron aqui en el foro), y ahy funciona bien, me podrias explicar una poco mas que es lo que debo hacer y tambien me gustaria saber como hacer lo que me dices con label

codigo:
Cita:
<%@LANGUAGE="VBSCRIPT" CODEPAGE="1252"%>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Documento sin t&iacute;tulo</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
<select name="select" size="3" multiple="multiple" id="frut" onchange="alert(document.getElementById('frut')[selectedIndex].innerHTML)">
<option value="1">uno</option>
<option value="2">dos</option>
<option value="3">tres</option>
</select>
</form>
</body>
</html>
__________________
Me junto con los que Saben, Queriendo Saber.
  #4 (permalink)  
Antiguo 25/11/2008, 09:17
Avatar de GatorV
$this->role('moderador');
 
Fecha de Ingreso: mayo-2006
Ubicación: /home/ams/
Mensajes: 38.567
Antigüedad: 18 años
Puntos: 2135
Respuesta: como obtener la etiqueta de un <select> generado con ajax y asp?

Código:
var fBusquedaSelect = document.getElementById('fbusqueda');
var selectedOption = fBusquedaSelect.options[fBusquedaSelect.selectedIndex];
alert( "valor: " + selectedOption.value + " etiqueta: " + selectedOption.label );
Saludos.

Tema trasladado a Javascript.
  #5 (permalink)  
Antiguo 27/11/2008, 10:30
Avatar de ACX_POISON  
Fecha de Ingreso: abril-2008
Ubicación: Talca-Chile
Mensajes: 750
Antigüedad: 16 años
Puntos: 7
Respuesta: como obtener la etiqueta de un <select> generado con ajax y asp?

me volvieron a trasladar a este foro
(si de aqui me mandaron al de ajax)
__________________
Me junto con los que Saben, Queriendo Saber.
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 16:20.