用户在输入字段中单击,该值消失

时间:2015-06-17 12:01:10

标签: javascript jquery html

我搜索脚本以消除输入字段中的值。 用户点击进入并且值消失,如果用户没有在输入字段中写入内容,则应该再次显示该文本。

我尝试使用jQuery和focusin()focusout(),但后来我改变了所有输入字段的值。

3 个答案:

答案 0 :(得分:5)

我打赌你正在寻找HTML5属性placeholder提供的机制,只需这样使用它:

<input type="text" placeholder="This value will disappear" name="somename" value="" />

对于textarea的多行占位符,请检查以下方法:

https://stackoverflow.com/a/25261886/1477938

答案 1 :(得分:2)

您可以使用占位符,否则您可以使用值作为占位符。看看吧

Placeholder based Value

jQuery(document).ready(function(){
    jQuery("input[type='text']").each(function(){
        var x = jQuery(this).attr("value");
        jQuery(this).focus(function(){
            if($(this).val()==x)
            {
                $(this).val('');
            }       
        });
        jQuery(this).blur(function(){
            if($(this).val()=="")
            {
                $(this).val(x);
            }
        });
    });
});

使用占位符

<input type="text" placeholder="test">

答案 2 :(得分:0)

您可以使用占位符属性。

$(document).ready(function() {
  $('#input').focus(
    function() {
      if (!$(this).val().length || $(this).val() == $(this).data('placeholder')) {
        $(this).val('');
      }
    }
  );

  $('#input').blur(
    function() {
      if (!$(this).val().length) {
        $(this).val($(this).data('placeholder'));
      }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Text here" />
<br/>
<hr/>

<b>ALTERNATIVE (jQuery):</b>
<br/>

<input type="text" id="input" data-placeholder="Text here" value="Text here" />