Es común a muchos sitio donde se puede buscar información,disponer un control de tipo text con la leyenda 'Buscar...' y sin ningún botón a su lado. Cuando el control toma foco se borra automáticamente su contenido, el operador ingresa el texto a buscar y presiona la tecla ENTER.Para probar como capturar este evento implementaremos una página que resuelva el problema anteriormente planteado.
pagina.html
<!DOCTYPE html>
<html>
<head>
<title>Problema</title>
<script>
window.addEventListener('load',inicializarEventos,false);
function inicializarEventos()
{
var ob=document.getElementById('buscar');
ob.addEventListener('focus',tomarFoco,false);
}
function tomarFoco(e)
{
e.target.value='';
}
</script>
<link rel="StyleSheet" href="estilos.css" type="text/css">
</head>
<body>
<form action="#" method="post">
<input type="text" name="buscar" id="buscar" value="Buscar..." size="20">
</form>
</body>
</html>
El código javascript es:
window.addEventListener('load',inicializarEventos,false);
function inicializarEventos()
{
var ob=document.getElementById('buscar');
ob.addEventListener('focus',tomarFoco,false);
}
function tomarFoco(e)
{
e.target.value='';
}
Registramos el eveont focus al control de tipo input:
function inicializarEventos()
{
var ob=document.getElementById('buscar');
ob.addEventListener('focus',tomarFoco,false);
}
Cuando se activa con el mouse el control input (es decir toma foco) procedemos a borrar su contenido:
function tomarFoco(e)
{
e.target.value='';
}
Accedemos a la propiedad target del parámetro que llega a la función (recordemos que target tiene la referencia del objeto que disparó el evento)