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

179
Visualizações
trying to get my if statement inside of the button to run every time I press the button
var test = document.getElementById("start").innerHTML;

document.getElementById("submit").onclick = function()
   
{
    var textinput = document.getElementById("inputbox").value;
    
    console.log(textinput)
    
    if(textinput.charAt(0) == test.slice(-1) )
    {
        document.getElementById("start").innerHTML = document.getElementById("start").innerHTML.replace(test,textinput)
    }



}

I am trying to figure out why whenever I press the button on my html site I only get the if statement to run once. My goal is to swap a piece of text on my html site every time the last letter is the same as the first letter of whatever text is written inside of an input box and the button is pressed but it only works for one button press for some reason

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

0

It's because you declare var test = document.getElementById("start").innerHTML; outside of the onclick function. So it is only run once and its value is never updated.

Put it inside the function to get its new value every time you press the button.

document.getElementById("submit").onclick = function(e) {
  e.preventDefault();
  const textinput = document.getElementById("inputbox").value;
  const test = document.getElementById("start").innerHTML;

  console.log(textinput)

  if (textinput.charAt(0) == test.slice(-1)) {
    document.getElementById("start").innerHTML = document.getElementById("start").innerHTML.replace(test, textinput)
  }



}
<span id="start">Somebody once told me the world is gonna roll me</span>

<form>
  <input type="text" id="inputbox" />
  <button id="submit">Submit</button>
</form>

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