Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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';
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading