Why data view impression promotion Google Analytics report is always 0?

I created an event impression promotion for google analytics, I have 2 events view_promotions and also select_content. In the report in GA for select_content the data is correct, but for view_promotion it is always 0. Is there something wrong with my code using push array like the code that I’ve made below?

const impressionBanner = [];

$(".banner-link").each(function(){
  const data = $(this).data('banner');

  impressionBanner.push({
    "id": data.id,
    "name": data.name
  })

  gtag('event', 'view_promotion', {
    impressionBanner
  });
})

$('.banner-link').each(function(){
  $(this).on("click", function(e){
    e.preventDefault()
    const data = $(this).data('banner')
    console.log(data)

    gtag('event', 'select_content', {
      "promotions": [
        {
          "id": data.id,
          "name": data.name
        }
      ]
    });
  })
})
.banner-link{
  width: 100px;
  height: 50px;
  background-color:red;
  margin:5px;
  color:#fff;
  text-align:center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="banner-link" data-banner='{"id" : "1" , "name" : "Banner 1"}'>
  Banner 1
</div>
<div class="banner-link" data-banner='{"id" : "2" , "name" : "Banner 2"}'>
  Banner 2
</div>
<div class="banner-link" data-banner='{"id" : "3" , "name" : "Banner 3"}'>
  Banner 3
</div>

How to make the file name appear next to the Input type of file while editing?

<input type="file" #file [(ngModel)]="model.Profile" (change)="upload($event, 'Profile')" class="form-control" id="Profile" name="Profile" required />

.getFiles(Id)
        .subscribe((s: any) => {
          this.model = s;
}

Now the this.model is populated with the data and everything and every field works. Even the data in model.Profile is populated but on the UI the name of the file next to the input doesn’t appear like the way it appears when we normally upload. How to make that happen?

It’s a template driven form.

i want to bind variables to a custom component but it is rending as a string only in vue

Hi i’m using google https://modelviewer.dev/editor/ <model-viewer> which is a custom component for vue i don’t want to compile it through vue so i’m using v-pre directive

<model-viewer v-pre></model-viewer>

but the problem is <model-viewer src=""> expect src that i need to give through view which is rendering as a string only

data(){
   return {
      path: '../path'
   }
}

<model-viewer :src="path"></model-viewer> <-- rendered code

My Question: my path is binding as a string to <model-viewer> how it will yeild path value.

Note: if i remove v-pre on <model-viewer> compile or build will fail, vue throws error unknown element <model-viewer>

Wait for prior fetch to finish aborting before proceeding

Right now I have code that is basically:

var loadingIndicator = /* Reference to UI component */,
    output = /* Reference to UI component */,
    abortController;

function onThingRequested(thing) {
    abortController?.abort();
    requestThing(thing);
}

async function requestThing(thing) {
    abortController = new AbortController();
    output.innerText = '';
    loadingIndicator.show();
    try {
        console.log(`STARTING ${thing}`);
        // For the sake of brevity of the example, assume `thing` is safe to put here.
        var thingRes = await fetch(`/example?thing=${thing}`, { signal: abortController.signal });
        output.innerText = await thingRes.text();
    } catch (err) {
        console.log(`ERRORED ${thing}`);
        output.innerText = err;
    } finally {
        console.log(`FINALLY'D ${thing}`);
        loadingIndicator.hide();
    }
}

If I trigger onThingRequested('thing1') and then, before it loads, trigger onThingRequested('thing2'), the output is, of course…

STARTED thing1
STARTED thing2
ERRORED thing1
FINALLY'D thing1
FINALLY'D thing2

…because requestThing triggers the new fetch immediately, while the abort happens asynchronously. Is there any elegant way to wait for the prior fetch to finish aborting before proceeding? Besides, of course, the hacky-feeling workaround of…

function onThingRequested(thing) {
    abortController?.abort();
    setTimeout(() => requestThing(thing), 1);
}

spliting an array into different arrays using javascript

I had a array of size dynamic..I need the split the array whenever the user click on particular element in that array.I user can have multiple clicks on different elements.
So we dont have a exact number to split the array..
suppose we have an array consists of 100 elements. the user clicks on the 3rd element in the array then the array should split into 2 different array..one should store (1 ,2) an the other should store (3 – 100)elements. and again the user clicks on the 10 element then array should split and in one array it should store (3 – 9) another one should have (10 – 100)elements..like that the user can have many clicks.and at every time the array should split.
Can I a solution for this using javascript?

How to reduce the use of conditions in React.js

I have a block of codes in React.js which I believe is not the best way to do it. However, I am not sure how I can simplify and optimize it. Does anyone have any ideas? Thanks so much

const url = new URL(window.location.href);
let date = "";
let locationId = 0, movieId = 0;

const urlDate = url.searchParams.get("date");
if (urlDate) {
    if (dateSelectors.filter(x => x.code === urlDate).length > 0) date = urlDate;
    else toast.error("Date retrieved from the URL is invalid");
}
const urlMovie = url.searchParams.get("movieId");
if (urlMovie && urlMovie !== "0") {
    if (!Number.isNaN(+urlMovie) && movieSelectors.filter(x => x.code === urlMovie).length > 0) movieId = urlMovie;
    else toast.error("Movie Id retrieved from the URL is invalid");
}
const urlLocation = url.searchParams.get("locationId");
if (urlLocation && urlLocation !== "0") {
    if (!Number.isNaN(+urlLocation) && locationSelectors.filter(x => x.code === urlLocation).length > 0) locationId = urlLocation;
    else toast.error("Theatre Id retrieved from the URL is invalid");
}

Can it possbile to connect mongodb atlas with linux cPanel nodeJS sofrware

I build an application with Vue, node js, and MongoDB.
Here I am using Mongo Atlas. But some error accrued here. When I made and run in localhost all the mongo connections and queries worked fine. When I go to deploy it in Cpanel it rising some bugs. Such as Primaryreplicanotset. Can anybody tell me the actual connection from the Cpanel Nodejs app code?

I am using npm mongobd.

Google sheet setValues

I would like to write some data to a spreadsheet using setValues function.
Runing the code below return the message:
“Exception: The parameters (number[]) don’t match the method signature for SpreadsheetApp.Range.setValues.”

var ss= SpreadsheetApp.openByUrl(ss_url);
var ws = ss.getSheetByName("Liste");
 var data=["1","2", "3", "4"];
ws.getRange(2,5,1,4).setValues(data);

How to trigger a particular button click event automatically on each change in front end input field

I have an order page where I need to get all product prices and apply some calculations to find out the final price.
I have done all these calculations and displayed the results there using button click event by jQuery.

But whenever I update the input fields, I need to click on the button to update previously calculated result and show new one.

How can I’m done this without button click? If any change in the whole content happened, I need to trigger the button click automatically.

If it is possible to do via Ajax, Can you please help me?

Please find my current jQuery code given below.

//Update data corresponding to change in value of days field
$(document).on('change', '#order-edit-extracost', function(e) {
    var days = $('#order-edit-extracost').val();
    var cost = (parseFloat(days) * 0.5).toFixed(2);
    $('#order-edit-extracost-sum').val(cost);
})

// Order page Price calculations
$(document).on('click', '#calculate-cost', function(e) {
    var prev_cost = $('.total-prev').html();
    var prev_cost_float = parseFloat(prev_cost.match(/-?(?:d+(?:.d*)?|.d+)/)[0]);
    var wastetype_sum = 0;
    //find sum of all wastetype rows
    $( '.order-wastetypeRow' ).each(function( index ) {
      var wastetype_price = $(this).find('#order-edit-wasteprice').val();
      prev_cost_float = parseFloat(prev_cost_float) + parseFloat(wastetype_price);      
    });
    //calculate VAT and add it to the sum
    var extra_cost = $('#order-edit-extracost-sum').val();
    var final_cost = (parseFloat(prev_cost_float) + parseFloat(extra_cost)).toFixed(2);
    $('.est-cost').html("CHF "+final_cost);
    var vat_in_float = parseFloat(final_cost);
    var vat_amount = (vat_in_float * 0.077).toFixed(2);
    $('.final-vat').html("CHF "+vat_amount);
    var total = (parseFloat(final_cost) + parseFloat(vat_amount)).toFixed(2);
    //show calculated costs
    $('.final-amount').html("CHF "+total);
    $('#finalcost-layout').show();
    $('.submit-cost').show();
});

How to get the JSON object value based on a certain condition in JavaScript?

I am playing with JSON objects. And I came across a challenging situation for me:

basically I have a JSON object:

let cinfo = {
   "costing_T063623477Z":{
      "service":[
         {
            "objid":"T063637283Z",
            "serviceid":"SRV2100003",
            "servicename":"FABRICATION OF SPRINKLER & HOSE",
            "estimatedprice":"10000.00",
            "description":"sdfg",
            "laborcost":"500.00"
         }
      ],
      "othercharges":[
         {
            "objid":"T063911531Z",
            "description":"Other Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063906963Z",
            "description":"Sales Expenses",
            "amount":"345.00",
            "remarks":"345"
         },
         {
            "objid":"T063730836Z",
            "description":"Delivery Expenses",
            "amount":"345.00",
            "remarks":"345"
         }
      ]
   }
}

I have something that can get the values of a specific object:

Object.keys(cinfo).forEach(function(ckey) {
     cinfo[ckey].service.forEach(function(skey){
         console.log(skey.laborcost);
     })
})

Based on the object above, the console output is: 500.00

But, I want something conditional when it comes to othercharges object.
I need to get the amount based only on the description:

Something like this:

Object.keys(cinfo).forEach(function(ckey) {
     cinfo[ckey].othercharges.forEach(function(skey){
          console.log(skey.amount) //-> where "description" = "Other Expenses";
          console.log(skey.amount) //-> where "description" = "Sales Expenses";
          console.log(skey.amount) //-> where "description" = "Delivery Expenses";
     })
}

How to make it possible? Thanks.

Chartjs-gauge create circumference until certain value from data

I am creating 5 sections of gauge using chartjs-gauge. I am using the following data.

[150,200,250,300,400]

From this data, I want to display the circumference until 300. But the angle should calculated by including the last section value too. I had custom the text showing in section by setting it to empty string if more than 300. For section colour, I set 4 colours["green", "yellow", "orange", "red"]. Now, last section showing as silver colour which is default background of gauge. I have add rgba(0,0,0,0) to colour array ["green", "yellow", "orange", "red","rgba(0,0,0,0)"] which will show transparent colour for last section. But, when hover on section, it is responsive showing border. I would like to know if have other way to show the circumference until certain value from our data ,but calculating section area in chart using all value from data.

var data = [150, 200, 250, 300, 400];

var config = {
  type: "gauge",
  data: {
    labels: ['Success', 'Warning', 'Warning', 'Error'],
    datasets: [{
      data: data,
      value: 300,
      backgroundColor: ["green", "yellow", "orange", "red"],
      borderWidth: 2
    }]
  },
  options: {
    responsive: true,
    title: {
      display: true,
      text: "Gauge chart with datalabels plugin"
    },
    layout: {
      padding: {
        bottom: 30
      }
    },
    needle: {
      // Needle circle radius as the percentage of the chart area width
      radiusPercentage: 2,
      // Needle width as the percentage of the chart area width
      widthPercentage: 3.2,
      // Needle length as the percentage of the interval between inner radius (0%) and outer radius (100%) of the arc
      lengthPercentage: 80,
      // The color of the needle
      color: "rgba(0, 0, 0, 1)"
    },

    valueLabel: {
      formatter: Math.round
    },
    plugins: {
      datalabels: {
        display: true,
        formatter: function(value, context) {
          //return '>'+value;
          if (value <= 300) {
            return value;
          } else {
            return '';
          }

        },
        color: function(context) {
          //return context.dataset.backgroundColor;
          return 'black';
        },
        //color: 'rgba(255, 255, 255, 1.0)',
        /*backgroundColor: "rgba(0, 0, 0, 1.0)",*/
        borderWidth: 0,
        borderRadius: 5,
        font: {
          weight: "bold"
        }
      }

    }
  }
};

window.onload = function() {
  var ctx = document.getElementById("chart").getContext("2d");
  window.myGauge = new Chart(ctx, config);
};
canvas {
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="en-US">
<head>
  <script src="jQuery/jquery-3.4.1.min.js"></script>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Gauge Chart with datalabels plugin</title>
  <script src="https://unpkg.com/[email protected]/dist/Chart.bundle.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/chartjs-gauge.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/chartjs-plugin-datalabels.js"></script>
</head>
<body>
  <div id="canvas-holder" style="width:100%">
    <canvas id="chart"></canvas>
  </div>
</body>
</html>

JQuery Datatable Convert Serialized data into a formatted JSON on Submit Form

I have a datatable inside a form with the data generated using a JQuery DataTable with one of the columns have a select list control

JS:

$(".detailTbl").DataTable({
                "ajax": {
                    "url": loadDetailHeader + "?code=" + code + "&ver=" + ver,
                    "type": "POST",
                    "dataSrc": ""
                },
                "columns": [
                    {
                        "data": null,
                        "render": function (data, type, full, meta) {
                            return meta.row + 1;
                        }
                    },
                    {
                        "data": "approverPositionId",
                        "render": function (data) {
                            return createListPosition(data,buttonCount)
                        }
                    },
                    {
                        "data": null,
                        "defaultContent": "<i class='fa fas fa-trash-alt' onclick='deleteNewRow(this)'></i>"
                    }
                ],
                "serverSide": false, // for process server side    
                "filter": false, // this is for disable filter (search box)    
                "orderMulti": false, // for disable multiple column at once,
                "info": false,
                "paging": false
            })

I also added a function to add new row to the datatable:

var t = $(".detailTbl").DataTable()
    t.row.add([
        null,
        null,
        null
    ]).draw();
    buttonCount = buttonCount+1

everytime a new row button is clicked it run the add new row function. after finish adding the neccessary data, a submit button is clicked to save all the data in the datatable.

After reading the docs and some posts out there i managed to get the data but the result isn’t what i was expecting.

enter image description here

function saveDetail() {
    var t = $(".detailTbl").DataTable()
    var data = t.rows().data().toArray()
    var data2 = t.$('select').serialize()
    console.log(data)
    console.log(data2)
}

Result:

enter image description here

as you can see the serialize method worked fine but i have no idea how to convert it to a json like this:

[
{ "posId": detail-select-1.value},
{ "posId": detail-select-2.value},
{ "posId": detail-select-3.value}
.... and so on
]

Is there a way to do it? Other solution is also welcomed.

Sorry for making this too long

Autoplay Audio in Loop

i am looking for autoplay an audio in loop without getting blocked by browser.

Code :

<audio id="audio1" src="assest/sound/1.mp3" autoplay="" />
      <script>
         a = document.getElementById('audio1');
         
         a.onended = function(){setTimeout("a.play()", 1000)}
      </script>

My current code working on firefox but in default it is blocked, i have to allow autoplay manually so it can play the audio and in other side in chrome the audio is not even playing.

Any solution for this?