Home > Software engineering >  Act on the last element of a page with querySelector and addEventListener
Act on the last element of a page with querySelector and addEventListener

Time:06-18

I am trying to check the security level of a password and put the field borders in green or red (depending on the respect of conditions). I have succeeded but the JavaScript only selects the first field (the nickname field) whereas I would like to select the last one. I have tried all sorts of things but nothing works. Can anyone help me?

Here is the HTML code:

...

<label for="pseudo">Rentrez un pseudo </label>
<input type="text" id="pseudo"> 

<label for="pseudo">Rentrez un mdp</label>
<input type="password" id="mdp">

<script src="js/verif_filed.js"></script>

...

and the js code:

const validationInput = document.querySelector("input");

const cara_nbr = Array.from("0123456789");
const cara_lower = Array.from("abcdefghijklmnopqrstuvwxyz");
const cara_upper = Array.from("ABCDEFGHIJKLMNOPQRSTUVWXYZ");

validationInput.addEventListener('input', (element) => {
    let have_nbr = false;
    let have_spetial = false
    let have_lower = false;
    let have_upper = false;
    for (let i of element.target.value) {
        if (cara_nbr.includes(i)) {have_nbr = true;}
        if (cara_lower.includes(i)) {have_lower = true;}
        if (cara_upper.includes(i)) {have_upper = true;}
        if (!(cara_nbr.includes(i) || cara_lower.includes(i) || cara_upper.includes(i))){
        have_spetial = true;
    }
}

if (element.target.value.length >= 8 && have_nbr == true && have_spetial && have_lower == true && have_upper == true) {
    validationInput.style.borderColor = "green";
}
else {
    validationInput.style.borderColor = "red";
    console.log(e.target.value)
    console.log(have_nbr, have_lower, have_upper)
}

CodePudding user response:

You can select the last <input> element by its id.

const validationInput = document.querySelector("input#mdp");
// or
const validationInput = document.getElementById("mdp");

CodePudding user response:

You need to use querySelectorAll and then loop through the elements:

const validationInputs = document.querySelectorAll("input"); // returns an array

Loop:

validationInputs.forEach(input => {
    input.addEventListener('input', (element) => {
        let have_nbr = false;
        let have_spetial = false
        let have_lower = false;
        let have_upper = false;
        for (let i of element.target.value) {
            if (cara_nbr.includes(i)) {have_nbr = true;}
            if (cara_lower.includes(i)) {have_lower = true;}
            if (cara_upper.includes(i)) {have_upper = true;}
            if (!(cara_nbr.includes(i) || cara_lower.includes(i) || cara_upper.includes(i))){
                have_spetial = true;
            }
        }
    }
}

  • Related