简体   繁体   English

使用javascript设置表单字段占位符属性

[英]Set form field placeholder attribute using javascript

I am trying to set the placeholder attribute for a form which I do not have access to. 我正在尝试为我无权访问的表单设置占位符属性。 I would like to use the name of the field to populate this. 我想使用字段名称来填充它。 Does anyone know of a way to do this using javascript. 有谁知道使用javascript做到这一点的方法。

This is the html for the form field: 这是表单字段的html:

<input type="text" onchange="checkdep(this);" onblur="validatefield(this);" value="" name="First Name" class="formTextfield" id="First_Name">

I am able to do this using getElementById but would like something which works for all the fields in the form without having to set it individually for each field. 我可以使用getElementById来执行此操作,但需要某种适用于表单中所有字段的方法,而不必为每个字段分别进行设置。

http://jsfiddle.net/XF6wT/5/ http://jsfiddle.net/XF6wT/5/

Thanks 谢谢

You should use: 您应该使用:

document.getElementById("First_Name").setAttribute('placeholder', document.getElementById("First_Name").getAttribute("name"));

do you need this ... I am not sure.. 你需要这个吗...我不确定..

check this: 检查一下:

Update: http://jsfiddle.net/XF6wT/6/ 更新: http//jsfiddle.net/XF6wT/6/

If you want for all tags of form then you can find all tags of form and add this via for loop. 如果要获取表单的所有标签,则可以找到表单的所有标签,然后通过for循环添加它。

Try some thing like this 试试这样的事情

var inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
   inputs[index].setAttribute('placeholder', inputs[index].getAttribute("name"));
}

JsFiddle JsFiddle

If you need to constrain it into a form try 如果您需要将其限制为表单,请尝试

var inputs = document.forms["form_name"].getElementsByTagName("input");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM