0

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);
}; 
0

3 Answers 3

1

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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>

1 Comment

I was just informed that I have a scope issue. I was defining a variable that I thought I could put in a function. However I am told that because this is a callback the rules are a bit different.
0

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);
};

1 Comment

Thanks! this did it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.