wellerweb's question

by James Long

HTML

<!-- Better IDs will help you remember what your elements are meant for. -->
<div> 
    <input type="text" id="value1" />
</div> 

<div>
<input type="text" id="value2" />
</div>
    
<div> 
    <textarea id="combo"></textarea> 
</div> 

<div> 
    <textarea id="overspill"></textarea> 
</div> 

<!-- Keep your HTML and JavaScript seperate as much as possible. -->
<div>
<button id="transfer">Transfer Text</button>
</div>

JavaScript

// The DOMContentLoaded event is better than the window onload event because
// it fires before the images have loaded. This check ensures that only 
// browsers that understand the event will use it and browsers that don't 
// will not throw any errors.
document.addEventListener && document.addEventListener('DOMContentLoaded', function () {
    
    // Anything that's likely to change should be placed in a config variable
    // so you and any future developer can easy tweak it.
    var config = {
            val1: 'value one: ',
            val2: 'value two: ',
            space: '\n',
            limit: 200
        },
    
    // It's worth storing the DOM elements that you wish to use because it's
    // faster to find them once and keep referencing them than to constantly
    // re-look them up.
        input1    = document.getElementById('value1'),
        input2    = document.getElementById('value2'),
        combo     = document.getElementById('combo'),
        overspill = document.getElementById('overspill'),
        transfer  = document.getElementById('transfer');
    
    // This function handles the textarea value setting.
    function populateTextareas() {
        
        var value1  = input1.value,
            value2  = input2.value,
            string  = config.val1 + input1.value + config.space +
                config.val2 + input2.value,
            string2 = '';
        
        // This is the key part of the function. If the "string" variable is
        // too long, we set "string2" to the extra bit, then reduce string to
        // the limit.
        if (string.length > config.limit) {
            
            string2 = string.slice(config.limit);
            string  = string.substr(0, config.limit);
            
        }
        
        // All we need to do after the if statement has done it's work is
        // populate the textareas with whatever our strings ended up being.
        combo.value     = string;
        overspill.value =...