简体   繁体   中英

How to get input provided in a textarea tag using JavaScript?

Have a textarea tag in form, to take input text and return the value of said text.

 <textarea id="code" name="code"></textarea>  

Using javascript to get the value, but it returns nothing. Used typeof to check if it's undefined , but typeof text gives 'string' . Is this correct way to use .value ? How to improve this?

JavaScript:

var text = document.getElementById('code').value;

document.getElementById('submit-button').onclick = function() {
    alert(text);
}; 

You're getting the value immediately when the page loads, before the user has had a chance to type anything. You want to get the value when the user clicks the button:

 document.getElementById('submit-button').onclick = function() { var text = document.getElementById('code').value; alert(text); }; 
 <textarea id="code" name="code"></textarea> <button type="button" id="submit-button">click me</button> 

You need to bind the event and get the value just when the user clicks the button.

Embrace the function addEventListener

 document.getElementById('submit-button').addEventListener('click', function() { var text = document.getElementById('code').value; console.log(text); }); 
 <textarea id="code" name="code"></textarea> <button type="button" id="submit-button">click me</button> 

Stick the var text line inside the click event; it's getting defined when the script runs originally, so it is just an empty string.

document.getElementById('submit-button').onclick = function() {
    var text = document.getElementById('code').value;
    alert(text);
};

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