[Javascript] Retaining values

Paul Novitski paul at juniperwebcraft.com
Tue Apr 12 00:47:34 CDT 2011


tedd wrote:
>http://www.webbytedd.com/aa/add-text-field/index.php
>http://www.webbytedd.com/aa/add-text-field/a.js
>
>Please follow these steps:
>
>1. Enter 'a' in the first input box.
>2. Click "Add Another Field". Note 'a' remains in the first input box.
>3. Enter 'b' in the newly generated input box.
>4. Click "Add Another Field". Please note that the value 'b' is now gone.
>
>You see, the Click "Add Another Field" has voided that new text box.
>
>So, how can this form be such that a user can enter data in a "new" 
>field and then Click "Add Another Field" and have that data remain?
>
>If you will note, this happens to all newly created text boxes -- 
>they simply do not retain their values.


Hey tedd, long time no post~

I believe your problem is the way you're adding the new fields:

>document.getElementById('text').innerHTML += "<input ...

Internally, in this context, these statements are equivalent:

         a += b
         a = a + b

or in your case:

         text.innerHTML += b
means:
         text.innerHTML = text.innerHTML + b

By using the += operator you're effectively replacing the contents of 
div#text each time. The innerHTML property on the right-hand side of 
the assignment statement gives you the markup of the current input 
fields, not any value already entered by the user. You're not just 
adding a new input field each time, you're also recreating all the 
ones you've already added and hence losing user input.

I recommend that you use the DOM functions createElement() and 
appendChild() to insert the new element without stomping on what 
you've previously inserted.

document.createElement
https://developer.mozilla.org/en/DOM/document.createElement

Node.appendChild
https://developer.mozilla.org/En/DOM/Node.appendChild

Your script is an excellent example of the pitfalls of innerHTML. 
It's seductively simple to use but it doesn't honor internal values 
within the DOM, only the HTML exoskeleton.

Regards,

Paul
__________________________

Paul Novitski
Juniper Webcraft Ltd.
http://juniperwebcraft.com

co-author, JavaScript Bible 7th Edition
http://wiley.com/WileyCDA/WileyTitle/productCd-0470526912.html 



More information about the Javascript mailing list