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

267
Vistas
Cómo detectar la longitud del valor de entrada usando MutationObserver

Necesito hacer un campo de entrada de texto (número de teléfono) de al menos 10 dígitos durante el pago con Bigcommerce. Estoy usando MutationObserver y se observa el campo de entrada, pero no puedo detectar los cambios. Por favor, vea el código a continuación:

 <script> (function(win) { 'use strict'; var listeners = [], doc = win.document, MutationObserver = win.MutationObserver || win.WebKitMutationObserver, observer; function ready(selector, fn) { // Store the selector and callback to be monitored listeners.push({ selector: selector, fn: fn }); if (!observer) { // Watch for changes in the document observer = new MutationObserver(check); observer.observe(doc.documentElement, { childList: true, subtree: true }); } // Check if the element is currently in the DOM check(); } function check() { // Check the DOM for elements matching a stored selector for (var i = 0, len = listeners.length, listener, elements; i < len; i++) { listener = listeners[i]; // Query for elements matching the specified selector elements = doc.querySelectorAll(listener.selector); for (var j = 0, jLen = elements.length, element; j < jLen; j++) { element = elements[j]; // Make sure the callback isn't invoked with the // same element more than once if (!element.ready) { element.ready = true; // Invoke the callback with the element listener.fn.call(element, element); } } } } // Expose `ready` win.ready = ready; })(this); ready('#phoneInput', function(element) { // do something if (element.value.length < 10) { element.style.borderColor = 'red'; return; } // otherwise, set it to green element.style.borderColor = 'green'; }); </script>

La idea es que el usuario reciba una alerta si el valor del campo de entrada tiene menos de 10 dígitos cada vez que el usuario termina de escribir y coloca el foco en un campo diferente. Gracias de antemano. Otras ideas son bienvenidas y apreciadas.

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

Puedes lograr lo que quieras sin usar el observador:

 ready('#phoneInput', function (element) { element.addEventListener("input", function (e) { if (e.target.value.length < 10) { element.style.borderColor = 'red'; return; } // otherwise, set it to green element.style.borderColor = 'green'; }); });

Si tiene que usar el observador, movería sus condiciones configurando borderColor a su función de verificación:

 if (!element.ready) { element.ready = true; // Invoke the callback with the element listener.fn.call(element, element); } else { // do something if (element.value.length < 10) { element.style.borderColor = 'red'; return; } // otherwise, set it to green element.style.borderColor = 'green'; }

y agregue un detector de eventos a su sección lista:

 ready('#phoneInput', function (element) { element.addEventListener("input", function (e) { element.setAttribute("value", e.target.value) }); });

Deberá agregar atributos a sus opciones de observador:

 observer.observe(doc.documentElement, { childList: true, subtree: true, attributes: true });

Nota: Creo que esto puede ser un duplicado o un problema similar a Detectar el cambio de valor de entrada con MutationObserver . ¿Puede haber algunas sugerencias útiles que respondan a su pregunta en ese hilo? :)

about 4 years ago · Santiago Gelvez 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