更改占位符文本

105

如何更改输入框的占位文本?

例如,我有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更改某些文本文本?


9
你尝试过 $('input').attr('placeholder','Some New Text'); 吗? - Jeemusu
1
你有尝试使用JavaScript或jQuery吗?请发布你已经尝试过的内容以及你面临的问题。 - Ravi Y
1
你可以使用胡言乱语。 - undefined
8个回答

192

如果你想使用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');

39
不使用外部库而直接运用本地工具,点赞!人们需要关注DOM API,或许做一些简单的事情并不需要用整个库。 - Ahmad Alfy
1
通常该字段已经包含一个值,因此占位符将不可见。您必须清除该值。var email = document.getElementsByName("Email")[0]; email.value=''; email.placeholder='电子邮件的新文本'; - askrynnikov

30

这个解决方案使用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');

17
var input = document.getElementById ("IdofInput");
input.placeholder = "No need to fill this field";

您可以在这里了解更多关于 placeholder 的信息:http://help.dottoro.com/ljgugboo.php


6
使用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

2
在你的Javascript文件中: document.getElementsByName('Email')[0].placeholder = '新的邮箱文本';

目前来说,您的回答不是很清晰。请进行[编辑]以添加额外细节,从而帮助其他人理解该回答如何解决问题。您可以在帮助中心找到更多编写良好回答的信息。 - Community

1
尝试访问输入框的占位符属性并像下面这样更改其值:
$('#some_input_id').attr('placeholder','New Text Here');

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

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

1

对于 JavaScript,请使用:

document.getElementsByClassName('select-holder')[0].placeholder = "This is my new text";

使用jQuery:

$('.select-holder')[0].placeholder = "This is my new text";

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接