Почему цвет меняется только в первой области ввода, если я пишу что-то - PullRequest
1 голос
/ 04 мая 2020

У меня есть форма с 4 областями ввода, но цвет меняется только в первую очередь, в чем причина и как я могу это исправить?

HTML
<form>
    <input id="username" type="text" placeholder="username" value="">
    <input id="email" type="email" placeholder="email" value="">
    <input id="password" type="password" placeholder="password" value="">
    <input id="passwordRepeat" type="password" placeholder="repeat your password" value>
</form>

JS
var input = document.querySelector("input");
input.addEventListener("input", function() {

  if (input.value.length > 0)
    input.style.background = "#27ae60";
  else
    input.style.background = "none";
})

Ответы [ 3 ]

2 голосов
/ 04 мая 2020

document.querySelector вернет только первый элемент, соответствующий селектору.

Что вы на самом деле хотите сделать, так это отобразить их все, используя querySelectorAll, и добавить его к каждому:

document.querySelectorAll('input').forEach(function(input) {
  input.addEventListener('input', function() { 
    if (input.value.length > 0)
      input.style.background = "#27ae60";
    else
      input.style.background = "none";
    }
  });
});

РЕДАКТИРОВАТЬ: Хорошо, так что некоторые из вас хотят получить лучший ответ. Вот вам go (в любом случае JS. Вы можете добавить атрибуты доступности к HTML, чтобы сделать его более практичным):

//HTML
<form id="form-signup">
    <input id="username" type="text" placeholder="username" value="">
    <input id="email" type="email" placeholder="email" value="">
    <input id="password" type="password" placeholder="password" value="">
    <input id="passwordRepeat" type="password" placeholder="repeat your password" value>
</form>

//JS
const signupForm = document.getElementById('form-signup');

signupForm.addEventListener('input', event => {
  const target = event.target;

  target.value.length > 0 ? 
  target.style.background = "#27ae60" :
  target.style.background = "none";
});

РЕДАКТИРОВАТЬ 2: На самом деле, лучший метод может быть чистым css , Предполагая, что этот стиль показывает, что ввод правильно заполнен, вы можете присвоить ему атрибуты проверки ie:

<input minlength="1" required></input>

, а затем применить css к стилю допустимых входных данных:

form input:valid {
  background: #27ae60;
}
1 голос
/ 04 мая 2020

Вам необходимо изменить JS так, чтобы он добавлял eventListners ко всем входам -:

document.querySelectorAll("input").forEach(input => {
    input.addEventListener("input", function() {
        if (input.value.length > 0)
            input.style.background = "#27ae60";
        else   input.style.background = "none";
     })
})

Также мы можем использовать всплывающее окно события, которое является более предпочтительным, так как оно уменьшает количество событий слушатели, как то так -

document.getElementById("signup").addEventListener("change", (e) => {
  if (e.target.value.length > 0)
    e.target.style.background = "#27ae60";
  else
    e.target.style.background = "none";
})
<form id="signup">
    <input id="username" type="text" placeholder="username" value="">
    <input id="email" type="email" placeholder="email" value="">
    <input id="password" type="password" placeholder="password" value="">
    <input id="passwordRepeat" type="password" placeholder="repeat your password" value>
</form>
0 голосов
/ 04 мая 2020

Это происходит потому, что document.querySelector() возвращает только первый элемент, соответствующий селектору. Вы можете использовать document.querySelectorAll() или, в данном случае c, document.getElementsByTagName. В любом случае, вам нужно перебрать массив, возвращаемый этими функциями.

var inputs = document.getElementsByTagName("input"); // You could also use document.querySelectorAll("input");

function listener() {
  if (input.value.length > 0)
    input.style.background = "#27ae60";
  else
    input.style.background = "none";
})

for (input of inputs) {
  input.addEventListener("input", listener);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...