Home > database >  How to write a function in javascript to match two words
How to write a function in javascript to match two words

Time:03-02

I am new in coding. I was working on a typing website which match the word in text field to the word shown in the website. How to write the function in Javascript. Here is what I have tried.

let displayWord = document.getElementById('word').innerHTML
let displayMessage = document.getElementById('message')
let inpWord = document.getElementById('input').value

function matchWords() {
    if(displayWord === inpWord){
        console.log('words matching')
    }   
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

</head>
<body >
    <header >
        <h1>Typing test</h1>
    </header>
    
   <div >
        <div >
            <div >
                <p >Type The Given Text</p>
                <h2  id="word">Hello</h2>
                <input  type="text" name="" id="input">
                <h4 id="message" ></h4>
            </div>
        </div>
   </div>
  
    
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u LWgxfKTRIcfu0JTxR EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</body>
</html>

CodePudding user response:

The issue is, that you grab the value when the document is loaded but at this point the value is empty.

If you change your code to this it should be updating the h4 field while you type.

let displayWord = document.getElementById("word").innerHTML;
let displayMessage = document.getElementById("message");
let inpWord = document.getElementById("input");

function matchWords() {
  if (displayWord === inpWord.value) {
    displayMessage.innerText = "words matching";
  }
}

input.addEventListener("keyup", matchWords);

CodePudding user response:

you need to call your method after an action

for sample after each key write by user in input

input.addEventListener('keyup', matchWords);

I also change innerHTML by innerText to recover #word text

let displayWord = document.getElementById('word').innerText;
let displayMessage = document.getElementById('message');
let input = document.getElementById('input');

input.addEventListener('keyup', matchWords);

function matchWords(event) {
  let target = event.target || event.srcElement;
  if (displayWord === target.value) {
    console.log('words matching')
  }
}
  <header >
    <h1>Typing test</h1>
  </header>

  <div >
    <div >
      <div >
        <p >Type The Given Text</p>
        <h2  id="word">Hello</h2>
        <input  type="text" name="" id="input">
        <h4 id="message" ></h4>
      </div>
    </div>
  </div>


  <script src="script.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u LWgxfKTRIcfu0JTxR EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>

CodePudding user response:

There are few things you need to add and change in your code

  1. Use keyUp() function to validate the input text as soon as user types. you need to call the JS function you wrote on keyUp.

    <input type="text" name="" id="input" onKeyUp="return matchWords()">

  2. You need to get the textbox value inside the validation function. It can be done by getting the value each time in the function or using event.target. I have used the first method for better understanding

  3. This is case sensitive check, which means hello and Hello do not match


Working Code

let displayWord = document.getElementById('word').innerText;
let displayMessage = document.getElementById('message');


function matchWords() {
  let inpWord = document.getElementById('input').value;
  document.getElementById('message').innerHTML = (displayWord === inpWord) ?
    'words matching' : 'words do not match';

}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

</head>

<body >
  <header >
    <h1>Typing test</h1>
  </header>

  <div >
    <div >
      <div >
        <p >Type The Given Text</p>
        <h2  id="word">Hello</h2>
        <input  type="text" name="" id="input" onKeyUp="return matchWords()">
        <h4 id="message" ></h4>
      </div>
    </div>
  </div>


  <script src="script.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u LWgxfKTRIcfu0JTxR EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</body>

</html>

CodePudding user response:

your script looks good by far, you just need to set an event handler to your input to trigger your function when user types in it.

below your code refactored with some suggestions:

  1. use const instead of let when variable is not going to change.

  2. is it better to store the HTML element that way you'll be able to do more with it.

in this case I use the input element to change its outline color and also change the message

const word = document.getElementById('word')
const message = document.getElementById('message')
const inputText = document.getElementById('input')

function matchWords() {
    if(word.innerHTML === inputText.value){
      message.innerHTML = "It does match!"
      inputText.style.outline = "1px solid green"
    } else {
      message.innerHTML = "It does not match!"
      inputText.style.outline = "1px solid red"
    }
}

inputText.onkeyup = () => matchWords()

  • Related