Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
La función sale después de ejecutar la primera condición .remove() en javascript

Estoy tratando de validar mi formulario de pago de woocommerce en la interfaz solo con javascript. La validación se ejecuta correctamente pero el problema es que la función sale después de la primera instrucción .remove().

También quiero ejecutar la segunda y tercera condición de eliminación () después de que se ejecute la primera condición de eliminación (quiero decir que todas las condiciones de eliminación deberían ejecutarse). ¿¿Alguien puede ayudar?? Adjuntando el código a continuación.

 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 Respuestas
Responde la pregunta

0

Su principal problema es que intenta eliminar un elemento sin verificar que exista.

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

fallará con un error cuando sp_billing_last_name_field no existe. Esta es mejor:

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

Pero también tienes la duplicación de código. Hagamos una función que pueda verificar cualquier campo de entrada y mostrar mensajes:

 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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda