¿Cómo hago que un cuadro de texto HTML muestre una pista cuando está vacío?


Quiero que el cuadro de búsqueda en mi página web muestre la palabra "Buscar" en cursiva gris. Cuando el cuadro recibe el foco, debe verse como un cuadro de texto vacío. Si ya hay texto en él, debe mostrar el texto normalmente (negro, sin cursiva). Esto me ayudará a evitar el desorden al quitar la etiqueta.

Por cierto, esta es una búsqueda on-page Ajax, por lo que no tiene botón.

Author: Drew Noakes, 2008-09-20

20 answers

Otra opción, si usted está feliz de tener esta característica solo para los navegadores más nuevos, es utilizar el soporte ofrecido por HTML 5 marcador de posición atributo:

<input name="email" placeholder="Email Address">

En ausencia de cualquier estilo, en Chrome esto se ve como:

introduzca la descripción de la imagen aquí

Puedes probar demos aquí y en Estilo de marcador de posición HTML5 con CSS.

Asegúrese de comprobar la compatibilidad del navegador de esta función. El soporte en Firefox fue añadido en 3.7. Chrome está bien. Internet Explorer solo agregó soporte en 10. Si se dirige a un navegador que no admite marcadores de posición de entrada, puede usar un complemento de jQuery llamado jQuery HTML5 Placeholder y, a continuación, simplemente agregue el siguiente código JavaScript para habilitarlo.

$('input[placeholder], textarea[placeholder]').placeholder();
 334
Author: Drew Noakes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-20 18:46:55

Que se conoce como una marca de agua de cuadro de texto, y se hace a través de JavaScript.

O si utiliza jQuery, un enfoque mucho mejor:

 91
Author: naspinski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-08 03:08:40

Puede establecer el marcador de posición usando el placeholder atributo en HTML ( soporte del navegador). font-style y color se pueden cambiar con CSS (aunque el soporte del navegador es limitado).

input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */
 color:gray;
 font-style:italic;
}
input[type=search]:-moz-placeholder { /* Firefox 18- */
 color:gray;
 font-style:italic;
}
input[type=search]::-moz-placeholder { /* Firefox 19+ */
 color:gray;
 font-style:italic;
}
input[type=search]:-ms-input-placeholder { /* IE (10+?) */
 color:gray;
 font-style:italic;
}
<input placeholder="Search" type="search" name="q">
 40
Author: 0b10011,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-18 18:01:59

Puede agregar y eliminar una clase CSS especial y modificar el valor de entradaonfocus/onblur con JavaScript:

<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">

Luego especifique una clase hint con el estilo que desea en su CSS, por ejemplo:

input.hint {
    color: grey;
}
 20
Author: levik,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-14 16:23:17

La mejor manera es cablear sus eventos JavaScript usando algún tipo de biblioteca JavaScript como jQuery o YUI y poner su código en un externo .js-file.

Pero si quieres una solución rápida y sucia esta es tu solución HTML en línea:

<input type="text" id="textbox" value="Search"
    onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}" 
    onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />

Actualizado : Se ha añadido el coloring-stuff solicitado.

 6
Author: Seb Nilsson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-14 16:25:10

Publiqué una solución para esto en mi sitio web hace algún tiempo. Para usarlo, importa un único archivo .js:

<script type="text/javascript" src="/hint-textbox.js"></script>

Luego anota cualquier entrada que quieras tener sugerencias con la clase CSS hintTextbox:

<input type="text" name="email" value="enter email" class="hintTextbox" />

Más información y ejemplo están disponibles aquí.

 4
Author: Drew Noakes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-06-08 04:10:31

Aquí hay un ejemplo funcional con la caché de la biblioteca Ajax de Google y algo de magia de jQuery.

Este sería el CSS:

<style type="text/stylesheet" media="screen">
    .inputblank { color:gray; }  /* Class to use for blank input */
</style>

Este sería el código JavaScript:

<script language="javascript"
        type="text/javascript"
        src="http://www.google.com/jsapi">
</script>
<script>
    // Load jQuery
    google.load("jquery", "1");

    google.setOnLoadCallback(function() {
        $("#search_form")
            .submit(function() {
                alert("Submitted. Value= " + $("input:first").val());
                return false;
        });

        $("#keywords")
            .focus(function() {
                if ($(this).val() == 'Search') {
                    $(this)
                    .removeClass('inputblank')
                    .val('');
                }
            })
            .blur(function() {
                if ($(this).val() == '') {
                    $(this)
                    .addClass('inputblank')
                    .val('Search');
                }
            });
    });
</script>

Y este sería el HTML:

<form id="search_form">
    <fieldset>
        <legend>Search the site</legend>
            <label for="keywords">Keywords:</label>
        <input id="keywords" type="text" class="inputblank" value="Search"/>
    </fieldset>
</form>

Espero que sea suficiente para que te interese tanto en GAJAXLibs como en jQuery.

 3
Author: Gustavo Carreno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-14 16:32:54

Ahora se vuelve muy fácil. En html podemos dar el atributo placeholder para los elementos input.

Por ejemplo,

<input type="text" name="fst_name" placeholder="First Name"/>

Compruebe para más detalles: http://www.w3schools.com/tags/att_input_placeholder.asp

 3
Author: apm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-29 17:11:13

Para los usuarios de jQuery: el enlace jQuery de naspinski parece roto, pero pruebe este: http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints /

Obtienes un tutorial de plugin de jQuery gratis como un bono. :)

 2
Author: tuomassalo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-05-10 16:56:50

Encontré el plugin jQueryjQuery en Español ser mejor que el que aparece en la respuesta superior. Por qué mejor? Porque admite campos de entrada de contraseña. Además, establecer el color de la marca de agua (u otros atributos) es tan fácil como crear una referencia .watermark en su archivo CSS.

 2
Author: Dustin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-14 14:57:20

Esto se llama "marca de agua".

Encontré el plugin jQueryjQuery en español que, a diferencia de la primera respuesta, no requiere configuración adicional (la respuesta original también necesita una llamada especial antes de enviar el formulario).

 2
Author: elcuco,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-16 07:06:22

Use jQuery Form Notifier - es uno de los complementos de jQuery más populares y no sufre de los errores que algunas de las otras sugerencias de jQuery aquí hacen (por ejemplo, puede estilizar libremente la marca de agua, sin preocuparse si se guardará en la base de datos).

JQuery Watermark utiliza un solo estilo CSS directamente en los elementos del formulario (noté que las propiedades CSS font-size aplicadas a la marca de agua también afectaban a los cuadros de texto not no es lo que quería). El plus con jQuery La marca de agua es que puede arrastrar y soltar texto en los campos (jQuery Form Notifier no permite esto).

Otro sugerido por algunos otros (el de digitalbrush.com), enviará accidentalmente el valor de la marca de agua a su formulario, por lo que recomiendo encarecidamente que no lo haga.

 2
Author: Kimball Robinson,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-06-16 07:08:58

Utilice una imagen de fondo para representar el texto:

 input.foo { }
 input.fooempty { background-image: url("blah.png"); }

Entonces todo lo que tienes que hacer es detectar value == 0 y aplicar la clase correcta:

 <input class="foo fooempty" value="" type="text" name="bar" />

Y el código JavaScript de jQuery se ve así:

jQuery(function($)
{
    var target = $("input.foo");
    target.bind("change", function()
    {
        if( target.val().length > 1 )
        {
            target.addClass("fooempty");
        }
        else
        {
            target.removeClass("fooempty");
        }
    });
});
 1
Author: Kent Fredric,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-14 16:26:51

Usted podría fácilmente tener un cuadro de lectura "Buscar", entonces cuando el foco se cambia a que el texto se elimina. Algo como esto:

<input onfocus="this.value=''" type="text" value="Search" />

Por supuesto, si lo hace, el propio texto del usuario desaparecerá cuando haga clic. Así que probablemente quieras usar algo más robusto:

<input name="keyword_" type="text" size="25"  style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">
 1
Author: Steve Kemp,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-27 11:31:56

Cuando la página se cargue por primera vez, haga que la búsqueda aparezca en el cuadro de texto, de color gris si lo desea.

Cuando el cuadro de entrada reciba el foco, seleccione todo el texto en el cuadro de búsqueda para que el usuario pueda comenzar a escribir, lo que eliminará el texto seleccionado en el proceso. Esto también funcionará bien si el usuario desea usar el cuadro de búsqueda una segunda vez, ya que no tendrá que resaltar manualmente el texto anterior para eliminarlo.

<input type="text" value="Search" onfocus="this.select();" />
 0
Author: 17 of 26,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-20 14:15:54

Me gusta la solución de "Conocimiento Chikuse" - simple y clara. Solo es necesario añadir una llamada para desenfocar cuando la carga de la página está lista que establecerá el estado inicial:

$('input[value="text"]').blur();
 0
Author: Isaac Liu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-01-11 05:07:58

Quieres asignar algo como esto a onfocus:

if (this.value == this.defaultValue)
    this.value = ''
this.className = ''

Y esto a onblur:

if (this.value == '')
    this.value = this.defaultValue
this.className = 'placeholder'

(Puede usar algo un poco más inteligente, como una función de framework, para hacer el cambio de nombre de clase si lo desea.)

Con algunos CSS como este:

input.placeholder{
    color: gray;
    font-style: italic;
}
 0
Author: Dan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-14 16:20:17
$('input[value="text"]').focus(function(){ 
if ($(this).attr('class')=='hint') 
{ 
   $(this).removeClass('hint'); 
   $(this).val(''); 
}
});

$('input[value="text"]').blur(function(){
  if($(this).val() == '')
  {
    $(this).addClass('hint');
    $(this).val($(this).attr('title'));
  } 
});

<input type="text" value="" title="Default Watermark Text">
 -1
Author: Drew Noakes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-09-09 22:18:56

La etiqueta Html simple 'required' es útil.

<form>
<input type="text" name="test" id="test" required>
<input type="submit" value="enter">
</form>
 -1
Author: Pradeep,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-07 04:59:26

Usuario AJAXToolkit de http://asp.net

 -3
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-07 02:17:01