操作textarea值,以便在各种情况下显示默认消息

manipulating textarea value so that a default message is shown under various circumstances

本文关键字:情况下 显示 默认 消息 textarea 操作      更新时间:2023-09-26

这是它的工作原理。在其自然状态下显示一条信息。当用户将注意力集中在文本区域时,消息就消失了。如果用户将焦点移出文本区,则消息显示

我的问题是,我只希望消息在开始时显示,如果且仅当在文本字段中没有用户编写的文本。也就是说,一旦用户开始键入,即使他没有关注文本区域,消息也不会显示,用户文本仍然保留。如果用户清除了文本区域,则消息将在焦点不集中时显示。

我的问题是确保在用户输入一些信息后消息不显示。

下面是我尝试过的。

 $(function() {
      // Initiate the textarea placeholder content
      if($(".more").val() != '') {
        var content = "Please provide any feedback from your experience or/and any features you would like to be added or removed.";
      // Empty it's value upon select
      $(".more").val(content);
      }
        $(".more").focus(function(event) {
            // Erase text from inside textarea
            if($(this).val() != '') {
              $(".more").val('');
          }
        });
        // Display the placeholder when the textarea is out of focus. Ensure that its empty.
        $(".more").focusout(function(event) {
          // Erase text from inside textarea
          if($(this).val() == '') {
            $(this).val("Please provide any feedback from your experience or/and any features you would like to be added or removed.");
          }
      });
    });

如果我理解正确,您希望占位符在文本区域聚焦时消失,您可以使用CSS。我在工作中经常使用这个,这是一个很好的微妙的触感。

/* set placeholder to transprent on focused elements:  */
:focus::-webkit-input-placeholder { color: transparent; }
:focus::-moz-placeholder { color: transparent; }
:focus:-ms-input-placeholder { color: transparent; }

注意:你必须使用单独的规则来保持不同的css解析器。

实时演示:http://pagedemos.com/nm2c6753g3r8/

你的问题是在下面这个块,你正在清除文本区域,如果它不是空的,你不应该这样做,你必须清除文本区域,如果它匹配一些默认文本。这样用户输入的文本在。

聚焦时就不会被清除
  if($(this).val() != '') {
     $(".more").val('');

1。默认情况下,插入一些默认文本。
2.在焦点外,如果文本区域为空,则插入默认值。
3.在焦点中,如果文本区域值等于默认文本,则清空文本区域。

试试这个。

var DefaultText = "Please provide any feedback from your experience or/and any features you would like to be added or removed."
$('#temp').val(DefaultText);
$('#temp').focusout(function(event) {
  if ($(this).val() == '') $(this).val(DefaultText); // add default text if there is no text
});
$('#temp').focusin(function(event) {
  if ($(this).val() == DefaultText) // remove text only if it default text
    $(this).val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id='temp'></textarea>

试试这个

<textarea placeholder="Enter your biography here"></textarea>