In this code there is an error, in your HTML, the textarea
has no attribute name
, only the id
, setado to "02"
, but in your Javascript you try to find it by name
, really never will. But even if you fix this error, there is one more problem. As already said, the function getElementsByName
returns a list of elements, i.e., you will need to locate the element you want, in this case it is at index 0, but if you have another element as the same property name
(of the same TAG, or different) before it, you will get an error because the index 0 will not be the element you want.
The most interesting thing is that you use the native functions Document.querySelector or Document.querySelectorAll, to make more specific CSS selections. In your case you can use
document.querySelector('input[name="01"]')
instead of document.getElementsByName("01")
, that will return a Nodeelement and you will be able to access the property value
. This selection ensures that the result will be a TAG element input
and attribute name="01"
, thing that the getElementsByName
doesn’t make.
Here is the corrected example
function t() {
var t1 = document.querySelector('input[name="01"]');
var t2 = document.querySelector('textarea[name="02"]');
t2.value = t1.value;
};
<input type='text' name='01'/><br>
<button onclick='t()'>CONFIRMAR</button><br>
<textarea name='02'></textarea>
Remember that if you do not want to specify the element TAG in the CSS selection, you can use asterisk in this way: '*[name="01"]'
. More examples of CSS selections you can see in W3scools: CSS Attribute Selectors and CSS Selectors
So if I go get elements with different names I keep how
[0]
for the first? exampledocument.getElementsByName("nome")[0].value
anddocument.getElementsByName("sobrenome")[0].value
– user117425
Yes, exactly. The
[0]
takes the first one with the specified name.– Sam