Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
How do I properly link text from an input field in HTML to JavaScript

Im tryting to make a simple palindrom checker.

When Im testing in the console it works fine. However when I try to link it with HTML I cannot get it to work. I think this is due to an error extracting the text from the input field in the HTML file...

Javascript:

const str = document.getElementById('input').value;


function reverseString(str){
    let string = str.toLowerCase();
    let splitStr = string.split('');
    let revString = splitStr.reverse('');
    let joinStr = revString.join('');
    return joinStr;
}

function compare(str){
 if (reverseString(str) === str){
        document.querySelector("#answer").innerHTML = 'Its a Palindrom';
    } else {
        document.querySelector("#answer").innerHTML =  'Its not a Palindrom';
    }
}

HTML

<body>
    <div class="checkerContainer">
        <h1 id="heading">Palendrom Checker</h1>
        <h2 id="subtext">Enter a word of phrase!</h2>
        <div id="answer">Answer will output here!</div>
        <input type="text" id="input" placeholder="Enter your word or phrase here!">
        <button type="button" id="submit" onclick="compare(str)">Check!</button>
    </div>  
</body>

When I change the compare(str) to output to the console it works fine:

const str = document.getElementById('input').value;


function reverseString(str){
    let string = str.toLowerCase();
    let splitStr = string.split('');
    let revString = splitStr.reverse('');
    let joinStr = revString.join('');
    return joinStr;
}

function compare(str){
 if (reverseString(str) === str){
        console.log('Its a Palindrom')
    } else {
        console.log('Its not a Palindrom')
    }
}
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have to retrieve the string from the input at the time you're going to test it, so you have to get it in compare. How you have it now you're getting the input value before you type in anything.

function compare(){
  const str = document.getElementById('input').value;
  if (reverseString(str) === str){
        document.querySelector("#answer").innerHTML = 'Its a Palindrom';
  } else {
        document.querySelector("#answer").innerHTML =  'Its not a Palindrom';
  }
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!