Reputation: 345
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
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
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>
Upvotes: 0
Reputation: 816442
As already mentioned, IDs have to be unique. However, name
s 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