Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

218
Visualizações
How to write a function in javascript to match two words

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/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

</head>
<body class="bg-secondary text-white">
    <header class="text-center p-2 bg-dark ">
        <h1>Typing test</h1>
    </header>
    
   <div class="container text-center">
        <div class="row">
            <div class="col-md-6 mx-auto">
                <p class="p-4">Type The Given Text</p>
                <h2 class="word pb-4" id="word">Hello</h2>
                <input class="form-control form-control-lg" type="text" name="" id="input">
                <h4 id="message" class="p-4"></h4>
            </div>
        </div>
   </div>
  
    
<script src="script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.min.js" integrity="sha384-cVKIPhGWiC2Al4u+LWgxfKTRIcfu0JTxR+EQDz/bgldoEyl4H0zUF0QKbrJ0EcQF" crossorigin="anonymous"></script>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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()

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda