Alex Gold
Alex Gold

Reputation: 345

Using a variable in the form name of DOM

This appears to be something that's easy when you know it but hard to figure out. The code should be pretty self-explanatory:

<html>
<head>
<body>

<form id='updatenotes_1139' action=index.php method=POST>
<input size=20 type='input' id='b_user' value="Default value">
<input type=submit>
</form>

<script>
var entered = 1139;
var formName = "updatenotes_"+entered;
//alert(formName);  // Displays "updatenotes_1139"
document.forms[formName]b_user.value = "Hello!";
</script>
</body>
</html>

The basic idea is to be able to tell JavaScript what form to edit via a variable. I can't just use GetElementByID because in the full application there are many forms with the same name of input (e.g., 15 forms that each have a "b_user" input). This is mainly so that the browser's autocomplete will function across all of them (it's just a script for me, so it doesn't have to be pretty so long as it works).

For what it's worth, the alert there works just fine. I just have no idea how to construct the next line, as all the examples I could find online were about using a variable on the input id and not the form id.

Upvotes: 1

Views: 1873

Answers (4)

Bruno
Bruno

Reputation: 5822

With an id I first tried using this code to access the form via its id

document[ "formID" ]; // returned undefined

However, when I used the following code it returned the correct form

window[ "formID" ]; // returned form element

Not really sure whether this is best practice. Anyhow, here is the code I ended up with.

var entered = 1139;
var formID = "updatenotes_" + entered;
window[formID].b_user.value = "Hello!";

Fiddle here

Upvotes: 0

Sachin Jain
Sachin Jain

Reputation: 21842

DO you want something like this

<html>
<head>
<body>

<form id='updatenotes_1139' action=index.php method=POST>
<input size=20 type='input' id='b_user' value="Default value">
<input type=submit>
</form>

<script>
var entered = 1139;
var formName = "updatenotes_"+entered;
//alert(formName);  // Displays "updatenotes_1139"
var myForm = document.forms[formName];
  console.log(myForm);
  myForm.getElementsByTagName('input')[0].value = "Hello!";
</script>
</body>
</html>

Working BIN

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816442

As already mentioned, IDs have to be unique. However, names don't have to be. Change your HTML to:

<input size=20 type='input' name='b_user' value="Default value">

(or keep the id attribute, but you need name)

Then you can do:

var form = document.getElementById(formName);
var b_user = form.getElementsByName('b_user')[0];
b_user.value = 'Hello';

Upvotes: 0

dsgriffin
dsgriffin

Reputation: 68596

document.forms[formName].b_user.value = "Hello!"; 
                     // ^ This is how you'd access it.

jsFiddle.

Upvotes: 1

Related Questions