Ограничение пользователя оставлять поле ввода пустым с помощью метода getElementsByClassName из JavaScript - PullRequest
0 голосов
/ 12 октября 2018

Создана форма.Я просто хочу сделать проверку формы.Использовать JavaScript, чтобы сделать работу здесь.Внутри jS-кода создана функция с именем check.В этой функции, если какой-либо пользователь оставляет поле ввода пустым, то функция возвращает false и, таким образом, я думаю, может ограничить пользователя, но не происходит.Мой вопрос касается как метода getElement .. (), так и проверки формы.

function check(){
  //fname is the value provided into the input field
    var fname = document.getElementsByClassName('fname').value;
    //checks the inpur field and it is blank then return false
    if (fname == '') {
    return false;
  }
  else {
  //if the input field is provided then will pass the validity
    return true;
  }
}
<div class="form">
<!-- created the class here and named form-->
  <form class="" action="output.html.php" method="post" onsubmit="return check()">
  <!-- called the check function-->
    <input class="fname" type="text" name="name" value="" placeholder="Name">
    <button type="submit" name="button">Send</button>
  </form>
</div>

Ответы [ 2 ]

0 голосов
/ 13 октября 2018

Вот мой полный код после выполнения.

function check(){
  //fname is the value provided into the input field
    var fname = document.getElementsByClassName('fname')[0].value;
  //var fname = document.querySelector('.fname').value;
    
    //checks the input field and if it is blank then return false
    if (fname == '') {
    return false;
  }
  else {
  //if the input field is provided then will pass the validity
    return true;
  }
}
<div class="form">
<!-- created the class here and named form-->
  <form class="" action="output.html.php" method="post" onsubmit="return check()">
  <!-- called the check function-->
    <input class="fname" type="text" name="name" value="" placeholder="Name">
    <button type="submit" name="button">Send</button>
  </form>
</div>
0 голосов
/ 12 октября 2018

Проблема в том, что getElementsByClassName возвращает массив, поэтому вы должны использовать либо document.getElementsByClassName('fname')[0].value, либо document.querySelector('.fname').value (querySelector возвращает только первый найденный объект)

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