Я не могу отображать сообщения об ошибках в форме, которая использует имена - PullRequest
0 голосов
/ 01 февраля 2019

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

Я проверил, что переменные действительно содержат правильные значенияиспользуя простое оповещение (variableName), однако я не смог отобразить ошибки, используя оповещения или .innerHTML
Хотя я не могу получить значение для раскрывающегося списка.

Это HTML:

<!-- This is for the name -->
        <p>Name: 
          <input type="text" name="textfield"> 
          </p>
<!-- This is for the email -->
      <p align="left" class="style3">E-mail: 
        <input type="text" name="textfield">
</p>
<!-- This is for the type of bird -->
      <p align="left" class="style3">Bird: 
        <select name="select" size="1">
          <option>Rainbow Lorikeet</option>
          <option>Golden Pheasant</option>
          <option selected>Hoopoe</option>
          <option>Bird of Paradise</option>
          <option>Kingfisher</option>
          <option>Peacock</option>
          <option>Other</option>
        </select>
        <input type="text" name="textfield">
</p>
<!-- This is for location of bird -->
      <p align="left" class="style3">Location: 
        <input type="text" name="textfield"></p>
      <p align="left" class="style3">You must agree to us contacting you to find out about your sighting. Please tick this box to agree to this statement: 
        <input type="checkbox" name="checkbox" value="checkbox">
</p>
      <p align="left" class="style3">
        <input onclick='checking()' type="submit" name="Submit" value="Submit">
</p>
<p id='output'></p>

А это JavaScript:

function checking() {
        var name = document.getElementsByName('textfield')[0]
        var email = document.getElementsByName('textfield')[1]
        var otherBird = document.getElementsByName('textfield')[2]
        var location = document.getElementsByName('textfield')[3]
        var birdSelect = document.getElementsByName('select')[0]
        var bird = birdSelect.options[birdSelect.selectedIndex]
        if (name.value===null){
            document.getElementById('output').innerHTML = 'Please enter your name'
            return false
        } else if (email.value===null) {
            document.getElementById('output').innerHTML = 'Please enter your email'
            return false
        } else if (location.value===null) {
            document.getElementById('output').innerHTML = 'Please enter the location of the bird'
            return false
        } else if (otherBird.value===null && bird.text==='Other') {
            document.getElementById('output').innerHTML = "Please enter a bird's name"
            return false
        } else {
            return true
        }
    }

Сообщение об ошибке должно отображаться, когда:

Если вам нужно что-то уточнить, я буду счастливдля этого.
Заранее спасибо

1 Ответ

0 голосов
/ 01 февраля 2019

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

function check() {
  // clear output
  document.getElementById('output').innerHTML = ''

  // check for null OR empty string
  var name = document.getElementsByName('textfield')[0]
  if (name.value === null || name.value === '') {
    document.getElementById('output').innerHTML = 'Please enter your name'
    return false
  }
}
<div>
  Name: <input type="text" name="textfield">
  <input type="button" onclick="check()" value="Check">
</div>

Output:
<p id='output'></p>

Возможно, вы даже можете опустить сравнение null, но я все равно оставил его.

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