2011-05-18 15 views
12

Estoy buscando una buena manera de agregar solicitudes de entrada a mis campos de formulario HTML - Del mismo modo que StackOverflow utiliza texto gris claro como indicaciones en todos sus campos de texto.Agregar mensajes de entrada a los campos de formulario HTML

Supuse que habría un plugin de jQuery, pero hasta ahora no ha encontrado nada bueno. ¿Nadie?

Respuesta

19

Ver las respuestas a esta pregunta: Jquery default value in password field

en HTML5 se puede hacer esto:

<input type="text" placeholder="Default Value"/> 

Esto es lo que lo hace si ve la barra de búsqueda en la parte superior:

<input name="q" class="textbox" tabindex="1" onfocus="if (this.value=='search') this.value = ''" type="text" maxlength="140" size="28" value="search"> 
8

Si quiere decir tener texto gris claro dentro del campo de formulario, puede usar el atributo placeholder en los navegadores recientes:

<input type="text" placeholder="This text will appear inside the form field until the user focuses it"> 

No sé de ningún plug-ins-envasados ​​jQuery que imitan esta funcionalidad en los navegadores que no soportan placeholder, pero aquí es un ejemplo de cómo hacerlo usted mismo en jQuery:

4

Puede usar HTML5 o javascript/jquery.

HTML5:

<input type="text" placeholder="The text box" /> 

jQuery:

var textbox = $('input:text'); 

// Use external css. This is just for example purposes 
textbox.css({ color: '#bbb' }).val('the text box'); 

textbox.focus(function(){ 
var that = $(this); 

that.removeAttr('style'); 
that.val(''); // Empty text box 

}).blur(function(){ 
var that = $(this); 

that.css({ color: '#bbb' }); // Use external css 
$(this).val('the text box'); // Refill it 

}); 
0

que estaba teniendo los mismos problemas pero usando IE 8 no me permitirá la opción de HTML 5 He utilizado el siguiente código que era inspirado en Kyle Schaeffer.

$.fn.fieldPrompt = function() { 
/*Add the two CSS elements to the application css file. They control the wrapping element and the prompt element 
.prompt_element {display:inline-block; position:relative; } 
.prompt_element .prompt_field {display:inline-block; color:#888; font-style:italic; position:absolute; left:5px; top:2px; }*/ 

var $this = $(this); 
$('input[type=text][title],input[type=password][title],textarea[title]', $this).each(function (i) { 
    if ($(this).parent().hasClass('prompt_element') == false) { //if prompt already exists then skip 
    $(this).wrap('<div class="prompt_element" ></div>');  //wrap the element with the prompt element 
    _promptfieldClassName = 'prompt_' + $(this)[0].uniqueID; 
    var _promptfield = '<div class="prompt_field ' + _promptfieldClassName + '" >' + $(this).attr('title') + '</div>' //Create the prompt field 
    $(this).before(_promptfield)        // Add the prompt field to the Prompt element. The 
    if ($.trim($(this).val()) != '') {        //Check if the field has a value 
     $(this).prev().hide();         //Hide the prompt if field has a value 
    }; 
    $('.prompt_field').focus(function() {     //If the prompt field get the focus - move to the next field which should be the input 
     $(this).next().focus(); 
    }); 
    $(this).on('keypress paste', function() {    //If field has keypress or paste event was triggered 
     $(this).prev().hide();         //hide the prompt field 
    }); 
    $(this).blur(function() {        //If leaving the field element 
     if ($.trim($(this).val()) == '') {      //Check if the value is empty 
     $(this).prev().show();        //Show the prompt 
     } 
     else { 
     $(this).prev().hide();        //Hide the prompt. This can be initiated by other events if they fill the field. 
     } 
    }); 
    }; 
}); 
return $(this); 

}

Al utilizar la función de autocompletar Jquery que sólo tenía que añadir en $ (this) .blur(); declaración sobre la función de cambio de opción. Esto aseguró que se desencadenara el desenfoque después de que se completaran todos los demás eventos de autocompletar para garantizar que se realizara una comprobación en el campo para restablecer el aviso si fuera necesario.

$(...).autocomplete({change:function(){ $(this).blur(); }}) 
Cuestiones relacionadas