How can I edit an element without altering the properties of the other elements?

Currently learning Vue 3 and new in stackoverflow.

I am trying to capture the id of an element, and based on it load an input to edit the value of the descriptionText property. The problem is that it edits the descriptionText property of all the elements, and I’m trying to make it happen only in one

I´m using vue-draggable-next and Sweetalert2 libraries on this project

<template>
  <head>
    <!-- Boxicons -->
    <link
      href="https://unpkg.com/[email protected]/css/boxicons.min.css"
      rel="stylesheet"
    />
  </head>

  <div class="container-fluid row mt-2">
    <div class="col-md-3 float-start">
      <div class="panel-default border" style="background-color: #f7f9fa">
        <div class="panel-heading text-center">
          <h3 class="panel-title visible-panel-text">Draggable elements</h3>
        </div>

        <!-- Elements zone -->
        <draggable
          class="row mt-2"
          :list="draggableElements"
          :sort="false"
          :group="{ name: 'cloneableItems', pull: 'clone', put: false }"
          @end="generateJSON"
        >
          <div
            class="col-sm-6 mb-2"
            v-for="element in draggableElements"
            :key="element.id"
          >
            <div class="border drag-element">{{ element.visibleName }}</div>
          </div>
        </draggable>

        <!-- Copy JSON panel -->
        <div
          class="panel-json json-container mt-2 border"
          style="background-color: #f7f9fa"
        >
          <div
            class="panel-heading text-center"
            @click="state.showJSONPanel = !state.showJSONPanel"
          >
            <h3
              class="panel-title"
              style="text-align: center; cursor: pointer; user-select: none"
            >
              JSON
            </h3>
          </div>
          <div class="panel-body" v-show="state.showJSONPanel">
            <textarea
              class="json-textarea form-control"
              v-model="state.generatedJSON"
              style="width: 90%; margin: 0 auto; resize: none"
            ></textarea>
            <button class="btn btn-secondary btn-sm" @click="copyJSON">
              Copy JSON
            </button>
          </div>
        </div>
      </div>
    </div>
    <div class="col-md-6">
      <!-- Show content -->
      <draggable
        class="w-100 h-100 border"
        :empty-insert-threshold="1000"
        :list="state.contentElements"
        @update="generateJSON"
        :group="{ name: 'putItems', pull: 'clone', put: true }"
      >
        <div
          v-for="element in state.contentElements"
          :key="element.id"
          class="container"
        >
          <template v-if="element.type == 'description'">
            <label>This is the description element</label>
            <div>{{ element.descriptionText }}</div>
          </template>

          <!-- Edit & delete -->
          <div
            class="iterable-icons-container"
            style="display: flex; justify-content: flex-end"
          >
            <!-- Edit icon -->
            <i class="bx bxs-cog edit-icon" @click="editElement(element.id)"></i>
            <!-- Delete icon -->
            <i class="bx bxs-trash-alt edit-icon" @click="deleteElement()"></i>
          </div>
        </div>
      </draggable>
    </div>

    <!-- Changes panel -->
    <div class="col-md-3 border">
      <div>
        <!-- Description -->
        <template
          v-if="
            state.editedId >= 0 &&
            state.contentElements[state.editedId].type == 'description'
          "
        >
          <label><strong>Description element</strong></label>
          <input type="text" v-model="edit.descriptionNewText" />

          <button class="btn btn-light" @click="saveChanges()">Save changes</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script setup>
import "bootstrap";
import "bootstrap/dist/css/bootstrap.css";

import { reactive, ref } from "vue";

//Drag and drop library
import { VueDraggableNext as draggable } from "vue-draggable-next";

//Sweetalert
import Swal from "sweetalert2";
import "sweetalert2/dist/sweetalert2.min.css";

//Array with the main elements list
const draggableElements = [
  {
    id: crypto.randomUUID(),
    visibleName: "Description",
    descriptionText: "This is a description that you can edit",
    type: "description",
    mandatory: false,
  },
];

//Variable where the data flows
let state = reactive({
  //Store a global index to edit
  editedId: ref(-1),
  contentElements: reactive([]),
  showJSONPanel: ref(false),
  generatedJSON: ref(""),
});

//eslint-disable-next-line
let edit = reactive({
  descriptionNewText: ref(""),
});

function copyJSON() {
  const textarea = document.querySelector(".json-textarea");
  textarea.select();
  document.execCommand("copy");
  Swal.fire("Success", "JSON copied", "success");
}

function generateJSON() {
  //Actualizar valor del textarea
  let textarea = document.querySelector(".json-textarea");
  textarea.value = state.generatedJSON;

  //Generar el archivo JSON de acuerdo a lo puesto por el usuario
  state.generatedJSON = JSON.stringify(state.contentElements, null, 2);
}

//Edit
function editElement(id) {
  const elementId = state.contentElements.findIndex((element) => element.id === id);
  state.editedId = elementId;

  const elementType = state.contentElements[state.editedId].type;

  console.log("Type is: ", elementType);
}

//Delete element
//Eliminar elemento del panel de construcción del formulario
function deleteElement(index) {
  Swal.fire({
    title: "Confirm delete",
    text: "Are you sure?",
    icon: "warning",
    showCancelButton: true,
    confirmButtonText: "Yes, delete",
    cancelButtonText: "Cancel",
  }).then((result) => {
    if (result.isConfirmed) {
      state.contentElements.splice(index, 1);
      state.generatedJSON = JSON.stringify(state.contentElements, null, 2);
    }
  });
}

//Save changes in the element
function saveChanges(type) {
  type = state.contentElements[state.editedId].type

  console.log("Type is: ", type)

  switch(type){
    case 'description':
      //Description data
      state.contentElements[state.editedId].descriptionText = edit.descriptionNewText;

      state.editedId = -1
      edit.descriptionNewText = ""
      break;
  }
}
</script>

<style scoped>
.drag-element {
  cursor: pointer;
}

.edit-icon {
  font-size: 25px;
}
.edit-icon:hover {
  color: blueviolet;
  cursor: pointer;
}
</style>

I have been searching the internet for methods to asolve this, or at least approach, but I have not been able to find anything.

How to use regex to extract a substring, manipulate the substring and re-insert it?

I have this Odata query string (I’ve split the string over 3 lines for easier reading but in reality is a single line)

/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20
PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z%20and%20
ForeignBarcode%20eq%20'abcd1234'

In Javascript, I need to manipulate the purchase-date parameter like so, from

PurchaseDate%20nIN%202023-11-20T00%3A00%3A00.000Z

to

date(PurchaseDate)%20eq%202023-11-20

(that is: add the date function with brackets, change nIN to eq and strip the time)

Question: Is there a regex one liner to do this?

Here is my attempt

//define the input

let input =
"/odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20PurchaseDate%20nIN%202023-02-02T23%3A00%3A00.000Z%20and%20ForeignBarcode%20eq%20'abcd1234"


//extract the date (using look behind and look ahead)
let rdate = /(?<=PurchaseDate%20nIN%20)d{4}-d{2}-d{2}(?=Td{2}%3Ad{2}%3Ad{2}.d{3}Z)/
let date = rdate.exec(input)

//use regex and some string manipulation to replace the orignal substring
input.replace(/PurchaseDate%20nIN%20d{4}-d{2}-d{2}Td{2}%3Ad{2}%3Ad{2}.d{3}Z/,`date(PurchaseDate%20eq%20${date[0]})`)

//result
// /odata/businessreport?%24top=25&%24skip=0&%24count=true&%24format=application%2Fjson%3Bodata.metadata%3Dfull&%24filter=()%20and%20date(PurchaseDate)%20eq%202023-02-02)%20and%20ForeignBarcode%20eq%20'abcd1234

shopping cart — how to get total quantity, pricing decimal

I downloaded a Javascript-based shopping cart. It works fine, but:

  1. “total quantity” is not shown up.
    How to get the total quantity, and show it up when buyer click “add to cart”?

  2. the total amount is not decimal.It shows the whole number only.
    How to get it to be decimal like “6.38 USD” or “6.00 USD”?

  3. When increase the quantity of the items, the unit price is changed from decimal to whole number.

link to the shopping cart: https://www.check.com.cn/shop.html

very much want to get them done.

Here is the link: https://www.check.com.cn/shop.html
below is the javascript code:

==================================


"use strict";                        
let cart = [];
let cartTotal = 0;
    //cartTotal = cartTotal.toFixed();
const cartDom = document.querySelector(".cart");
const addtocartbtnDom = document.querySelectorAll('[data-action="add-to-cart"]');

addtocartbtnDom.forEach(addtocartbtnDom => {
    addtocartbtnDom.addEventListener("click", () => {
    const productDom = addtocartbtnDom.parentNode.parentNode;
    const product = {
      img: productDom.querySelector(".product-img").getAttribute("src"),
      name: productDom.querySelector(".product-name").innerText,
      price: productDom.querySelector(".product-price").innerText,
      quantity: 1
   };

const IsinCart = cart.filter(cartItem => cartItem.name === product.name).length > 0;
if (IsinCart === false) {
  cartDom.insertAdjacentHTML("beforeend",`
  <div class="cart flex-row card plus_minu">
       <div class="flex_cell">
            <img src="${product.img}" alt="${product.name}" style="width:6.5vw;"/>
            </div>
       <div class="flex_cell">
            <p class="cart_item_name" style="font-size:1.5vw;">${product.name}</p>
            </div>
       <div class="flex_cell">
            <p class="cart_item_price" style="font-size:1.5vw;">${product.price}</p>
            </div>
       <div class="flex_cell">
            <button class="btn_plus_minu" type="button" data-action="increase-item">&plus;
            </div>
       <div class="flex_cell">
            <p class="cart_item_quantity" style="background-color: yellow border: 1px blue dotted">${product.quantity}</p>
            </div>
       <div class="flex_cell">
            <button class="btn_plus_minu" type="button" data-action="decrease-item">&minus;
            </div>
       <div class="flex_cell">
            <button class="btn_plus_minu" type="button" data-action="remove-item">&times;
            </div>
   </div> `);

  if(document.querySelector('.cart-bottom') === null){
    cartDom.insertAdjacentHTML("afterend",  `
      <div class="flex-bottom card cart-bottom ">
           <div class="flex_cell">
                <button class="btn_clear" type="button" data-action="clear-cart">Clear Cart
                </div>
           <div class="flex_cell">
                <button class="btn_buy" type="button" data-action="check-out">Buy now: <span class="pay" ></span>
                </div>

      </div>`); }

    addtocartbtnDom.innerText = "Added!";
    addtocartbtnDom.disabled = true; /*---- when it's disabled =true, button greyed out---*/
    cart.push(product);

    const cartItemsDom = cartDom.querySelectorAll(".plus_minu");
    cartItemsDom.forEach(cartItemDom => {

    if (cartItemDom.querySelector(".cart_item_name").innerText === product.name) {

      cartTotal += parseInt(cartItemDom.querySelector(".cart_item_quantity").innerText) 
      * parseInt(cartItemDom.querySelector(".cart_item_price").innerText);
      
      document.querySelector('.pay').innerText = cartTotal + " USD";
      document.querySelector('.pay1').innerText = cartTotal + " USD";
      document.querySelector('.pay2').innerText = cartTotal + " USD";
      document.querySelector('.pay3').innerText = cartTotal + " USD";

      // increase item in cart
      cartItemDom.querySelector('[data-action="increase-item"]').addEventListener("click", () => {
        cart.forEach(cartItem => {
          if (cartItem.name === product.name) {
            cartItemDom.querySelector(".cart_item_quantity").innerText = ++cartItem.quantity;
            cartItemDom.querySelector(".cart_item_price").innerText = parseInt(cartItem.quantity) *
            parseInt(cartItem.price) + " USD";
            cartTotal += parseInt(cartItem.price)
            document.querySelector('.pay').innerText = cartTotal + " USD";
            document.querySelector('.pay1').innerText = cartTotal + " USD";
            document.querySelector('.pay2').innerText = cartTotal + " USD";
            document.querySelector('.pay3').innerText = cartTotal + " USD";
          }
        });
      });

      // decrease item in cart
      cartItemDom.querySelector('[data-action="decrease-item"]').addEventListener("click", () => {
        cart.forEach(cartItem => {
          if (cartItem.name === product.name) {
            if (cartItem.quantity > 1) {
              cartItemDom.querySelector(".cart_item_quantity").innerText = --cartItem.quantity;
              cartItemDom.querySelector(".cart_item_price").innerText = parseInt(cartItem.quantity) *
              parseInt(cartItem.price) + " USD";
              cartTotal -= parseInt(cartItem.price)
              document.querySelector('.pay').innerText = cartTotal + " USD";
              document.querySelector('.pay1').innerText = cartTotal + " USD";
              document.querySelector('.pay2').innerText = cartTotal + " USD";
              document.querySelector('.pay3').innerText = cartTotal + " USD";
            }
          }
        });
      });

      //remove item from cart
      cartItemDom.querySelector('[data-action="remove-item"]').addEventListener("click", () => {
        cart.forEach(cartItem => {
          if (cartItem.name === product.name) {
              cartTotal -= parseInt(cartItemDom.querySelector(".cart_item_price").innerText);

              document.querySelector('.pay').innerText = cartTotal + " USD";
              document.querySelector('.pay1').innerText = cartTotal + " USD";
              document.querySelector('.pay2').innerText = cartTotal + " USD";
              document.querySelector('.pay3').innerText = cartTotal + " USD";

              cartItemDom.remove();
              cart = cart.filter(cartItem => cartItem.name !== product.name);
              addtocartbtnDom.innerText = "Add to cart";
              addtocartbtnDom.disabled = false;
          }
          if(cart.length < 1){
            document.querySelector('.cart-bottom').remove();
          }
        });
      
      
      
      });

      //clear cart
      document.querySelector('[data-action="clear-cart"]').addEventListener("click" , () => {
        cartItemDom.remove();
        cart = [];
        cartTotal = 0;
        if(document.querySelector('.cart-bottom') !== null){
          document.querySelector('.cart-bottom').remove();
        }
        addtocartbtnDom.innerText = "Add to cart";
        addtocartbtnDom.disabled = false;
/*
        setTimeout(function(){
          window.location.reload();
       }, 100);
*/

      });

      document.querySelector('[data-action="check-out"]').addEventListener("click" , () => {
        if(document.getElementById('paypal-form') === null){
          checkOut();
        }
      });
    }
  });
}
});
});
/*
function animateImg(img) {
  img.classList.add("animated","shake");
}

function normalImg(img) {
  img.classList.remove("animated","shake");
}
*/
function checkOut() {
  let paypalHTMLForm = `
  <form id="paypal-form" action="https://www.paypal.com/cgi-bin/webscr" method="post"  target="paypal">  
    <input type="hidden" name="cmd" value="_cart">
    <input type="hidden" name="upload" value="1">
    <input type="hidden" name="business" value="[email protected]">
    <input type="hidden" name="currency_code" value="USD">`;   /* replace "USD" with "USD" */

  cart.forEach((cartItem,index) => {
   ++index;
   paypalHTMLForm += ` <input type="hidden" name="item_name_${index}" value="${cartItem.name}">
    <input type="hidden" name="amount_${index}" value="${cartItem.price.replace("USD.","")}">  
    <input type="hidden" name="quantity_${index}" value="${cartItem.quantity}">`;
  });
 
  paypalHTMLForm += `<input type="submit" value="PayPal" class="paypal">
  </form><div class="overlay">Please wait...</div>`;
  document.querySelector('body').insertAdjacentHTML("beforeend", paypalHTMLForm);
  document.getElementById("paypal-form").submit();
 /*
  const cartDomAAA = document.getElementById("cart_test");
  cartDomAAA.remove();*/
  setTimeout(function(){
    window.location.reload();
 }, 100);
}



Set checkbox to checked by comparing values from 2 arrays in Angular and build formArray

I have 2 arrays.

arr1

[
    {
        "id": 12,
        "name": "X",
        "description": "text"
    },
    {
        "id": 13,
        "name": "Y",
        "description": "text"
    }
]

arr2

{
    "id": 13,
    "name": "Y",
    "description": "text"
}

I have a method in my TS file to build a form

 buildFoodForm(item) {
        console.clear();
        console.log(this.arr1); // OK
        console.log(this.arr2); // OK
        const fArray = this.arr1.map(m=> new FormControl(false)); // generates unchecked checkboxes
    
        this.form = this.formBuilder.group({
          id : item.id === 0 ? this.id : this.id.setValue(item.id),
          name : item.name === '' ? this.name : this.name.setValue(item.name),
          xx : fArray //How to properly bind it to formBuilder ?
        })
      }

HTML

 <label  *ngFor="let x of arr1">
      <mat-checkbox class="example-margin" [formArray]="arr1" [value]="x.id"  [checked]="arr2.includes(x)">
      {{x.name}}
      </mat-checkbox>
    </label>

arr2 is included in arr1
How to generate a list of checkboxes which are ‘checked’ ?

I also simply tried doing this but it does not work

<div *ngFor="let x of arr1">
    <input type="checkbox"  [checked]="arr2.includes(x)">
      {{x}}
</div>

Circular audio player to be extrapolated on this site need

I need to extrapolate from this site: https://auxnyc.com/case-studies/forme-audio-branding their circular audio player with an urgent need, can you help me get the code to use on another website ?
I would need all the components to customise it and replicate it similarly.
I would have to insert more than one on the same page as in this case, alternatively if you have other solutions always for the same type it would still be great, I’m looking for a circular audio player like this one, that works both on mobile(iphone) and desktop.
Thanks in advance 🙂

I have already tried a similar code on the site but I can only put one per page and I would need more than one of these players, all working

inline event handler nested within a javascript – Refused to execute inline event handler because it violates the following Content Security Policy

Preface: Hashes belonging to all known or identifiable Javascripts have been included in the CSP Header.

When I click on the custom Facebook share button, I get the following error:

Refused to execute inline event handler because it violates the
following Content Security Policy directive: “script-src…”

From within the browser console I see that the error refers to a generic <! DOCTYPE html> X which is in the HTML page where external Javascripts are called.

It looks like the called inline event handler is nested within a Javascript (this Javascript has its own hash in the CSP header and it is called from the HTML page bentioned above):

INLINE EVENT HANDLER:

var s = new Array(‘”#”
onclick=”window.open(‘//www.facebook.com/sharer/sharer.php?u=’ + u +
”, ‘_blank’, ‘scrollbars=0, resizable=1, menubar=0, left=100,
top=100, width=550, height=440, toolbar=0, status=0’);return false”
title=”share on example”‘);

var l = “”;

for (j = 0; j < s.length; j++) l += ‘<a rel=”noopener noreferrer” style=”display:inline-block;vertical-align:bottom;width:32px;height:32px;margin: 10px 10px 10px 10px;padding:0;outline:none;background:url(‘ + f + fn + “) -” + 32 * j + ‘px 0 no-repeat” href=’ + s[j] + ‘ target=”_blank”>’;

e[k].innerHTML = ‘< span id=”share” >’ + l + “< /span >”;

The event handler should open a new browser’s window but it fails generating the error in the subject. However, it opens a new browser’s tab reloading the same page (it does not open facebook.com).

If I disable the CSP in the header, everything works fine.

Unfortunately, I am unable to identify the exact inline event handler for generating the correct hash.

Is there any effective debugging tool or technic for tracing the precise code which is triggering the error, or any other way to resolve this issue?

ChartJS + SQL problem of non-existent dates and values

Good afternoon!

I encountered a problem with displaying dates and values.

Task: display a chart of client registrations by day. Now the chart displays only dates that have records. I need a date with a value of 0 to be displayed when a record is deleted. So that there are columns on the chart from the first to the midday of the month

Result ScreenShoot

PHP:

<?php 
  $conn = new mysqli('localhost','test','password','test');
  $query = $conn->query("
    SELECT 
    DATE(date) as monthname,
    COUNT(id) as amount
    FROM clients WHERE date BETWEEN '2023-01-09' AND '2024-01-09' 
    GROUP BY monthname 
  ");

  foreach($query as $data) {
    $month[] = $data['monthname'];
    $amount[] = $data['amount'];
  }
?>

JavaScript:

<script>
  const labels = <?php echo json_encode($month) ?>;
  const data = {
    labels: labels,
    datasets: [{
      label: 'Clients',
      data: <?php echo json_encode($amount) ?>,
      backgroundColor: [
        'rgba(255, 99, 132, 0.2)',
        'rgba(255, 159, 64, 0.2)',
        'rgba(255, 205, 86, 0.2)',
        'rgba(75, 192, 192, 0.2)',
        'rgba(54, 162, 235, 0.2)',
        'rgba(153, 102, 255, 0.2)',
        'rgba(201, 203, 207, 0.2)'
      ],
      borderColor: [
        'rgb(255, 99, 132)',
        'rgb(255, 159, 64)',
        'rgb(255, 205, 86)',
        'rgb(75, 192, 192)',
        'rgb(54, 162, 235)',
        'rgb(153, 102, 255)',
        'rgb(201, 203, 207)'
      ],
      borderWidth: 1
    }]
  };
  const config = {
    type: 'bar',
    data: data,
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    },
  };

  var myChart = new Chart(
    document.getElementById('myChart'),
    config
  );
</script>
SELECT 
DATE(date) as monthname,
COUNT(id) as amount
FROM leads WHERE date BETWEEN '2023-01-09' AND '2024-01-09'
GROUP BY monthname 

JavaScript is automatically adding 1 to my number [duplicate]

I was working on a project where some API was sending the ID to me and the ID was pretty long. I stored that into a number in JavaScript and it automatically added 1 to the ID.
Here’s the code if anyone wants to try

let a = 9273528282721259;
console.log(a);

Can anyone let me know why is it occurring? You can try this in your browser console too. It took me many days to find this bug.

I tried to make it into a string but first I had to store it into a number to cover. I even tried BigInt but the issue still persist.

How to prevent page scrolling if I am over iframe?

I have iframe on my page. The iframe does not have more content than it’s height but it does use mousewheel for zooming. When I mousewheel on main page it scrolls the main page, when I am over the iframe, it also scrolls the main page. I want iframe to use catch mousewheel events and prevent parent page to scroll.

I want this page to be scrollable but when you are over the iframe page should not be scrollable

<br>
<iframe src="https://ghost.sk/bug/iframe-scroll-child.html"></iframe>
<br>

Here I try use scrolling="yes":<br>

<br>
<iframe src="https://ghost.sk/bug/iframe-scroll-child.html" scrolling="yes"></iframe>
<br>


<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable
<br>More text to make page scrollable

How to retain value of field in JS

I have one multi-select field whose values are coming from one table which has the following data.

Desc      | Code
----------------
India     | IN
Australia | AUS
Other     | OTH

Requirement: In that multi-select field if Other then a new field is getting populated as Please specify (Others) in which we will add some text value.

  1. If I am selecting India, Other, Australia then the Please specify (others) should be enabled and the text which the user has written should be retained in please specify others field.

  2. If I am selecting India, Other then removing Other and again selecting other then value of Please specify(others) should be blank.

Problem: When I am selecting India, Other, Australia then the Please specify (others) field value is getting nullified.

My attempt:

     function showHideOthers(){
    var selectedValue = $("#field_id_ui").val();
    for (var i=0; i< selectedValue.length; i++){
    if (selectedValue[i] =="OTH"){
      $("#Others_section").show();
    }
    else{
      $("#Others_section").hide();
    $("#Others_section").val('');
    }
    }
    }
else{
$("#Others_section").hide();
    $("#Others_section").val('');
}
    }

The fields for show and hide are taken from VTL file.

ts(1005) error and console log error “Uncaught SyntaxError: Unexpected identifier ‘location'” (line 32)

The bigger picture

I am a new student and I have been given this challenge on branching logic. I have solved it so far except for one error I am getting on my very last line, line 32:

line 32: location === 'NK' ? console.log(BANNED_WARNING) : console.log('Price:', currency, shoes + batteries + pens + shirts + shipping)

**Error(s): **

  1. Within VSCode, “location” is underlined in red with the following: : expected. ts(1005)
  2. In my DevTools console log: Uncaught SyntaxError: Unexpected identifier ‘location’

**Here is all of my code: **

const FREE_WARNING = 'Free shipping only applies to single customer orders'
const BANNED_WARNING = 'Unfortunately we do not ship to your country of residence'
const NONE_SELECTED = 0

let customers = 1
let location = 'RSA'
let currency = null
let shipping = null

if (location === 'RSA') {
  shipping = 400, currency = 'R';
}

if (location === 'NAM') {
  shipping = 600, currency = '$'
} else {
  shipping = 800, currency = '$'
}


let shoes = 300 * 1
let toys = 100 * 5
let shirts = 150 * NONE_SELECTED
let batteries = 35 * 2
let pens = 5 * NONE_SELECTED

if (location === 'RSA' && shoes + batteries + pens + shirts >= 1000) { shipping = 0 }
if (location === 'NAM' && shoes + batteries + pens + shirts >= 60) {shipping = 0}

shipping === 0 && customers !== 1 ? console.log(FREE_WARNING)

**location === 'NK' ? console.log(BANNED_WARNING) : console.log('Price:', currency, shoes + batteries + pens + shirts + shipping)**

I have tried with the help of Bito.AI and ChatGPT to resolve it but nothing has helped.

I have:

  1. Added semi-colons where necesarry
  2. Changed “let location” to “let locationValue” and changed it everywhere necessary. According to Bito.AI that was a possible resolution.
  3. Changed it from a tenary back to a normal if loop.

Netlify-hosted Next.js API returning 502 error for all APIs

I’m currently hosting a Next.js application on Netlify, and I’ve encountered a puzzling issue with my API routes. When I attempt to access any of my API routes from the client-side, I’m consistently receiving a 502 Bad Gateway error in the console. This issue does not occur when I run the application locally. The error message in the console is as follows:

GET https://example.com/api/testApi 502

I’ve double-checked my code, environment variables, and the Netlify configuration, but I can’t seem to pinpoint the root cause of this problem. It’s affecting ALL my API routes, not just one specific route.

Here are a few details about my setup:

My environment variables are correctly set in the Netlify environment.
My local development environment works perfectly, and I can access the API routes without any issues.
Is there anything I might be overlooking or any common pitfalls related to Netlify-hosted Next.js applications that could cause this 502 error? I’d appreciate any guidance or suggestions to help diagnose and resolve this issue.

here are the codes i am using :
for the api/testApi code: note this code is inside pages/api/testApi

// pages/api/testApi.js

exports.handler = async (event, context) => {
    const response = {
      statusCode: 200,
      headers: {
        "Access-Control-Allow-Origin": "*",
        "Access-Control-Allow-Headers": "Content-Type",
        "Access-Control-Allow-Methods": "GET, POST, OPTION",
      },
      body: JSON.stringify({ message: "Hello World" })
    };
    return response;
  };

for the Frontend code TestButton.js

// components/TestButton.js

import { useState } from 'react';

const TestButton = () => {
  const [message, setMessage] = useState('');

  const testApi = async () => {
    try {
      const response = await fetch('/api/testApi');
      const data = await response.json();
      setMessage(data.message);
    } catch (error) {
      setMessage('An error occurred.');
    }
  };

  return (
    <div>
      <button onClick={testApi}>Test API</button>
      <p>{message}</p>
    </div>
  );
};

export default TestButton;

my current netlify.toml:

[build]
  command = "next build"
  publish = ".next"

[[plugins]]
  package = "@netlify/plugin-nextjs"

[functions]
  included_files = [".next/*.json"]

Thank you in advance for your assistance!

kafka for pure javascript without nodejs

I’m working on a project where I need to consumer topic from an Apache Kafka topic using pure JavaScript.(Without Node) Is there a way to achieve this ?

Additionally, any tips or best practices for working with Kafka in JavaScript would be greatly appreciated

DNS address could not be found when deploying node application with iisnode

I have a machine running Windows Server 2012 R2 and I have been trying to deploy a simple node application using iisnode.

I have tried to achieve this in 2 ways. The first one, set up IIS as a reverse proxy. For this I followed this article “https://dev.to/petereysermans/hosting-a-node-js-application-on-windows-with-iis-as-reverse-proxy-397b”.

And the second way, using iisnode which is described here: host node js on windows server (iis).

I followed both methods step by step, but I het the same result. “DNS address could not be found”

I have tried to fix this in the following ways:

  • clear the host cache in my browser
  • restart “DNS Client”
  • change DNS settings (set DNS server address to 8.8.8.8 and 8.8.4.4, which led brought “DNS address could not be found” errors when I tried to access any website, not just mine)
  • delete files from “etc” folder (I restarted my computer afterwards)
  • flush, renew, reset the DNS, which did not finish successfully, here it the responce that I got:
    enter image description here

I cant figure out why I am getting the “The operation failed ad no adapter is in the state permissible for this operation” error. When I run “ipconfig /all” they show up fine. Is there something wrong with the firmware/drivers or maybe there is something that I have not set correctly in the IIS Manager?