Как справиться с функцией catch? - PullRequest
2 голосов
/ 21 апреля 2020

Я создал базу данных в облачном firestor, поэтому теперь я хочу добавить к ней некоторую информацию по полям ввода, проблема в том, что поля ввода пустые, информация хранится и функция catch не работает, как я могу это исправить, и заставить функцию catch работать.

Вот код:

HTML:

<div class="container"> 
          <input  type="text" placeholder="Enter the country" id="country-field"  required>
          <p class="selectPar">Enter City</p>
          <input type="text" placeholder="Enter the city" id="city-field" required>
          <p class="selectPar">Enter the place name</p>
          <input type="text" placeholder="Enter the place name" id="placename-field" required>
          <p class="selectPar">Enter Address</p>
          <input type="text" placeholder="Enter the address" id="address-field" required>
          </div>
        </div>
        <div id="btnFrmAlignSec">
          <button id="btnFrm" type="button" onclick="AddToDataBase()">Send to admin</button>
        </div>

Javascript

function AddToDataBase () {

  var inputCountry = document.getElementById("country-field").value;
  var inputCity = document.getElementById("city-field").value;
  var inputAddress = document.getElementById("address-field").value;
  var inputNameofPlace = document.getElementById("placename-field").value;

  // Add a new document in collection "cities"
   db.collection("UsersShare").doc().set({

    name:inputNameofPlace,
    city:inputCity,
    country:inputCountry,
    address:inputAddress,

  })

  .then(function() {
    console.log("Document successfully written!");
    document.getElementById("reply").style.display="inline";  
  })
  .catch(function(error) {
    console.error("Error writing document: ", error);
  });
}

Ответы [ 2 ]

4 голосов
/ 21 апреля 2020
if(inputCountry.trim() && inputCity.trim() && inputAddress.trim() && 
   inputNameOfPlace.trim()){
  // Add a new document in collection 
  // your code
} else {
 // fields are empty --- error message
}
0 голосов
/ 21 апреля 2020

Вы можете проверить заранее, являются ли поля пустыми, если нет, то поработать с БД, в противном случае зарегистрировать ошибку на консоли, как это делает ваша функция catch:

if(inputCountry && inputCity && inputAddress && inputNameOfPlace){
    db.coll.....
} else {
    console.error('Field(s) are empty');
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...