如何使文本框显示一个值,但单击时,显示另一个值?

时间:2014-08-13 19:14:38

标签: javascript jquery html input textbox

我希望有一个文本框,默认情况下包含“在此处输入文字”之类的内容,但在点击时,另一个单词将采用默认值的位置。

到目前为止,我只包含显示默认值的代码:

<input type="text" name="phrase" value="Enter text here..." size="24" onfocus="if(this.value == 'Enter text here...') { this.value = ''; }" onBlur="if(this.value == '') {this.value='Enter text here...';}">

4 个答案:

答案 0 :(得分:1)

您应该使用placeholder作为关注焦点的文字:

<input type="text" data-default="Default" placeholder="Enter text here..." />

我使用data-default来保存将替换占位符的默认值

鉴于此,下面的代码将输入值设置为data-default:

$(funcion(){
  $(input).on('click', function(){
      var $this = $(this),
          defaultValue = $this.data('default');

    if(defaultValue) $this.val(defaultValue);
  })  
 });

这是一个小提琴:http://jsfiddle.net/z4mhqgjg/

答案 1 :(得分:0)

你的意思是 this

$('input').focus(function(){
    $(this).val('New Text');
});
$('input').blur(function(){
    $(this).val('Default Text');
});

答案 2 :(得分:0)

查看以下代码段:

<input type="text" name="phrase" value="Enter text here..." size="24" onfocus="if(this.value == 'Enter text here...') { this.value = 'New Value goes here'; }" onBlur="if(this.value == '' || this.value == 'New Value goes here') {this.value='Enter text here...';}" onkeypress="if(this.value == 'New Value goes here') { this.value = ''; }" >

这就是你需要的。演示:http://jsbin.com/homapa

答案 3 :(得分:0)

使用jQuery,您可以使用.focusin()事件处理程序来更改输入的值。

它看起来像这样:

HTML:

<input type="text" id="mybox" name="phrase" value="Enter text here..." size="24"/>

使用Javascript:

$('#mybox').focusin(function() {
    $(this).val('your new text here');
});

这里使用.focusout()的JSFiddle演示:http://jsfiddle.net/jpreynat/f9ffudof/8/