Как сделать чтобы функция применялась к каждому элементу? (Убрать placeholder при фокусе на input)
Изучаю JS. Решил посидеть поэкспериментировать.
const loginInput = document.querySelector(".login_input");
const placeholderAttr = loginInput.getAttribute("placeholder");
loginInput.addEventListener("focus", () => {
if (placeholderAttr.length > 1) {
loginInput.setAttribute("placeholder", "")
}
})
<form action="">
<input type="text" placeholder="Login" id="login_input" class="login_input">
<div class="pwd_container">
<input type="password" id="pwd_input login_input" class="pwd_input login_input" placeholder="Password">
<span class="hide_pwd_icon"><img src="img/eye.svg" alt="" width="18"></span>
</div>
</form>
Как сделать чтоб placeholder удалялся у кажого input'a. В данному случае удаляется только у первого инпута Login
Спасибо за ответ.
Ответы (2 шт):
Автор решения: CbIPoK2513
→ Ссылка
Читайте код, чтобы его понимать.
Вы вешаете обработчик только на один элемент - document.querySelector(".login_input")
Чтобы повесить на несколько, нужно "повесить на несколько", например так
let elements = document.querySelectorAll('input'); // Возмём !все! элементы input, т.е. наша переменная является массивом с этими элементами.
elements.forEach(function(e){ // Проходим циклом по всем элементам
e.addEventListener('focus', function(e){ // И на каждый вешаем один и тот же обработчик
e.target.value = 'FOCUS';
});
e.addEventListener('blur', function(e){
e.target.value = '';
});
});
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
Или пользуемся делегирование событий, это лучший вариант (ИМХО).
Подробнее почитайте тут - ссылка
document.body.addEventListener('focus', function(e){
//Обработчик вешается уже какой-то родитель, который содержит в себе все эти элементы.
if(e.target.tagName === 'INPUT') {
e.target.value = 'FOCUS';
}
}, true);
document.body.addEventListener('blur', function(e){
if(e.target.tagName === 'INPUT') {
e.target.value = '';
}
}, true);
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
<input type="text" value="">
Автор решения: UModeL
→ Ссылка
(Убрать placeholder при фокусе на input)
Подозреваю, что имелось в виду следующее поведение:
input.login_input:focus::placeholder { color: #0000; }
<form action="">
<input type="text" placeholder="Login" id="login_input" class="login_input">
<div class="pwd_container">
<input type="password" id="pwd_input login_input" class="pwd_input login_input" placeholder="Password">
<span class="hide_pwd_icon"><img src="img/eye.svg" alt="" width="18"></span>
</div>
</form>