Reputation: 41
i got the following function:
function add() {
for (var i = 0; i < 49; i++) {
var b = Math.floor(Math.random() * 50) + 1;
document.getElementById("tt5").innerHTML += b + " ";
}
}
after click on button --> 50 different integers (from 1-50) will be outputted in textarea("tt5")
but now I got like 2 additional textareas, with the same id="tt5",
but it's not affecting them at all...
<button onclick="add()">OK</button>
<textarea class="textarea2" name="t5" id="tt5"></textarea>
<textarea class="textarea3" name="t5" id="tt5"></textarea>
<textarea class="textarea4" name="t5" id="tt5"></textarea>
I want all textareas, to be filled with the add-function()
Upvotes: 0
Views: 21
Reputation: 218960
You got something key backwards in your markup. You're using unique classes and non-unique ids. It should be the other way around:
<textarea class="textarea" name="t5" id="tt1"></textarea>
<textarea class="textarea" name="t5" id="tt2"></textarea>
<textarea class="textarea" name="t5" id="tt3"></textarea>
This is because any id
in the DOM needs to be unique ("id" is short for "identifier"). But you can apply classes anywhere you like. Then you can use a different function to get an array of matching elements:
var textareas = document.document.getElementsByClassName("textarea");
for (var j = 0; j < textareas.length; j++) {
textareas[j].innerHTML += b + " ";
}
There are some more advanced ways of applying something across multiple elements or applying a function multiple times to an array, but as you're already familiar with loops and such this should at least be enough to get started. Note also that repeating name
values may have unexpected consequences if you're submitting a form at all. The key/value pairs sent to the server need unique names.
Upvotes: 1