J
J
jugger12020-04-13 18:15:25
JavaScript
jugger1, 2020-04-13 18:15:25

What is the correct way to refer to a specific element in an array?

This code only works on the first object in the array. How can I make it work on the active object?

let input = document.getElementById('callback_phone');
    input.oninput = function() {
        let value = input.value;
        let flag = document.getElementsByClassName('validate_flag');
        let label = document.getElementsByClassName('callback_phone_label');
        console.log(flag);
        if(value.length === 18) {
            flag[0].classList.remove('hidden');
            label[0].innerText = 'Ваш номер телефона';
        }
        else {
            flag[0].classList.add('hidden');
            label[0].innerText = 'Введите ваш номер и мы перезвоним';
        }
    };

<div class="callback-form-block">
                            <label class="callback_phone_label" for="callback_phone">Введите ваш номер и мы перезвоним</label>
                            <input id="callback_phone" type="tel" placeholder="+7" name="phone" value="+7">
                            <span class="hidden validate_flag"> done </span>
</div>
<div class="callback-form-block">
                            <label class="callback_phone_label" for="callback_phone">Введите ваш номер и мы перезвоним</label>
                            <input id="callback_phone" type="tel" placeholder="+7" name="phone" value="+7">
                            <span class="hidden validate_flag"> done </span>
</div>
<div class="callback-form-block">
                            <label class="callback_phone_label" for="callback_phone">Введите ваш номер и мы перезвоним</label>
                            <input id="callback_phone" type="tel" placeholder="+7" name="phone" value="+7">
                            <span class="hidden validate_flag"> done </span>
</div>

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Inzeneries, 2020-04-13
@Inzeneries

document.querySelectorAll('.callback-form-block').forEach(div => {
 let input = div.querySelector('input');
 input.oninput = function() {
        let value = input.value;
        let flag = div.getElementsByClassName('validate_flag');
        let label = div.getElementsByClassName('callback_phone_label');
        console.log(flag);
        if(value.length === 18) {
            flag[0].classList.remove('hidden');
            label[0].innerText = 'Ваш номер телефона';
        }
        else {
            flag[0].classList.add('hidden');
            label[0].innerText = 'Введите ваш номер и мы перезвоним';
        }
    }
})

E
Evgeny Zaletsky, 2020-04-13
@JZ_52

Maybe it will help you

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question