JS Conditional logic

/**
 * AxonCreator - Website Builder
 *
 * NOTICE OF LICENSE
 *
 * @author    axonvip.com <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="bfcccacfcfd0cdcbffdec7d0d1c9d6cf91dcd0d2">[email protected]</a>>
 * @copyright 2021 axonvip.com
 * @license   You can not resell or redistribute this software.
 *
 * https://www.gnu.org/licenses/gpl-3.0.html
 */
var AxpsSearchModule;
!(function (d) {
    "use strict";
    AxpsSearchModule = {
        init: function () {
            this.mdCategoryDropdown(), this.mdSearch();
        },
        mdSearch: function () {
            d("body").on("shown.bs.modal", "#search-popup", function () {
                var e,
                    a,
                    i = d("#search-popup").find("input[name=s]").val();
                d("#search-popup").find("input[name=s]").val("").focus().val(i),
                    d(window).width() < 768 ||
                        ((a = (e = d("#search-popup").find(".category-dropdown-inner")).innerWidth() + e.closest("form").find(".search-submit").innerWidth() + 17),
                        (i = "padding-right"),
                        d("form.has-ajax-search").each(function () {
                            var a,
                                e,
                                i,
                                n,
                                r,
                                s,
                                t,
                                o,
                                c = d(this);
                            c.hasClass("fs-initialized") ||
                                (c.addClass("fs-initialized"),
                                (a = '<div class="view-all-results view-all-products"><span>' + opSearch.all_results_product + "</span></div>"),
                                (e = c.attr("action")),
                                (i = parseInt(opSearch.count)),
                                (n = c.find('[name="c"]')),
                                (r = "cart_default"),
                                (s = c.closest(".search-wrapper").find(".search-results")),
                                c.removeClass("has-ajax-search"),
                                void 0 !== opSearch.imageType && "" != opSearch.imageType && (r = opSearch.imageType),
                                0 != opSearch.search_string && c.find("input[name=s]").val(opSearch.search_string),
                                c.find("input[name=s]").click(function () {
                                    3 <= c.find("input[name=s]").val().length && "" !== s.find(".autocomplete-suggestions").html() && s.find(".autocomplete-suggestions").css({ display: "flex" });
                                }),
                                s.on("click", ".view-all-products", function () {
                                    c.submit();
                                }),
                                c.find("input[name=s]").devbridgeAutocomplete({
                                    serviceUrl: e,
                                    appendTo: s,
                                    type: "POST",
                                    dataType: "json",
                                    paramName: "s",
                                    minChars: 3,
                                    params: { c: n.val(), resultsPerPage: i },
                                    onSelect: function (e) {
                                        void 0 !== e.permalink && 0 < e.permalink.length 
                                     // Add conditional statement here to check if price is greater than 0
{
if(e.price > 0){
(d('.search-price').append('<td>'+ e.price+'</td>'))
}
},

                                       ;
                                    },
                    mdCategoryDropdown: function () {
                        d(".category-dropdown-inner").each(function () {
                            var i,
                                n,
                                s,
                                r = d(this);
                            function t() {
                                r.removeClass("shown");
                            }
                            function o() {
                                var e, a;
                                d(window).width() < 768 ||
                                    ((e = r.innerWidth() + r.closest("form").find(".search-submit").innerWidth() + 17), (a = "padding-right"), d("body").hasClass("rtl") && (a = "padding-left"), r.closest("form").find("input[name=s]").css(a, e));
                            }
                            r.hasClass("cd-initialized") ||
                                (r.addClass("cd-initialized"),
                                (i = r.find("> a")),
                                (n = r.find("> input")),
                                (s = r.find("> .list-wrapper")),
                                opSearch.current_category_id &&
                                    (s.find(".active-item").removeClass("active-item"),
                                    s
                                        .find("a[data-value=" + opSearch.current_category_id + "]")
                                        .parent()
                                        .addClass("active-item"),
                                    i.text(s.find("a[data-value=" + opSearch.current_category_id + "]").text()),
                                    n.val(opSearch.current_category_id),
                                    s.find("ul:not(.children) > li:first-child").show()),
                                o(),
                                d("body").on("click", function (e) {
                                    e = e.target;
                                    if (r.hasClass("shown") && !d(e).is(".category-dropdown-inner") && !d(e).parents().is(".category-dropdown-inner")) return t(), !1;
                                }),

In the below code the e.price is the price of a product, I want to know how I can put an If conditional statement in this so that the price with zero price shall not be shown (no price), and if amount is greater than 0 then it will be shown. I tried `if(e.price == 0)` but I don't know how and in which line it should be written.

formatResult: function(e, a) {
  var i = "(" + (a = "&" === a ? "&#038;" : a).replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ")",
    a = "";
  return (
    e.divider && (a += ' <h5 class="search-divider-text">' + e.divider + "</h5>"),
    e.thumbnail && (a += ' <div class="search-thumb">' + e.thumbnail + "</div>"),
    e.value && (a += '<h4 class="search-title">' + e.value.replace(new RegExp(i, "gi"), "<strong>$1</strong>").replace(/&lt;(\/?strong)&gt;/g, "<$1>") + "</h4>"),
    e.no_found && (a = '<div class="no-result">' + e.value + "</div>"),
    e.view_all_products && (a = '<div class="view-all-products"></div>'),
    e.sku && (a += ' <div class="search-sku">' + e.sku + "</div>"),
    e.price &&
       // Adjusted condition based on your requirement
      (a += e.price > 0 ? ' <div class="search-price">' + e.price + '</div>' : ''),
    a
  );
},

Answer №1

One clever way to utilize a Template literal with a concise condition is by doing the following -

<div class="search-price"> ${e.price === 0 ? '' : e.price}  </div>

Answer №2

Just a heads up, no guarantee it will work perfectly


formatResult: function(e, a) {
  var i = "(" + (a = "&" === a ? "&#038;" : a).replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&") + ")",
    a = "";

// This is where the magic happens
   if(e.price<=0){
      e.price = ""
   }
// End of magic

  return (
    e.divider && (a += ' <h5 class="search-divider-text">' + e.divider + "</h5>"),
    e.thumbnail && (a += ' <div class="search-thumb">' + e.thumbnail + "</div>"),
    e.value && (a += '<h4 class="search-title">' + e.value.replace(new RegExp(i, "gi"), "<strong>$1</strong>").replace(/&lt;(\/?strong)&gt;/g, "<$1>") + "</h4>"),
    e.no_found && (a = '<div class="no-result">' + e.value + "</div>"),
    e.view_all_products && (a = '<div class="view-all-products"></div>'),
    e.sku && (a += ' <div class="search-sku">' + e.sku + "</div>"),
    e.price && (a += ' <div class="search-price">' + e.price + "</div>"),
    a
  );
},

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 ensure a component waits for asynchronous data to be retrieved from a service

I am working on a scenario where a service is fetching API data and I need to store and use it in multiple components every time the URL changes, without making additional API calls. The API should only be fetched when the service is invoked. The challeng ...

Is there a way to store the result from LiquidJS as a variable?

On the homepage of , this code snippet is provided as an example: import { Liquid } from 'liquidjs' const engine = new Liquid() const tpl = engine.parse('Welcome to {{v}}!') engine.render(tpl, {v: "Liquid"}).then(console.log) ...

JavaScript TypeError - missing method issue

When I try to call this code, I am encountering a TypeError: player = new Player({name:''}); Player = MeteorModel.extend({ schema:{ name:{type:String,}, value:{} }, belongsTo:{ meteorCollection:'', methodName ...

Having difficulty displaying files in the directory on the console?

Here lies the content of several JavaScript files. // index5.js var server = require("./nonblockingserver"); var router = require("./nonblockingrouter"); var requestHandlers = require("./requestHandlers4"); var handle = {} handle["/"] = requestHandlers.st ...

What is the best way to continuously add items to a div until their heights are equal?

In my layout, I have two divs positioned next to each other. Typically, the left div displays n+2 items while the right div displays n items. The value of n changes depending on the category and is already set. However, there are instances where certain ...

Unable to create a random number using JavaScript

Looking for a bit of help with this code snippet: <!DOCTYPE html> <html> <head> <title>Test Your Luck Here!</title> <script type="text/javascript"> function myFunction() { var x = Math.floor((Math.random() * 6) +1); doc ...

Utilizing JavaScript within an ASP page to control the movement of the browser window

I've recently made the switch from using Internet Explorer to Chrome. I've been relying on standardized scripts for some of my intranet pages that use vbcript window.MoveTo to position the browser window at 50,50. Despite finding information onli ...

Using TypeScript, you can pass an object property name as a function argument while ensuring the type is

How can I define a type in a function argument that corresponds to one of the object properties with the same type? For instance, if I have an object: type Article = { name: string; quantity: number; priceNet: number; priceGross: number; }; and I ...

Exporting Data from Angular's ui-grid to Excel

I am currently facing a scenario where I receive significant response data from a REST service to the Angular UI-Grid. Rather than rendering all the data simultaneously, I would like to display it in batches, while still having the option to export all t ...

Monitor the Ajax for any updates in the database and trigger the code accordingly

My objective is to send requests to a php file with specific parameters in this format: <!DOCTYPE html> <html> <head> <script> function onsubmit() { var id = $_SESSION['user']['id']; var xmlhttp; if ...

What causes CSS animations to suddenly halt?

Recently, I've been delving into the world of CSS animations and experimenting with some examples. Below is a snippet of code where two event handlers are set up for elements, both manipulating the animation property of the same element. Initially, th ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Differences Between require: ngModel and scope: { ngModel: '=' } in AngularJS DirectivesWhen it comes to AngularJS directives, there are

Hi there, I'm trying to figure out which option is better. Can you please explain the differences and list out the pros and cons of each? Below is a comparison between the two options: scope: { ngModel:'=' } <!DOCTYPE html> <html ...

Is there a way to extract data from a JSON file with dc.js?

As a beginner in programming, I am looking to learn how to import data from a JSON file using dc.js. ...

Is it possible to Dispatch a Toggle action in Redux without storing it in the State?

Current Implementation At present, I have a list of items. When the user clicks on button X, the state of shouldShowItem is toggled. This state is managed in Redux and passed down to each individual Item component as a prop, where it can be either true or ...

Received the error message "Material-UI: capitalize(string) expects a string argument" while implementing the snackbar feature in a React Material-UI project

While working with Material-UI, I came across an issue with the snackbar where I received an error message saying: Error: Material-UI: capitalize(string) expects a string argument. Here's a snippet of my code: this.state = { snackBarOpenVer ...

Maintaining String Integrity in JQuery when Adding Elements to the DOM

I am currently working on dynamically adding elements to the DOM in order to display a list of search results. Here is a snippet of the code I am using: for(var i=0; i<length; i++){ console.log(temp[i].CATEGORY); console.log(temp[i].SUBCATEGORY ...

Utilizing JavaScript Array Mapping with Object Properties

I am facing a challenge with my dynamic rendering component, which is responsible for rendering sub-components. I recently encapsulated the component within another object, and I am struggling to rewrite the rendering process. Rendering {this.props.compo ...

Having trouble rendering JSON data on the webpage using PHP and AJAX

I've developed a PHP file that is supposed to generate JSON data, as illustrated below. However, it appears that the file is not returning any data. When attempting to retrieve data.status, I encounter an undefined error. While it seems to be success ...

Embed a JavaScript file containing PHP code

Recently, I incorporated PHP into my JavaScript code, as shown below: var currentTotalContribution = <?php echo $myContribution; ?>; Now, I am interested in moving that content to my JavaScript file and importing it. I am unsure if this is achievab ...