/    Sign up×
Community /Pin to ProfileBookmark

Add element to all forms

I’m trying to add an input element to [b]all[/b] forms using appendChild.

The script first searches for input elements with the name of “myinput”.

If it finds an input element with that name, it assigns the value “myvalue”.

If it can’t find an input element with that name, it tries to create a new one for all forms.

[code]
if (document.getElementsByName(‘myinput’)) {
var testcode = document.getElementsByName(‘myinput’);
for (var i=0; i < testcode.length; i++){
testcode[i].value = “myvalue”;}
}

else {
var z = document.createElement(“input”);
z.type = “hidden”;
z.name = “myinput”;
z.value = “myvalue”;
z.id = “mycode”;
var d = document.getElementsByTagName(‘form’);
for (var i=0; i < d.length; i++){
d.appendChild(z);}
}
[/code]

What’s wrong with my code?

Thanks!

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@slaughtersNov 05.2009 — getElementsByName is valid for (X)HTML documents, but tends to act different depending on what XHTML version you are talking about. For example, as of XHTML 1.0 the use of the name attribute was deprecated on <a>, <applet>, <form>, <frame>, <iframe>, <img>, and <map> :

https://developer.mozilla.org/en/document.getElementsByName

It also tends to be a little "funky" in IE7 if something else has an ID with the same value as the name.

I tend to stick with getElementById and just look at the name "attribute" of the object. You can use document.getElementsByTagName to limit your self to scanning for "input" tags instead of every element in the DOM.

*Edit*

P.S. - The[COLOR="Red"] z.id = "mycode"; [/COLOR]bit in your code can end up giving the same id to multiple objects
×

Success!

Help @four0four spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.22,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...