简体   繁体   中英

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.

This is the html for the form field:

<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.

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/

If you want for all tags of form then you can find all tags of form and add this via for loop.

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

If you need to constrain it into a form try

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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