Добавление подсказок ввода к полям формы HTML
Я ищу хороший способ добавить подсказки ввода к моим полям формы HTML. Точно так же StackOverflow использует светло-серый текст в качестве подсказок во всех своих текстовых полях.
Понял, что там будет плагин jQuery, но пока ничего хорошего не нашел. Кто-нибудь?
Ответы
Ответ 1
См. ответы на этот вопрос: Значение по умолчанию JQuery в поле пароля
В html5 вы можете сделать это:
<input type="text" placeholder="Default Value"/>
Это то, что делает SO, если вы просматриваете панель поиска сверху:
<input name="q" class="textbox" tabindex="1" onfocus="if (this.value=='search') this.value = ''" type="text" maxlength="140" size="28" value="search">
Ответ 2
Если вы имеете в виду светло-серый текст внутри поля формы, вы можете использовать атрибут placeholder
в последних браузерах:
<input type="text" placeholder="This text will appear inside the form field until the user focuses it">
Я не знаю каких-либо пакетов jQuery-плагинов, которые имитируют эту функциональность в браузерах, которые не поддерживают placeholder
, но вот пример того, как сделать это самостоятельно в jQuery:
Ответ 3
Вы можете использовать HTML5 или 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
});
Ответ 4
У меня были те же проблемы, но использование IE 8 не позволяло мне использовать HTML 5
Я использовал следующий код, вдохновленный Кайлом Шеффером.
$.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);
}
При использовании функции автозаполнения JQuery мне нужно было добавить $(this).blur(); утверждение функции изменения. Это гарантировало, что событие размытия было инициировано после завершения всех других событий автозаполнения, чтобы убедиться, что проверка поля была выполнена для сброса запроса, если это необходимо.
$(...).autocomplete({change:function(){ $(this).blur(); }})