0

Как сделать, чтоб в текстовом поле (type='text') перед нажатием на него была замутированная запись типа "Логин" или "Пароль", а после нажатия надпись стиралась и поле становилось чистым?

1
  • 2
    А при чем здесь Java?
    – Dex
    30 июл 2011 в 7:06

4 ответа 4

5

В HTML5 можно так:

<input type="text" placeholder="[email protected]">

Для кроссбраузерности можно взять библиотечку placeholder.js и писать так:

<input type="text" placeholder="[email protected]" id="someinput">
<script type="text/javascript">
  inputPlaceholder( document.getElementById('someinput') )
</script>
2
  • То есть (в первом случае), то что я вписал в атрибут placeholder он мне введет в строку????
    – igolka97
    29 июл 2011 в 21:19
  • да, именно так: <input type="text" placeholder="[email protected]">
    – Nofate
    29 июл 2011 в 21:20
3
<script>
   $("#login").focus(function(){
      $(this).attr("value","");
   })
</script>

<input type="text" id="login" value="Логин" />

Это с jQuery, думаю, идея понятна.

1
  • 1
    Только строчку с $(this).attr("value",""); надо заменить на if ($(this).val() == 'Логин') $(this).val(''); В противном случае сотрете частично введенный логин (такая ситуация может быть если пользователь ввел логин неполностью, и кликнул случайно куда либо еще, когда он попытается вернуться поле окажется пустым)
    – GLAGOLA
    30 июл 2011 в 7:00
1

Вот один из достаточно простых вариантов с использованием jQuery:

<head>
    <script type="text/javascript" src="http://yandex.st/jquery/1.6.2/jquery.min.js"></script>
    <style>
    input {
        padding: 4px 2px;
        width: 200px;
    }

    label {
        position: absolute;
        width: 200px;
        text-align: center;
        margin: 5px 2px 0 2px;
        cursor: text;
    }
    </style>
    <script>
    $(document).ready(function() {
        var allfields = "input[type='text'], input[type='password']";

        $(allfields).focus(function() {
            $("label[for='" + this.id + "']").css("display", "none");
        });

        $(allfields).blur(function() {
            if (this.value == '')
                $("label[for='" + this.id + "']").css("display", "");
        });
    });
    </script>
</head>

<body>
    <form action="" method="post">
        <p>
            <label for="username">login</label>
            <input type="text" name="username" id="username" />
        </p>
        <p>
            <label for="password">password</label>
            <input type="password" name="password" id="password" />
        </p>
    </form>
</body>

input'ы в параграфы забираем специально для safari.

0

если не бояться html5 то можно использовать атрибут placholder:

<input type="text" name="login" placeholder="Введите сюда Login" />

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.