Steps for correctly invoking a function based on input value conditions

Lately, I've been developing a new website geared towards serving as a platform for various travel agencies to showcase their tour packages.

The homepage features a functional filter section that enables users to search for offers based on different criteria.

            <div id="offer-filters">
            <h2>Filter Search</h2>
            <div id="filter-bars">
                <ul id="filter-list">
                    <li>
                        <label for="searchagency">Agency</label>
                        <input list="agencies" id="searchagency" name="searchagency"
                            onclick="dataListFromOriginAgency('agencies', 'searchagency')">
                    </li>
                    <datalist id="agencies"></datalist>
                    ... (additional filter options) ...
                    
        

The primary concept here is that the button at the bottom triggers functions based on the number of filled inputs. For instance, if a user searches by agency and destination, corresponding functions are called accordingly.

However, there's an issue where only one function gets invoked as conditions evaluate sequentially. Is there a way to assign unique functions to every combination of filters?

Furthermore, these functions make AJAX requests to fetch data dynamically, enhancing the user experience with real-time content updates.

function triggerFuncByScenario() {
if (!(document.querySelector("#searchagency").value === "")) {
    getOffersByName();
}

else if (!(document.querySelector("#searchagency").value === "" && document.querySelector("#searchdestination").value === "")) {
    getOffersByDestinationName();
}

Answer №1

Upon reviewing the code, I had a thought: have you considered nesting your if-else statements?

function triggetFuncByScenario(){
    if(!(document.querySelector("#searchagency").value === "")){
        if(!(document.querySelector("#searchdestination").value === "")){
            getOffersByDestinationName();
        }else{
            getOffersByName();
        }
    }
}

It appears to me that this oversight may be the root of your issue. By nesting the statements, you ensure all conditions are checked thoroughly.

I hope this insight proves helpful as you continue with your project. Best of luck!

Answer №2

By simply reordering how you evaluate the conditions, you can achieve the desired outcome. However, a more detailed approach can provide a clearer understanding of each step in the process.

In this scenario, the evaluateSearchFields function returns a singular value indicating which fields the user has populated. This knowledge allows for confident decision-making on the next course of action.

While most situations may not require such intricate analysis, there are times when clarity is essential to progress with certainty.

function triggerFuncByScenario() {
  const
    searchAgency = document.getElementById("searchagency"),
    searchDestination = document.getElementById("searchdestination"),

    agencyEmpty = (searchAgency.value === ""),
    destinationEmpty = (searchDestination.value === "");

  if( evaluateSearchFields() == "agencyOnly" ){ getOffersByName(); }
  else if( evaluateSearchFields() == "both" ){ getOffersByDestinationName(); }
}

function evaluateSearchFields(){
  if(!agencyEmpty && !destinationEmpty){ return "both"; }
  if(!agencyEmpty && destinationEmpty){ return "agencyOnly"; }
  if( agencyEmpty && !destinationEmpty){ return "destinationOnly"; }
  if( agencyEmpty && destinationEmpty){ return "neither"; }
  else { return "this is impossible"; }
}

Answer №3

When removing the else statement in this section, both conditions will be evaluated and executed.

It is advisable to use getElementById if you only need to retrieve a single element by its ID.

function triggerFuncByScenario() {
    var searchAgency = document.getElementById("searchagency");

   if (!(searchAgency.value === "")) {
         getOffersByName();
   }


  if (!(searchAgency.value === "" && 
    document.querySelector("#searchdestination").value === "")) {
        getOffersByDestinationName();
     }
  }

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

What is the best way to refresh a navigation bar after making an API request, such as when using Google Sign-In?

Struggling to grasp the hook concept in this particular scenario: The flow goes like this - the user logs in with Google, which updates the session state. Consequently, the visitorType state transitions from 'viewer' to 'buyside'... A ...

The footer should remain at the bottom of the page without being permanently fixed

Is there a way to keep the bootstrap footer at the bottom without fixing it in place? In the code example below, the footer should always appear at the bottom. The white space after the footer should come before it. Using sticky-bottom achieves this, but ...

Utilizing regular expressions on a URI parameter in JavaScript

I implemented an ajax function that retrieves three images (PORTRAIT, SQUARE, and LANDSCAPE) from a JSON response: $.ajax({ url: link, method: 'GET', headers: { "Authorization": authToken ...

Using CSS, center a div element both vertically and horizontally, and position the footer at the bottom of the page

I am encountering some unexpected behavior for a task that I thought would be simple. I have two main objectives in mind. Firstly, I want the footer to be displayed at the bottom of the page as an actual footer. Secondly, I need the div with the ".center-d ...

Angular 8's array verification feature lacks the ability to recognize preexisting elements

I've been trying to add and delete items in an array when a user selects or deselects the same item. However, it appears that either my array is not working properly or there is a bug in my code causing it to fail. <div class="grp-input"> ...

Is there a way to efficiently clear the Express session for all users without the need to restart the application?

During my development of REST services using the nodejs express framework, I encountered an issue with storing user-specific data in sessions. I utilized the user's ID as a key to identify the user's data. The following code snippet demonstrates ...

Retrieving Django view information using AJAX

Currently, I am in the process of developing an application that updates the main page's data via AJAX. After reading through a helpful response on this Stackoverflow post, I implemented AJAX to refresh my page. In addition to this, I have a specific ...

Using Javascript to attach <head> elements can be accomplished with the .innerHTML property, however, it does not work with XML child nodes

Exploring new ways to achieve my goal here! I want to include one JS and one jQuery attachment for each head section on every page of my static website. My files are: home.html <head> <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

Extracting information from an ENORMOUS Array

Let's start with my code snippet, featuring an array: var UserProfiles = [{ userProfileID: 1, firstName: 'Austin', lastName: 'Hunter', email: 'test', token: '', platform: 'android ...

Updating a value within destructuring and a loop: A step-by-step guide

My Goal: I aim to modify a value in an object that is part of an array element. Take a look at the code snippet below for a clearer understanding. An issue arises when I update the object's value through reference instead of creating a new copy, cau ...

Error message: Unexpected character found at the beginning of JSON data - REST API using node.js and Express

Recently, I have embarked on the journey of learning REST API with node and express. My main goal is to achieve file read and write operations using APIs. However, a frustrating error arises when attempting to hit the API through Postman. Strangely enough, ...

Pushing items to an array is causing the loss of previously added data

Currently, I am working on developing a prototype of a Restaurants application using Angular 8. In this project, I have implemented @Input() to transfer individual restaurant data as an object from the parent component to the RestaurantCardComponent for pr ...

Angular: Maximizing Input and Output

I'm having trouble with the function displaying within the input field. My goal is to simply allow the user to enter a name and have it displayed back to them. HTML: <div ng-app = "mainApp" ng-controller = "studentController"> <tr> < ...

How can I implement a single-column search feature in a GridView using Javascript in ASP.NET?

I found a Google function for client-side searching in a grid using a textbox Here is the function: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <script> function searchFunction(phrase, ...

The jquery ajax call only seems to function properly when executed on a local

Currently, I am utilizing jQuery ajax to retrieve data from a back-end method in asp.net using the following code: $.ajax({ cache: false, type: "POST", url: '<%= Page.ResolveUrl("~/Live/Live.aspx/GetViews") %>', content: "j ...

How can you reference the immediate selector object using jQuery?

I'm currently delving into the realm of jQuery and decided to create a test page equipped with the following code: <a id='encode' href='javascript: void(0)'>encode</a> | <a id='decode' href='javascr ...

The execution of jQuery encountered an issue as it threw an error: parsererror with the specific error being SyntaxError due to

I'm currently facing an issue with a contact form that connects to a PHP script through ajax. After processing the form, the ajax script should execute specific actions based on the response received from the json_encode() function in the PHP script. ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

`Next application will have all accordions simultaneously opening`

Is there a way to make the accordion open only one item at a time? Currently, when I click on one accordion item, all of them expand simultaneously. The data is being fetched from a local JavaScript file and consists of a list of objects with questions a ...