更改占位符文本


77

如何更改输入元素的占位符文本?

例如,我有3个文本类型的输入。

<input type="text" name="Email" placeholder="Some Text">
<input type="text" name="First Name" placeholder="Some Text">
<input type="text" name="Last Name"placeholder="Some Text">

如何使用JavaScript或jQuery更改Some Text文本?


9
你尝试了$('input').attr('placeholder','Some New Text');吗?
Jeemusu 2012年

1
您是否尝试过使用javascript或jquery进行任何操作?请发布您尝试过的内容以及遇到的问题。
ryadavilli 2012年

您可以使用malarkey
未定义的

Answers:


142

如果您想使用Javascript,则可以使用getElementsByName()方法来选择input字段并placeholder为每个字段进行更改...请参见以下代码...

document.getElementsByName('Email')[0].placeholder='new text for email';
document.getElementsByName('First Name')[0].placeholder='new text for fname';
document.getElementsByName('Last Name')[0].placeholder='new text for lname';

否则使用jQuery:

$('input:text').attr('placeholder','Some New Text');

29
+1无需使用外部库就可以原生化……人们需要注意DOM API,您可能并不需要使用整个库来完成类似这样的简单操作。
Ahmad Alfy 2012年

通常该字段已经包含一个值,因此占位符将不可见。您必须清除该值。 var email = document.getElementsByName("Email")[0]; email.value=''; email.placeholder='new text for email';
askrynnikov

28

此解决方案使用jQuery。如果要对所有文本输入使用相同的占位符文本,则可以使用

$('input:text').attr('placeholder','Some New Text');

如果需要不同的占位符,则可以使用元素的ID更改占位符

$('#element1_id').attr('placeholder','Some New Text 1');
$('#element2_id').attr('placeholder','Some New Text 2');


5

使用jquery,您可以通过以下代码执行此操作:

<input type="text" id="tbxEmail" name="Email" placeholder="Some Text"/>

$('#tbxEmail').attr('placeholder','Some New Text');

4

我一直面临着同样的问题。

在JS中,首先必须清除文本输入的文本框。否则,占位符文本将不会显示。

这是我的解决方案。

document.getElementsByName("email")[0].value="";
document.getElementsByName("email")[0].placeholder="your message";

那就对了。如果不首先将该字段设置为空白,则不会显示占位符。为此花了很长时间,直到我碰到了这个职位。
User12345

0

尝试访问输入的占位符属性,并按如下所示更改其值:

$('#some_input_id').attr('placeholder','New Text Here');

如果需要,还可以清除占位符,例如:

$('#some_input_id').attr('placeholder','');

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.