Reputation: 3113
I want to copy the input value in "Round 1" to "Round 2" using javascript. My "Round 2" values will really be empty, but for debugging I have given them values.
I think the line in my JS i2 = i1;
needs to be enhanced but cannot figure out how. I've tried using ".innerHTML" for example, but no luck.
Html:
<div id="round1">
<input type="text" name="partner1" value="name1" />
<input type="text" name="partner2" value="name2" />
</div>
<div id="round2">
<input type="text" readonly name="partner1" value="name3" />
<input type="text" readonly name="partner2" value="name4" />
</div>
JS:
var r1 = document.getElementById("round1");
var i1 = r1.getElementsByTagName("input")[0].value;
alert(i1);
var r2 = document.getElementById("round2");
var i2 = r2.getElementsByTagName("input")[1].value;
alert(i2);
i2 = i1;
Upvotes: 0
Views: 663
Reputation: 254
When you set i1 and i2 initially, you extracted the strings in each by value. This is important because i1 and i2 each represent a copy of the value of each form element, not the value of the element itself.
You could skip declaring the i
variables separately and instead put:
r2.getElementsByTagName("input")[1].value=r1.getElementsByTagName("input")[0].value;
Of course, you can skip the intermediate steps entirely and do everything at the same time:
document.getElementById("round2").getElementsByTagName("input")[1].value = document.getElementById("round1").getElementsByTagName("input")[0].value;
Upvotes: 2
Reputation: 11
what you are storing in i2 and i1 is value of the elements and not the reference to the elements, that's why your code is not working, what you can do is store the element in the variables and exchange the value of those elements, like this:
var r1 = document.getElementById("round1");
var i1 = r1.getElementsByTagName("input")[0];
alert(i1.value);
var r2 = document.getElementById("round2");
var i2 = r2.getElementsByTagName("input")[1];
alert(i2.value);
i2.value = i1.value;
Values in JS are copied to new variables and elements are passed by reference, this means that even if you have them in variables, if you edit them, the result will impact on the html code.
hope it helps !
Upvotes: 1
Reputation: 571
I think your JS code needs to be something like this...
var r1 = document.getElementById("round1");
var i1 = r1.getElementsByTagName("input")[0];
alert(i1.value);
var r2 = document.getElementById("round2");
var i2 = r2.getElementsByTagName("input")[0];
alert(i2.value);
i2.value = i1.value;
The issue with your original code was that you were getting the value of the fields in to vars and not references to the fields themselves.
Upvotes: 1