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

125
Visualizações
Function exits after executing the first .remove() condition in javascript

I am trying to validate my woocommerce checkout form on the frontend only with javascript. The validation executes correctly but the problem is that the function exits after the first .remove() statement.

I want to execute the second, third remove() condition as well after the first remove() condition is executed (I mean all the remove conditions should run). Can anyone help?? Attaching the code below.

function myFunction() { 

  // for name
let n = document.getElementById("billing_first_name").value;
  
  if ( n.length < 3 || n == '' ) {
    var n1 = document.getElementById('billing_first_name'); 
        if(!document.getElementById("sp_billing_first_name_field")){  
         n1.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_first_name_field"> This is test</p>');           
    }     
  }

  else {
         document.getElementById('sp_billing_first_name_field').remove() ; 
    
          }


  // Last name
  let n2 = document.getElementById("billing_last_name").value;
  if ( n2.length < 3 || n2 == '' ) {
   var n21 = document.getElementById('billing_last_name');
    if(!document.getElementById("sp_billing_last_name_field")){  
    n21.insertAdjacentHTML('afterend', '<p class="sp-error-notice" id="sp_billing_last_name_field">お名前(姓・名)は必ず入力してください。</p>');  
    }
  }
  else {

    document.getElementById('sp_billing_last_name_field').remove();
    
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Your main issue is that you try to remove an element without checking that it exists.

document.getElementById('sp_billing_last_name_field').remove();

will fail with an error when sp_billing_last_name_field does not exist. This is better:

let hint = document.getElementById('sp_billing_last_name_field');
if (hint) hint.remove();

But you also have code duplication. Let's make a function that can check any input field and show messages:

function checkField(fieldId, condition, message) {
  document.getElementById(fieldId).addEventListener("input", function () {
    let isInvalid = condition(this.value);
    let hint = this.nextElementSibling;
    if (hint && !hint.classList.contains("sp-error-notice")) hint = null;
    if (!hint && isInvalid) {
      this.insertAdjacentHTML('afterend', '<p class="sp-error-notice">' + message + '</p>');
    } else if (hint && !isInvalid) {
      hint.remove();
    }
  });
}

checkField("billing_first_name", v => v.length < 3, "ダメよ");
checkField("billing_last_name", v => v.length < 3, "お名前(姓・名)は必ず入力してください。");
p.sp-error-notice {
  display: inline-block;
  color: red; margin: 0 0 0 10px;
}
<div><input id="billing_first_name"></div>
<div><input id="billing_last_name"></div>

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