Guidelines for managing a catch function

I have recently set up a database in Cloud Firestore and am looking to populate it with information using input fields. However, I've encountered an issue where if the input fields are left empty, the information still gets stored and the catch function fails to work. How can I resolve this and ensure that the catch function works properly?

Below is the code snippet:

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;

  // Adding a new document in the "UsersShare" collection
   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);
  });
}

Answer №1

if(inputCountry.trim() && inputCity.trim() && inputAddress.trim() & 
   inputNameOfPlace.trim()){
  // Insert new data into the database
  // your implementation here
} else {
 // Fields cannot be empty --- display error message
}

Answer №2

Prior to performing any operations on the database, it is advisable to validate whether the fields contain any data. If they are empty, an error message can be logged to the console using a catch function:

if(inputCountry && inputCity && inputAddress && inputNameOfPlace){
    db.coll.....
} else {
    console.error('One or more field(s) are empty');
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

Steps to reverting CSS attributes back to their default values for a specified element (or blocking inheritance)

How can you reset a specific CSS attribute of an HTML element, which is automatically inheriting styles from its parent, to the default value? For example: CSS: .navigation input { padding: 0; margin: 0 30em; } HTML <div class="navigation"& ...

Understanding the reason why "undefined" is occurring in Javascript

Can anyone help me understand why the alert at the start is showing "undefined"? The alerts are displayed in this order: "success!" "Data" (the correct value) "undefined" I have gone through several threads and found that the issue usually arises du ...

Managing responses from ajax requests that can handle both text and json formats

After submitting a form via Ajax and receiving a response from the servlet in either text or JSON format, I'm wondering if there is a way to handle both types of responses. I've read through the jQuery/Ajax documentation, but the JQuery Ajax page ...

Cheerio - Ensure accurate text retrieval for selectors that produce multiple results

Visit this link for more information https://i.stack.imgur.com/FfYeg.png I am trying to extract specific market data from the given webpage. Specifically, I need to retrieve "Sábado, 14 de Abril de 2018" and "16:00". Here is how I did it using Kotlin an ...

Adjust the form action and text input name according to the selected radio input

Seeking assistance with the following code, can someone help? $(document).ready(function() { $('#searchform').submit(function() { var action = ''; if($('.action_url').val() == 'l_catalog') { ...

Troubleshooting UDP output issues in FFMPEG

Currently attempting to stream a video via ffmpeg to a udp stream by piping rawvideo directly into ffmpeg using ffmpeg.stdin.write(data). Here are my specified options/parameters: var ffmpegArgs = [ '-c:v', 'rawvideo',// input cont ...

Can dates in the form of a String array be transmitted from the server to the client?

Struggling to send a String array from the server side to the client using Nodejs and Pug. Encounter errors like "SyntaxError: expected expression, got '&'" or "SyntaxError: identifier starts immediately after numeric literal". Server runs o ...

The box shadow does not envelop the entire block uniformly

I have been struggling to evenly cover the shadows around all the blocks using CSS. Unfortunately, after working on it for 2 days, I still haven't been able to find a solution. The middle line seems to be misaligned and thicker compared to the others. ...

Implementing a nested ng-repeat for organizing limited data

I'm working with a nested ng-repeat setup like this: <div ng-repeat="item_l in list1"> <div ng-repeat="item_f in list2"> {{item_f}} {{item_l}} </div> </div> Currently, this code is producing around 20 results. ...

Discovering the Voice Channel of a User using Discord.js v13

I'm currently working on a 'wake up' command for my bot that should move the mentioned member between 2 specific voice chats and then return them to their original VC. I've successfully got the bot to move me between those 2 VCs, but no ...

Prompting the website to 'refresh' and return to the beginning of the page

My website's functionality is closely tied to the user's position on the page. Different features are triggered once specific distances are reached. I am seeking a way for users to automatically return to the top of the page upon page reload. Cu ...

Guide on altering the Class with jquery

Here is My jQuery Code: $('a#cusine1').on('click', function(){ $('div#product-list').html("LOADING..........").show(); $(".ccid").addClass("0"); document.getElementById("ccid1").className="acti ...

Stop form from submitting on bootstrap input, still check for valid input

Encountering a dilemma here: Employing bootstrap form for user input and utilizing jQuery's preventDefault() to halt the form submission process (relying on AJAX instead). Yet, this approach hinders the input validation functionality provided by boots ...

The Kendo Grid is refusing to show up within the popup window

I am new to using Angular 2 and Kendo UI. Currently, I am attempting to include a grid inside my pop-up window. While I have successfully displayed the pop-up, adding the grid has proven challenging. The grid is not appearing as expected ...

"Error in react-three-fiber: Only the last mesh retains its model, all others are

Currently, I am working on a React application where I am using react-three-fiber to visualize data in a 3D environment. My goal is to create various models by passing data representing their characteristics as props into components. However, I am encounte ...

Using AngularJS to show/hide elements within a colgroup tag

Looking to create a dynamic table allowing users to hide certain columns. Wondering if it's possible to use ng-show with colgroup or col tags instead of adding ngshow to each cell individually. Struggling to make it work... <colgroup ng-repeat="mt ...

Utilizing KnockoutJS to Apply CSS Binding Based on Dropdown Selection

Check out the live example here: http://jsfiddle.net/0gmbbv5w/ In my application, I have an object retrieved from the database that I bind to a <select> var NoticeType = function (noticeType) { this.NoticeTypeId = ko.observable(noticeType.Notic ...

Steps for extracting information from an html webpage that runs javascript

I'm currently working on a program to extract the IUPACcondensed from this specific website. On this page, G03307GF serves as the ID. The desired information is as follows: HexNAc(b1-?)[Fuc(a1-?)]GlcNAc(b1-2)Man(a1-3)[HexNAc(b1-?)[Fuc(a1-?)]GlcNAc(b ...

the ever-changing dimensions of a PDF document

I'm attempting to display a PDF using an iframe, but I want the height of the viewer to match the document's height, meaning that all 3 pages should be visible without scrolling. How can I achieve this? Here's a simple example I created on ...