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

Time:09-02

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>

CodePudding user response:

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

CodePudding user response:

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>

  • Related