Как изменить placeholder jquery

The placeholder text is the text output for the user what is that input for. Like in HTML we use Name as an input field and place a text inside that space i.e. Enter your name. Like shown in the below image Name So we want a button or some

Improve Article

Save Article

  • Read
  • Discuss
  • Improve Article

    Save Article

    The placeholder text is the text output for the user what is that input for. Like in HTML, we use Name as an input field and place a text inside that space i.e. Enter your name. Like shown in the below image:

    Name:

    So we want a button or some event that will change that placeholder text into some other text. To do that we have 2 methods that are described below:

    Method 1: In this method we will use the attr() method. The attr() method is used to set or return the specified attribute of a selected element. It takes two arguments, the first is the attribute to be set and the second is the value of the attribute to be changed to.

    The “placeholder” attribute controls the text that will be shown as a placeholder in an input area. This attribute is passed as the first argument to the attr() method. The required text to be set is passed as the second argument. This will change the placeholder text of the element to the new text.

    • Syntax:
      $('selectedTextarea').attr('placeholder', 'Placeholder text');
    • Example:

      <!DOCTYPE html>

      <html>

      <head>

          <title>

              Changing Placeholder text

          </title>

          <style>

              body {

                  text-align: center;

              }

          </style>

      </head>

      <body>

          <h1 style="color: green;">

           GeeksforGeeks

          </h1>

          <b>

           Changing Placeholder text

          </b>

          <p>

            Click the button to change placeholder 

            of the textarea.

          </p>

          <textarea id="area1" placeholder="Default Text"></textarea>

          <br>

          <button onclick="changePlaceholder()">

              Change Placeholder

          </button>

          </script>

          <script type="text/javascript">

              function changePlaceholder() {

                  $('#area1').attr('placeholder',

                      'This is a new placeholder');

              }

          </script>

      </body>

      </html>

    • Output:

    Method 2: Using the placeholder property. The “placeholder” property is used to get or set the placeholder of an input text. This can be used to change the placeholder text to a new one. The element is first selected using a jQuery selector. The new placeholder text can then be assigned to the element’s placeholder property. This will change the placeholder text of the element to the new text.

    • Syntax:
      selectedTextarea = $('selectedTextarea')[0];
      selectedTextarea.placeholder = "Placeholder text";
    • Example:

      <!DOCTYPE html>

      <html>

      <head>

          <title>

              Changing Placeholder text

          </title>

          <style>

              body {

                  text-align: center;

              }

          </style>

      </head>

      <body>

          <h1 style="color: green;">

           GeeksforGeeks

          </h1>

          <b>

           Changing Placeholder text

          </b>

          <p>

           Click the button to change placeholder 

           of the textarea.

          </p>

          <textarea id="area1" placeholder="Default Text"></textarea>

          <br>

          <button onclick="changePlaceholder()">

              Change Placeholder

          </button>

          </script>

          <script type="text/javascript">

              function changePlaceholder() {

                  selectedTextarea = $('#area1')[0];

                  selectedTextarea.placeholder =

                      "This is a new placeholder";

              }

          </script>

      </body>

      </html>

    • Output:

    jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.
    You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.

    28.12.2019JQuery, Веб-технологии

    Текст-заполнитель — это текстовый вывод для пользователя, для чего этот ввод. Как и в HTML, мы используем Имя в качестве поля ввода и помещаем текст в это пространство, т.е. вводим ваше имя. Как показано на рисунке ниже:

    Имя:

    <!DOCTYPE html>

    <html>

    <head>

        <title>

            Changing Placeholder text

        </title>

        <style>

            body {

                text-align: center;

            }

        </style>

    </head>

    <body>

        <h1 style="color: green;">

         GeeksforGeeks

        </h1>

        <b>

         Changing Placeholder text

        </b>

        <p>

          Click the button to change placeholder 

          of the textarea.

        </p>

        <textarea id="area1" placeholder="Default Text"></textarea>

        <br>

        <button onclick="changePlaceholder()">

            Change Placeholder

        </button>

        <script src="https://code.jquery.com/jquery-3.4.1.min.js">

        </script>

        <script type="text/javascript">

            function changePlaceholder() {

                $('#area1').attr('placeholder',

                    'This is a new placeholder');

            }

        </script>

    </body>

    </html>

  • Выход:
  • Способ 2: использование свойства заполнителя. Свойство placeholder используется для получения или установки заполнителя входного текста. Это может быть использовано для изменения текста заполнителя на новый. Элемент сначала выбирается с помощью селектора jQuery. Новый текст заполнителя затем может быть назначен свойству заполнителя элемента. Это изменит текст заполнителя элемента на новый текст.

    • Синтаксис:
      selectedTextarea = $('selectedTextarea')[0];
      selectedTextarea.placeholder = "Placeholder text";
    • Пример:

      <!DOCTYPE html>

      <html>

      <head>

          <title>

              Changing Placeholder text

          </title>

          <style>

              body {

                  text-align: center;

              }

          </style>

      </head>

      <body>

          <h1 style="color: green;">

           GeeksforGeeks

          </h1>

          <b>

           Changing Placeholder text

          </b>

          <p>

           Click the button to change placeholder 

           of the textarea.

          </p>

          <textarea id="area1" placeholder="Default Text"></textarea>

          <br>

          <button onclick="changePlaceholder()">

              Change Placeholder

          </button>

          <script src="https://code.jquery.com/jquery-3.4.1.min.js">

          </script>

          <script type="text/javascript">

              function changePlaceholder() {

                  selectedTextarea = $('#area1')[0];

                  selectedTextarea.placeholder =

                      "This is a new placeholder";

              }

          </script>

      </body>

      </html>

    • Выход:

    Рекомендуемые посты:

    • Как изменить текст кнопки с помощью jQuery?
    • JQuery | Изменить текст элемента span
    • Изменить цвет заполнителя ввода HTML5 с помощью CSS
    • Как выровнять заполнитель текста в HTML?
    • HTML | Свойство заполнителя входного текста DOM
    • Как изменить текст метки с помощью JavaScript?
    • JavaScript | Изменить текст элемента span
    • Как изменить идентификатор элемента с помощью jQuery?
    • JQuery | change () с примерами
    • Как изменить значение флажка с помощью jQuery?
    • Как изменить имя элемента HTML с помощью jQuery?
    • Как изменить стиль курсора с помощью jQuery?
    • Как изменить фоновое изображение с помощью jQuery?
    • JQuery | : селектор текста
    • JQuery | Метод text ()

    Как изменить текст заполнителя с помощью jQuery?

    0.00 (0%) 0 votes

    I was pleasantly surprised to discover that the following code, when viewed in Chrome, renders a datepicker:

    <input type="date" name="wdate" id="wdate" value="" placeholder="date of purchase" />
    

    However, the placeholder text is ignored and «Date/Month/Year» is shown instead.

    How can I change the placeholder text and use my own?

    I have already tried:

    <script>
        $("#wdate").attr("placeholder", "Day/Month/Year of purchase");
    </script>
    

    but to no avail.

    War10ck's user avatar

    War10ck

    12.3k7 gold badges41 silver badges52 bronze badges

    asked Oct 12, 2012 at 14:08

    Jez D's user avatar

    7

    answered Oct 13, 2012 at 1:58

    int32_t's user avatar

    int32_tint32_t

    5,5741 gold badge22 silver badges20 bronze badges

    0

    Older question, but here is the solution I recently had to use.

    You will not be able to use the HTML5 date field, but this can be done with jQuery UI datepicker.
    http://jsfiddle.net/egeis/3ow88r6u/

    var $datePicker = $(".datepicker");
    
    // We don't want the val method to include placehoder value, so removing it here.
    var $valFn = $.fn.val;
    $.fn.extend({
        val: function() {
            var valCatch = $valFn.apply(this, arguments);
            var placeholder = $(this).attr("placeholder");
            
            // To check this val is called to set value and the val is for datePicker element 
            if (!arguments.length && this.hasClass('hasDatepicker')) {
                if (valCatch.indexOf(placeholder) != -1) {
                    return valCatch.replace(placeholder, "");
                }
            }
            return valCatch;
        }
    });
    
    // Insert placeholder as prefix in the value, when user makes a change.
    $datePicker.datepicker({
        onSelect: function(arg) {
            $(this).val($(this).attr("placeholder") + arg);
        }
    });
    
    // Display value of datepicker
    $("#Button1").click(function() {
        alert('call val(): {' + $datePicker.val() + '}');
    });
    
    // Submit
    $('form').on('submit', function() {
        $datePicker.val($datePicker.val());
        alert('value on submit: {' + $datePicker[0].value + '}');
        return false;
    });
    .ui-datepicker { width:210px !important; }
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/blitzer/jquery-ui.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    <form method="post">
        <p>HTML5 Date: <input type="date" placeholder="html5 date:" /></p>
        <p>jQuery DatePicker: <input type="text" class="datepicker" placeholder="Start date:" /></p>
        <p><input id="Button1" type="button" value="Get DatePicker Value" title="Get DatePicker Value" /></p>
        <p><input type="submit" text="fire submit" /></p>
        <p>Original Source for this <a target="_blank" href="http://jqfaq.com/how-to-add-some-custom-text-to-the-datepickers-text-field/">JQFaq Question</a></p>
    </form>

    answered Oct 21, 2014 at 20:40

    Eddie's user avatar

    EddieEddie

    4,9908 gold badges36 silver badges46 bronze badges

    I was pleasantly surprised to discover that the following code, when viewed in Chrome, renders a datepicker:

    <input type="date" name="wdate" id="wdate" value="" placeholder="date of purchase" />
    

    However, the placeholder text is ignored and «Date/Month/Year» is shown instead.

    How can I change the placeholder text and use my own?

    I have already tried:

    <script>
        $("#wdate").attr("placeholder", "Day/Month/Year of purchase");
    </script>
    

    but to no avail.

    War10ck's user avatar

    War10ck

    12.3k7 gold badges41 silver badges52 bronze badges

    asked Oct 12, 2012 at 14:08

    Jez D's user avatar

    7

    answered Oct 13, 2012 at 1:58

    int32_t's user avatar

    int32_tint32_t

    5,5741 gold badge22 silver badges20 bronze badges

    0

    Older question, but here is the solution I recently had to use.

    You will not be able to use the HTML5 date field, but this can be done with jQuery UI datepicker.
    http://jsfiddle.net/egeis/3ow88r6u/

    var $datePicker = $(".datepicker");
    
    // We don't want the val method to include placehoder value, so removing it here.
    var $valFn = $.fn.val;
    $.fn.extend({
        val: function() {
            var valCatch = $valFn.apply(this, arguments);
            var placeholder = $(this).attr("placeholder");
            
            // To check this val is called to set value and the val is for datePicker element 
            if (!arguments.length && this.hasClass('hasDatepicker')) {
                if (valCatch.indexOf(placeholder) != -1) {
                    return valCatch.replace(placeholder, "");
                }
            }
            return valCatch;
        }
    });
    
    // Insert placeholder as prefix in the value, when user makes a change.
    $datePicker.datepicker({
        onSelect: function(arg) {
            $(this).val($(this).attr("placeholder") + arg);
        }
    });
    
    // Display value of datepicker
    $("#Button1").click(function() {
        alert('call val(): {' + $datePicker.val() + '}');
    });
    
    // Submit
    $('form').on('submit', function() {
        $datePicker.val($datePicker.val());
        alert('value on submit: {' + $datePicker[0].value + '}');
        return false;
    });
    .ui-datepicker { width:210px !important; }
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/themes/blitzer/jquery-ui.css" rel="stylesheet"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
    <form method="post">
        <p>HTML5 Date: <input type="date" placeholder="html5 date:" /></p>
        <p>jQuery DatePicker: <input type="text" class="datepicker" placeholder="Start date:" /></p>
        <p><input id="Button1" type="button" value="Get DatePicker Value" title="Get DatePicker Value" /></p>
        <p><input type="submit" text="fire submit" /></p>
        <p>Original Source for this <a target="_blank" href="http://jqfaq.com/how-to-add-some-custom-text-to-the-datepickers-text-field/">JQFaq Question</a></p>
    </form>

    answered Oct 21, 2014 at 20:40

    Eddie's user avatar

    EddieEddie

    4,9908 gold badges36 silver badges46 bronze badges

    Оформление placeholder с помощью CSS стилей

    У элементов ввода есть атрибут «placeholder». С его помощью можно вывести текст в поле ввода который исчезает при начале заполнения. Браузеры по разному отображают плейсхолдер, а устаревшие — вовсе не поддерживают. Однако, существуют способы обхода всех недостатков этого полезного атрибута. Рассмотрим следующие моменты:

    • изменение стиля плейсхолдера;
    • скрытие сразу при нажатии на поле;
    • отображение в браузерах, которые не поддерживают атрибут.

    Для примера возьмём текстовое поле input и будем применять к нему стили.

    Изменение цвета placeholder

    Браузеры на разных движках по разному отображают плейсхолдер. Чаще всего это чёрный текст с прозрачностью, что в итоге смотрится как серый. Чтобы изменить цвет и прозрачность необходимо в CSS стилях к элементам ввода указывать дополнительные директивы для движков браузеров. Изменим цвет на красный без прозрачности.

    <style>
      ::-webkit-input-placeholder {color:#f00; opacity:1;}/* webkit */
      ::-moz-placeholder          {color:#f00; opacity:1;}/* Firefox 19+ */
      :-moz-placeholder           {color:#f00; opacity:1;}/* Firefox 18- */
      :-ms-input-placeholder      {color:#f00; opacity:1;}/* IE */
    </style>
    
    <input type="text" placeholder="Начните вводить текст" value="" />
    

    Если не указать «opacity», то цвет в браузерах, поддерживающих прозрачность, будет розовым. Так же можно указать для разных полей разные цвета. Для этого используйте классы.

     .input-1::-webkit-input-placeholder { color:red; }
     .input-2::-webkit-input-placeholder { color:green; }
     ...
     и.т.д.
    

    Убираем placeholder при нажатии на поле

    По-умолчанию браузеры скрывают плейсхолдер только после начала ввода текста. Но не сложно сделать чтобы он ичезал сразу после установки курсора в поле ввода. Для этого для полей с фокусом напишем стиль, в котором сделаем подсказку полностью прозрачной.

      :focus::-webkit-input-placeholder {opacity:0;}/* webkit */
      :focus::-moz-placeholder          {opacity:0;}/* Firefox 19+ */
      :focus:-moz-placeholder           {opacity:0;}/* Firefox 18- */
      :focus:-ms-input-placeholder      {opacity:0;}/* IE */
    

    Скрывать плейсхолдер при форкусе можно по разному, например, плавно изменяя прозрачность или цвет. А можно настроить и css анимацию, когда подсказка будет плавно уезжать за пределы поля. Всё это возможно благодаря CSS, но большого смысла я в этом не вижу, так как кроссбраузерность таких прелестей будет страдать, а пользы от этих эффектов практически никакой.

    Кроссбраузерность placeholder

    Устаревшие браузеры не поддерживают атрибут «placeholder» — он просто не будет отображаться. К таким браузерам относится IE8. Несмотря на прекращение поддержки Internet Explorer, есть «люди» которые им пользуются. Если плейсхолдер не несёт важной информации, то можно забить на его отображение, но если увидеть содержимое подсказки должен каждый, то разработчик обязан позаботиться о полной кроссбраузерности.

    Для отображени подсказки в браузерах, которые не поддерживают атрибут, будем использовать jquery плагин.

    Скачать «jquery.placeholder»

    Скачиваем его и подключаем. Не забываем, что должна быть подключена так же jquery библиотека. Применяем плагин к элементам ввода с атрибутом «placeholder»:

        <script src="/jquery.placeholder.min.js"></script>
        
        <script>
            $(function(){
                $('input[placeholder], textarea[placeholder]').placeholder();
            });
        </script>
        
        <style>
            input.placeholder, textarea.placeholder. { color: green; }
        </style>
    

    Плагин срабатывает только если браузер не поддерживает плейсхолдеры. В таком случае элементам, к которым он применён, присваивается класс «placeholder», а в «value» записывается текст из атрибута «placeholder». При фокусе «value» очищается. Чтобы текст из атрибута не выглядел точно так же как вводимый текст, оформляем его с помощью стилей, опираясь на устанавливаемый класс. В примере цвет текста неактивного поля будет зелёным. Но увидеть это можно только в IE8 или других устаревших браузерах.

    HTML5 Placeholder jQuery Plugin

    Demo & Examples

    https://mathiasbynens.github.io/jquery-placeholder/

    Example Usage

    HTML

    <input type="text" name="name" placeholder="e.g. John Doe">
    <input type="email" name="email" placeholder="e.g. address@example.ext">
    <input type="url" name="url" placeholder="e.g. https://mathiasbynens.be/">
    <input type="tel" name="tel" placeholder="e.g. +32 472 77 69 88">
    <input type="password" name="password" placeholder="e.g. h4x0rpr00fz">
    <input type="search" name="search" placeholder="Search this site…">
    <textarea name="message" placeholder="Your message goes here"></textarea>

    jQuery

    Use the plugin as follows:

    $('input, textarea').placeholder();

    By default, .placeholder css class will be added. You can override default by passing the customClass option:

    $('input, textarea').placeholder({ customClass: 'my-placeholder' });

    You’ll still be able to use jQuery.val() to get and set the input values. If the element is currently showing a placeholder, .val() will return an empty string instead of the placeholder text, just like it does in browsers with a native @placeholder implementation. Calling .val('') to set an element’s value to the empty string will result in the placeholder text (re)appearing.

    CSS

    The plugin automatically adds class="placeholder" to the elements who are currently showing their placeholder text. You can use this to style placeholder text differently:

    input, textarea { color: #000; }
    .placeholder { color: #aaa; }

    I’d suggest sticking to the #aaa color for placeholder text, as it’s the default in most browsers that support @placeholder. If you really want to, though, you can style the placeholder text in some of the browsers that natively support it.

    Installation

    You can install jquery-placeholder by using Bower.

    bower install jquery-placeholder

    Or you can install it through npm:

    npm install --save jquery-placeholder
    

    Contributors should install the »dev dependencies« after forking and cloning via npm.

    Notes

    • Requires jQuery 1.6+. For an older version of this plugin that works under jQuery 1.4.2+, see v1.8.7.

    • Works in all A-grade browsers, including IE6.

    • Automatically checks if the browser natively supports the HTML5 placeholder attribute for input and textarea elements. If this is the case, the plugin won’t do anything. If @placeholder is only supported for input elements, the plugin will leave those alone and apply to textareas exclusively. (This is the case for Safari 4, Opera 11.00, and possibly other browsers.)

    • Caches the results of its two feature tests in jQuery.fn.placeholder.input and jQuery.fn.placeholder.textarea. For example, if @placeholder is natively supported for input elements, jQuery.fn.placeholder.input will be true. After loading the plugin, you can re-use these properties in your own code.

    • Using <input type="reset" /> will break the plugin functionality

    • Makes sure it never causes duplicate IDs in your DOM, even in browsers that need an extra input element to fake @placeholder for password inputs. This means you can safely do stuff like:

      <label for="bar">Example label</label>
      <input type="password" placeholder="foo" id="bar">

      And the <label> will always point to the <input> element you’d expect. Also, all CSS styles based on the ID will just work™.

    License

    This plugin is available under the MIT license.

    Thanks to…

    • Paul Irish for his inspiring snippet in jQuery 1.4 Hawtness #1
    • everyone from #jquery for the tips, ideas and patches
    • anyone who contributed a patch or made a helpful suggestion

    – Mathias

    Понравилась статья? Поделить с друзьями:
  • Как изменить sample based simulink
  • Как изменить pixel aspect ratio
  • Как изменить sampfuncs файл
  • Как изменить pivot point blender
  • Как изменить samp dll