单击文本区域可隐藏标签值

Clicking textarea hides label value

本文关键字:标签 隐藏 文本 区域 单击      更新时间:2023-09-26
当我

点击文本区域时,有没有办法删除标签?

http://jsfiddle.net/1smvym84/4/

.HTML:

<li id='field_1_9' class='gfield' >
    <label class='gfield_label' for='input_1_9'>Place this inside the textarea</label>
    <div class='ginput_container'>
        <textarea name='input_9' id='input_1_9' class='textarea medium' tabindex='8'   rows='10' cols='50'></textarea>
    </div>
</li>

JQUERY:

$(document).ready(function(){
   $('.textarea').text($('.gfield_label').text());
    $('.gfield_label').remove();
});

非常感谢任何帮助:-)

如果要

在焦点上删除它:

$("#input_1_9").focus(function() {
    $(this).parent("div").prev("label").remove();
});

我认为您正在寻找的是HTML的占位符属性:

<textarea name="input_9" id="input_1_9" class="textarea medium" tabindex="8" rows="10" cols="50" placeholder="Your text goes here"></textarea>

我认为如果您使用占位符会更好。喜欢这个:

<textarea placeholder="Place this inside the textarea"></textarea>

但是,如果你想在JS中做到这一点,它将是这样的:

$('.textarea').on('click', function() {
$('.gfield_label').remove();
});

试试这个:

$(document).ready(function(){
  //work for all elements which have the css class textarea
  $('.textarea').click(function(){
      $('.textarea').val($('.gfield_label').html());
      //if you want to remove all elements having gfield_label css class
      $('.gfield_label').remove();
  });
   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <label class="gfield_label">this is label</label>
<textarea class="textarea"></textarea>
</form>

您可能

希望在输入时将其删除,如果未写入任何内容,则将其添加回来。有两种方法可以实现此目的:

The HTML5 way:http://jsfiddle.net/1smvym84/8/

$(document).ready(function(){
   var placeholderText = $('.gfield_label').text();
   $('.textarea').attr("placeholder",placeholderText);
   $('.gfield_label').remove();
});

jQuery方式:http://jsfiddle.net/1smvym84/7/

$(document).ready(function(){
   var placeholderText = $('.gfield_label').text();
   $('.textarea').text(placeholderText);
    $('.gfield_label').remove();
    $('.textarea').focus(function(){
        var $this = $(this);
        if ($this.text() === placeholderText){
            $(this).text("");
        }
    }).blur(function(){
        var $this = $(this);
        if ($this.text() === ""){
            $(this).text(placeholderText);
        }
    })
});

如果您始终如一地在标签上使用 for 属性,查找要删除的相应标签应该相当容易:

$('.textarea').on("focus", function() {
  var areaId = $(this).attr("id");
  var areaLabel = $("label[for='" + areaId + "']");
  
  // Get the content from the label
  $(this).text(areaLabel.text());
  
  // Remove the label
  areaLabel.remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class='gfield_label' for='input_1_9'>Place this inside the textarea</label>
<div class='ginput_container'>
  <textarea name='input_9' id='input_1_9' class='textarea medium' tabindex='8' rows='10' cols='50'></textarea>
</div>