简体   繁体   中英

Trying to grap the input value and display, Can anyone tell me what i'm doing wrong here?

Is anyone else having trouble grabbing the input value using.value?

I usually do it like this, but doesn't seem to be working.

const getVal = document.getElementById('newtext').value;
const getBtn = document.getElementById('btn');

getBtn.addEventListener('click',displayNewText);

function displayNewText(){
    return document.getElementById('displaytext').innerHTML = getVal;
    console.log(getVal);
}


    <script src="index.js" defer></script>
</head>
<body>
    <h1>This is my first note</h1>
    <input id="newtext" type="text" value=""><br>
    <button id="btn">Press Me</button>
    <h3 id="displaytext"></h3>

You have to get.value when the function is called and console.log will never show after the return statement, so to debug do it before.

const getVal = document.getElementById('newtext');
const getBtn = document.getElementById('btn');

getBtn.addEventListener('click',displayNewText);

function displayNewText(){
    console.log("im working yey")
    return document.getElementById('displaytext').innerHTML = getVal.value;
}

The problem is that you're getting value once your code gets excuted.. hence, value = ""

To solve this problem, you have to get value whenever the button is clicked

so, just move getVal inside the function

 const getBtn = document.getElementById('btn'); getBtn.addEventListener('click', displayNewText); function displayNewText() { const getVal = document.getElementById('newtext').value; return document.getElementById('displaytext').innerHTML = getVal; }
 <h1>This is my first note</h1> <input id="newtext" type="text" value=""><br> <button id="btn">Press Me</button> <h3 id="displaytext"></h3>

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