Algunas de mis preguntas con respecto a este bit de código.
Qué está ocurriendo exactamente en estas líneas de código:
confirmPassword.oninput = function() { checkpassword(confirmPassword.value); }
¿Cuál es el propósito de (f)
en esta línea de código:
checkpassword(f)
confirmPassword.oninput = function() { checkpassword(confirmPassword.value); } function checkpassword(f) { if (password.value !== f) { addWarning(); } if (password.value === f) { confirmPasswordError.textContent = ''; } }
Este código no sigue muy buenas prácticas de codificación, ya que usa funciones impuras, y el nombre de las variables no se explica por sí mismo.
Esto debería ser mejor:
confirmPassword.oninput = function() { checkpassword(password.value, this.value); } function checkpassword(pwd, confirmPwd) { if (pwd !== confirmPwd) addWarning(); else confirmPasswordError.textContent = ''; }
Este debería ser tu script completo:
const password = document.getElementById("password"); const confirmPassword = document.getElementById("confirm-password"); // Assuming your HTML code has: // <input id="password" type="password" /> // <input id="confirm-password" type="password" /> // HTMLElement.onevent = function // is equivalent to : // HTMLElement.addEventListener(event, function) // in this case you are assigning a function to be executed when your // passwordConfirm element receives new inputs // ( key strokes on input focus ) // At each key stroke the anonymus function you assigned to .oninput // is being called, checkPassword function is being called // with two parameters, the first one is the value of the first input // box, the original password string value, the second parameter is the // value of confirmPassword input box. // Those two walues are being compared to be sure that both original and // confirmation passwords are the same. confirmPassword.oninput = function() { checkpassword(password.value, this.value); } function checkpassword(pwd, confirmPwd) { if (pwd !== confirmPwd) addWarning(); else confirmPasswordError.textContent = ''; }
El primer bloque de código se usa para adjuntar una función al detector de eventos "oninput" del elemento <input>
que ha almacenado en el elemento confirmPassword
. (Puede leer más sobre el evento "oninput" aquí mismo)
Entonces, cuando la entrada/contenido del elemento <input>
cambie, se llamará a la función que adjuntó, y esa función, a su vez, llama a la función checkpassword
. Y el valor/contenido de este elemento se pasa a la función de checkpassword
de contraseña.
confirmPassword.oninput = function() { // You are attaching a function to an event listener! // // The "oninput" event is fired when your <input> // element's (the one stored in the "confirmPassword" // variable) value changes. // checkpassword(confirmPassword.value); // ^^^ Pass the value of the input element // to the first variable/argument of the // function "checkpassword" }
En cuanto a lo que significa la f
dentro del segundo bloque de código, se usa para almacenar el valor que pasó a la función en el primer bloque de código.
function checkpassword(f) { // ^ The first function argument/variable // (It holds the value of your input // field in this case) ... }
Nota al margen: parece que eres bastante nuevo en JS. Intente usar algunos sitios web gratuitos para comprender mejor este idioma. (Recomiendo usar sololearn o w3schools )
f
es un parámetro, puede reemplazarlo y todas las ocurrencias en esa función con password
y seguirá haciendo lo mismo. Está comprobando el texto introducido para las cosas. Si no hubiera ningún parámetro, entonces no podrían hacer este código o verificar el texto porque tendrían que hacer trillones de funciones para cada combinación de caracteres posible.
Puede llamar a esa función usando f
usando checkpassword("example"); entonces f
sería igual a example
.
El primer evento ejecuta la función checkPassword con su valor cuando se ingresa la entrada del formulario.
Más información sobre parámetros:
https://developer.mozilla.org/en-US/docs/Glossary/Parameter https://www.w3schools.com/js/js_function_parameters.asp
Más información sobre oninput:
https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/oninput https://www.w3schools.com/jsref/event_oninput.asp