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

Choose the initial offspring from a shared category and assign a specific class identifier

I am trying to figure out how to apply the "active" class to the first tab-pane within each tab-content section in my HTML code. Here is an example of what I'm working with: <div class="tab-content"> <div class='tab-pane'>< ...

Animate the div only when the button is clicked

I need a way to hide the text inside a div when it exceeds a certain height, but then expand it to full height upon clicking a button. However, I want this action to only affect the parent div of that specific button, rather than all the divs on the page. ...

Guide to verifying the property value following mocking a function: Dealing with Assertion Errors in Mocha

Based on a recommendation from a discussion on this link, I decided to mock the readFileSync function and then mocked my outer function. Now, my goal is to verify whether the variable's value has been set as expected. file.js const fs1 = require ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

How can AJAX be used for form validation prior to submission?

Currently, I am facing an issue with validation on the client side when making an ajax cross-domain request to my PHP server page. I have a standard HTML form that posts input fields such as name, last name, and message. Here is an example of my form on th ...

Updating state in React using the spread operator is not allowed

As a newcomer to React, I've been struggling with using the spread operator to push new elements into an array stored in the state. My aim is to create an array with a sequence of different numbers. Here's the code snippet that I've been wor ...

What is the method to verify if a variable in ES6 is constant?

I'm seeking advice on how to accomplish a specific task. I attempted using the try-catch method, but encountered some limitations: "use strict"; const a = 20; var isConst = false; try { var temp = a; a = a+1; a = temp; } catch (e) { isConst = ...

The component is unable to access VueJS references

Below is a simplified version of the code I am working with: <html> <head> <script src="file:///D:/OtherWork/javascript/vue/vue.js"></script> </head> <body> <div id="app"> & ...

Next.js Page is failing to render React component props

I am currently facing an issue where I need to display data from the props object in a functional component using React. The component structure looks like this: interface TagsComponentProps { tags: Tag[]; } const TagsComponent: FC<TagsComponentPro ...

Using Rails to render a partial with jQuery for a loop function

I am trying to include a partial multiple times in my view with different parameters. I have a search form that returns project data in JSON format using Ajax. Now, I want to use a jQuery function to get the project and display it in the view. $.ajax({ ...

What is the best way to structure Vue.js components for optimal organization?

Imagine having an index page called index.vue consisting of various components like this: index.vue <template> <div> <component-1 /> <section class="section-1"> <div class="container section-container"> <com ...

Storing data locally in PhoneGap using localStorage via AJAX calls is a common requirement for

Our mobile application is built with cordova [phonegap] and we are looking to implement offline saving of results into the cache memory. The results are fetched from a PHP server and displayed in a webview using ajax and javascript. I have tried using loc ...

Adjust the size of the Div and its content to fit the dimensions of

Currently, I have a div containing elements that are aligned perfectly. However, I need to scale this div to fit the viewport size. Using CSS scale is not an option as it does not support pixel values. https://i.stack.imgur.com/uThqx.png I am looking to ...

Implementing the decrement functionality within an onclick event handler for a variable

Can someone assist me with this issue? I am trying to use a variable ID in HTML to call a function on a JavaScript page. For example: (Minus button not functioning) <button class="minus-button quantity-button button" type="button" name="subtract" onc ...

Swap out the content in a text input box with the text chosen from a suggested autocomplete option

I am working on a text input box with auto-complete options displayed below it. I want to enable users to navigate through the options using keyboard arrows and "select" one, causing it to change color. How can I update the text in the input box with the s ...

Can an additional height be added to the equalizer to increase its height?

Is it feasible to append an additional 35px to the height determined by Foundation Equalizer? For instance, if Equalizer computes a height of 350px, I would like to increase it by 35px. This means that the resultant style should be height: 385px; instead ...

Encountered an issue with the property 'push' not being defined

Here's the schema for my mongoose model in JavaScript: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const CartSchema = new Schema({ userID: String, items: [{ itemID: String, quantity: Number }] }); modul ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

Creating HTML content in TypeScript with NativeScript using document.write()

Essentially, I am looking to create a set number of labels at various row and column positions depending on the user's input. However, I have been unable to find any resources that explain how to write to the .component.html file from the .component.t ...

Building paths through a jQuery loop

Transform String into Delimited Array, Generate Loop of Check Boxes, and Build New String Given String = "Folder Tier1\Folder Tier2\Folder Tier3\Folder Tier4\Folder Tier5\Folder Tier6\" (Missing) Use "\" as a delimi ...