Link to home
Start Free TrialLog in
Avatar of Lawrence Barnes
Lawrence BarnesFlag for United States of America

asked on

Javascript textarea cleanup from old textarea to new textarea

Hello EE,
I am receiving a paste of item numbers into a form textarea...probably strait from Excel, but who knows.  When the user pastes or enters data into the old text area I want cleaned items to be written to a new textarea (for passing as a string.).  This form will be on IE only.  Here's the questions:  
* Can this happen live or do I need to tie this to a submit button?
* The old textarea "paste" may contain spaces, special characters, line feeds, commas.
* The new textarea should have each cleaned item set to 10 digits (zero filled or left as is if they are bigger) and  separated by a single comma (in case of multiple line feeds, spaces, etc.)

I've gotten this far, but broke something.  For adding the zeroes I figured I could use a combination of length and concat, but I don't know how to repeat the zeroes.

Any direction would be appreciated!
LVBarnes

function getItems(id) {
        var textArea = document.getElementById(id);
        var words = textArea.value.replace(/[^a-zA-Z0-9]/g, ' ').split(/\s+/);
        var words = textArea.value.replace('  ', ' ').split(/\s+/);
        document.getElementById('new').value = words.join(',');
    }
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

For padding numbers, you can use a while loop:

while (str.length < 10) {
    str = '0' + str;
}

Open in new window

Avatar of Lawrence Barnes

ASKER

Thanks...can you help me get that into the function above?
I'm not very good with regular expressions, but in your function you are declaring the variable words twice. The second declaration is overwriting the first. You should fix that, I'm not sure what you are trying to accomplish there.

Once you have the words array set up properly, you can insert before your last line:

for (var i = 0; i < words.length; i++) {
    word = words[i];
    while (word.length < 10) {
        word = '0' + word;
    }
    words[i] = word;
}

Open in new window

Also, you can attach this script to an onchange event on your input textarea element without having a button, but you would have to click outside the textarea or tab outside it for the script to execute.
Here's my goal:
*****Input by user into textarea *****
12345,54321  23451
512#

45123
*****************************************
******Javascript writes cleaned up and zero filled string into a different textarea****
0000012345,0000054321,0000023451,00000512,0000045123
****************************************************************************
ASKER CERTIFIED SOLUTION
Avatar of Kim Walker
Kim Walker
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you!