Как проверить длину переменной, которая объявлена ​​через getElementById? - PullRequest
0 голосов
/ 08 ноября 2019

Я хочу, чтобы длина переменной pw1 сравнивалась с числовым значением 5. Я получил переменную с помощью document.getElementById.value .
Но я думаю, что эта переменная не является строкой, поэтому метод длины не работает.

//Enter code to display "Password is too short" if the password is less than 5 characters

function PasswordlengthCheck() {
 var pw1 = document.getElementById("Pword1").value;
if(pw1.value.length < 5){ //why is this not working?
document.getElementbyId("Placeholder1").innerHTML="Password too short";
}
else{
document.getElementbyId("Placeholder1").innerHTML="";
}
<html> 
<body>
 
<h1>Some password<br>check script</h1>

 <p>Please enter your new password here:<br>
  <input id="Pword1" type="text"  value=""><br>
<p id= "Placeholder1"></p>

</body> 
</html>

Ответы [ 3 ]

0 голосов
/ 08 ноября 2019

у вас довольно много ошибок в вашем коде,

  1. document.getElementById (его ById не byId)
  2. Отсутствуют конечные скобки функции
  3. функция нигде не вызывается
  4. удалить value хотя бы из одного из 2 мест (1. document.getElementById("Pword1") и 2. if (pw1.value.length < 5))

после разрешения всего нижерабочий пример должен работать на вас!

//Enter code to display "Password is too short" if the password is less than 5 characters

function PasswordlengthCheck() {
  var pw1 = document.getElementById("Pword1");
  console.log(pw1.value.length );
  if (pw1.value.length < 5) { //why is this not working?
    document.getElementById("Placeholder1").innerHTML = "Password too short";
  } else {
   document.getElementById("Placeholder1").innerHTML = "";
  }
}
<html>

<body>

  <h1>Some password<br>check script</h1>

  <p>Please enter your new password here:<br>
    <input id="Pword1" type="text" value="" oninput="PasswordlengthCheck()"><br>
    <p id="Placeholder1"></p>
    
</body>

</html>
0 голосов
/ 08 ноября 2019

вы получили значение на первом месте var pw1 = document.getElementById("Pword1").value; вам не нужно получать его снова if(pw1.value.length<5){ //.... }

, просто удалите атрибут значения из pw1 и сделайте это как if(pw1.length<5){ //.... }

0 голосов
/ 08 ноября 2019

У вас есть куча опечаток, и вы не вызывали функцию. Я собираюсь предположить, что вы просто вставили код в свой вопрос и не имели отношения к вашей проблеме.

Ваша переменная pw1 содержала значение, а в вашем операторе if вы получали pw1.value, поэтому она далавы ошиблись, потому что вы действительно делали document.getElementById("Pword1").value.value.length. Удалил лишние .value и для проверки добавил функцию onkeydown ввода.

Вот рабочий пример:

//Enter code to display "Password is too short" if the password is less than 5 characters
function PasswordlengthCheck() {
  var pw1 = document.getElementById("Pword1").value;
  if (pw1.length < 5) { //why is this not working?
    document.getElementById("Placeholder1").innerHTML = "Password too short";
  } else {
    document.getElementById("Placeholder1").innerHTML = "";
  }
}
<html>
<body>
  <h1>Some password<br>check script</h1>

  <p>Please enter your new password here:<br>
    <input id="Pword1" type="text" value="" onkeydown="PasswordlengthCheck()"><br>
    <p id="Placeholder1"></p>

</body>
</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...