2012-07-11 78 views
2

我想通过jQuery将value属性更改为占位符。所以结果会是这样的将值更改为占位符(输入字段)

原始

<input type="text" value="Enter name" /> 

我想改变上面

<input type="text" placeholder="Enter name" /> 

我只找到了改变的“”而不是实际工作中的文字解决方案那些之前的文本。所以replaceWith,replaceAll does not似乎工作。

有人有一个想法如何解决这个问题?

回答

12

您可以使用

.removeAttr('value')删除属性

例子:

$('input[type=text]').removeAttr('value'); 

,并添加新的属性与

.attr('placeholder','Enter name')

实施例:

$('input[type=text]').attr('placeholder','Enter name'); 

如所建议的通过rcdmk

您可能做到这一点链的方法:

$('input[type="text"]').each(function() { 
     var $this = $(this); 
     $this.attr("placeholder", $this.attr("value")).removeAttr("value"); 
    }); 
+4

我会添加一个答案,但这很适合。每一个函数(){var $ this = $(this); $ this.attr(“placeholder()); “,$ this.attr(”value“))。removeAttr(”value“);});' – rcdmk 2012-07-11 12:10:00

+0

@rcdmk:谢谢,并加入我的答案。 – 2012-07-11 12:17:33

+1

谢谢,像一个魅力工作! – JohnSmith 2012-07-11 12:24:02

0
<input type="text" id="searchInput" value="enter text..."> 

var plcehldr = "enter text...";  
$("#searchInput").focusin(function() { 
    $(this).removeAttr("value"); 
}); 

$("#searchInput").focusout(function() { 
    $(this).attr("value",plcehldr); 
}); 

http://jsfiddle.net/ipsjolly/2qutf/14/