View Full Version : Mirror textbox doesn't work on second try

07-01-2011, 10:17 AM

I'm trying to mirror two textboxes with the following:

<input type="text" id="0" name="tb1[]" onkeyup="document.getElementsByName('tb2[]')[this.id].setAttribute('value',this.value)">

<input type="text" id="0" name="tb2[]" onkeyup="document.getElementsByName('tb1[]')[this.id].setAttribute('value',this.value)">

If I start by picking the first box and typing it appears automatically in the second textbox. It works the same if if i start by picking the second box. However after entering text into one of the textboxes and having it mirrored, if I select the other textbox and make a change it isn't mirrored.

Any suggestions? Thanks!

07-01-2011, 10:39 AM
You stumbled upon the difference between attributes and properties which is not always obvious in browsers.

If you use setAttribute('value', '...') you set the attribute "value" for an element. But if you use .value on an attribute, you get or set the property "value" of the element.

Let's take a look at the difference
1. Assuming that the element has a value of "abc" the browser will render the value into the element and internally copy "abc" to the property "value"
2. Now if you change the attribute "value" afterwards it will not change the property and will therefore not be visible in the element
3. But if you set the property with .value, it will be visible because it's the property

So try this

<input type="text" id="0" name="tb1[]" onkeyup="document.getElementsByName('tb2[]')[this.id].value = this.value">

<input type="text" id="0" name="tb2[]" onkeyup="document.getElementsByName('tb1[]')[this.id].value = this.value">