简体   繁体   中英

Get TextArea Input Value in form of array and forEach loop the value in console.log Using Javascript

function someSample() {
    let textAreaTag = document.getElementById('textAreaId');
    let textAreaVal = textAreaTag.value;
    let textAreaSplit = textAreaVal.split('');
    
    textAreaTag.addEventListener('input', () => {
        textAreaSplit.forEach((val, ind) => {
            console.log(val);
        });
    }); 
}   

someSample();

在此处输入图像描述

There is on textarea input field, so first i gave a addEventListener while typing any text in textarea the value of text area text should get forEach Loop and the loop array should show inside console.log.. But now the loop array is showing blank or undefined.

All you need to do is move 2 lines of code.

someSample is getting the initial value of the textarea, which will be an empty string. Then it is adding an event listener, which will fire every time the input changes in the text area. The problem is that you're not updating textAreaVal with every input change, and you're simply using the initial empty string. On input change, you need to get the value, split the value, then loop through. someSample should look like this:

function someSample() {
    let textAreaTag = document.getElementById('textAreaId');
    
    textAreaTag.addEventListener('input', () => {
        let textAreaVal = textAreaTag.value;
        let textAreaSplit = textAreaVal.split('');
        textAreaSplit.forEach((val, ind) => {
            console.log(val);
        });
    }); 
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM