Remove [[Prototype]] : Object / From Array / DataCloneError Error Dexie indexDB Put

I am trying to save an array to indexDB via Dexie and I’m getting a DataCloneError.

This is the layout of the array I’ve built (image below). The only thing I can see that is not a supported type that would throw that error is the

[[Prototype]]: Object

That appears in my array.

enter image description here

Everything else is a string, a boolean, a number, or undefined. I’ve changed all array elements to just strings and it still wont save, still throws the error.

Is there a way to get rid of that prototype part of the array? I’ve been Googling and haven’t found any answers.

I build the array with a .push as the user clicks checkboxes to add items they want just using a push:

this.detailArrayAllEntries.push({
  enteredDate: theDate,
  enteredTrial: theTrialNum,
  enteredElement: theElement,
  enteredLevel: theLevel,
  enteredBox: enterThisBox,
  enteredAorB: aOrBModel,
})

And every time the user selects a checkbox and the push runs, the array that is built includes that “prototype:Array”.

I’m just using a .put to save the data to the database (newEntry is the variable that has all the information I’m saving).

await theDB.theTable
     .put(newEntry)

Here is newEntry:

let newEntry = {
        clubName: this.eventClub,
        dog: {
          pk_dog:  this.enteredDogsInfo.pk_dog,
          dogBday: this.enteredDogsInfo.dogBday,
          dogBreed: this.enteredDogsInfo.dogBreed,
          dogCallName: this.enteredDogsInfo.dogCallName,
        },
        editEntry: false,
        entries: this.detailArrayAllEntries, // broken
        eventBusinessName: this.eventBusinessName,
        eventID: theEventID,
        eventName: this.eventName,
        eventSecretaryEmail: this.eventSecretaryEmail,
        eventSecretaryName: this.eventSecretaryName,
        eventStartDate: this.eventStartDate,
        eventType: this.eventType,
        person: {
          p_key: this.enteredPersonInfo.pk_person,
          f_lastName: this.enteredPersonInfo.f_lastName,
          f_firstName: this.enteredPersonInfo.f_firstName,
          f_email: this.enteredPersonInfo.f_email,
        },
        totalEntryFees: this.saveEntryFeesWithProcessing,
        }

This is driving me crazy why it won’t save, and the only thing I can really think that’s not working is that Prototype, but I don’t know how to build the array without it, or strip it out once it’s there.

I am using Quasar… so this is Javascript.

Unable to download file in laravel using jquery

When I am trying to use the download button to download file in laravel, it is not working properly and I am not able to download file. there is code.

info.blade.php

    @if ($user->is_maba)
    <x-button id="coCard" :tagA="true" class="bg-base-blue-300 hover:bg-base-blue-400 uppercase text-md whitespace-nowrap my-3"
        target="_blank" href="{{ route('home.cocard', ['id' => $user->id])}}">
        Download Co Card
    </x-button>
    @endif

coCard.blade.php

<x-home-layout menu="CoCard" title="CoCard">

    <div class="font-poppins lg:px-40 md:px-30 sm:px-16 px-3 lg:pt-32 md:pt-28 pt-24 mb-20">

        <div class="grid justify-items-center">
            <div class="text-base-blue-400 mb-5 text-center">
                <h1 class="font-extrabold xl:text-4xl lg:text-3xl md:text-2xl sm:text-xl text-xl leading-normal">
                    Menyiapkan Co Card ...
                </h1>
                <p class="text-base mt-4 italic">Harap tunggu sebentar ...</p>
                <div id="qrcode" class="hidden"></div>
            </div>
            <div class="xl:w-45 lg:w-32 md:w-24 sm:w-20 w-16 h-2 bg-base-yellow-400"></div>
        </div>
    </div>

    @push('script-bottom')
    <script src="{{ asset('js/jquery-3.6.0.slim.min.js')}}" integrity="sha256-u7e5khyithlIdTpu22PHhENmPcRdFiHRjhAuHcs05RI=" crossorigin="anonymous"></script>
    <script src="{{ asset('js/qrcode.min.js') }}"></script>
    <script type="text/javascript">
        const getQRCode = () =>{
            new QRCode(document.getElementById("qrcode"), {
                text: "{{ $username }}",
            });
        };
        getQRCode();
    </script>
    <script>
        let url;
        var generateUrlQrCode = async() => {
            let qrcode = document.getElementById("qrcode").firstElementChild;
            let blob = await new Promise(resolve=>qrcode.toBlob(resolve));
            url = URL.createObjectURL(blob);
        };

        generateUrlQrCode();
        
        const getCoCard = () => {
            const doc = new jspdf('l', 'cm', 'a4', true);
            const width = 18;
            const height = 13;

            doc.addImage(`<?= $imgDepan ?>`, "PNG", 0, 0, width, height, '','FAST');
            doc.addImage(`<?= $desainDepan ?>`, "PNG", 0, 0, width, height, '','FAST');
            doc.addImage(`${url}`, "PNG", 6.5, 4.33, 5, 5, '','FAST');
            doc.addPage('l', 'cm', 'a4', true);
            doc.addImage(`<?= $imgBelakang ?>`, "PNG", 0, 0, width, height, '','FAST');
            doc.addImage(`<?= $desainBelakang ?>`, "PNG", 0, 0, width, height, '','FAST');
            doc.save(`<?= $nimb; ?>` + "_CoCard.pdf");

            setTimeout(() => {
                window.close();
            }, 1000);
        }

        document.addEventListener("DOMContentLoaded", function(event) {
            setTimeout(getCoCard, 500);
        });
    </script>
    @endpush
</x-home-layout>

is there something missing in my code? beacuse when i click, there is no file download are coming in

Computed Style not working with overwrited css variables

I’m making a website search engine like google, and when a thing is visited I want to it turn green and change a tooltip. I use the :visited to do that, and the code changes it to purple and sets a variable --visitedLink1 to true.

The problem is, in my javascript, using getComputedStyle(document.getElementById("link1")).getPropertyValue("--visitedLink1") gives the :root value, not the updated value after visiting the website. Thus, when updating the tooltip, its “not visited” and sets the tooltip to “not visited” instead of “visited”

My code is the following:
HTML (after doing a query)

<h1>Search</h1>
<div class="text">Link 1: <a id="link1" href="https://www.scouting.org">scouting.com</a><div id="tt" class="tooltip">Not visited</div> troop.</div>

and JS

var mousePos = { x: undefined, y: undefined };
window.addEventListener('mousemove', (event) => {
    mousePos = { x: event.clientX, y: event.clientY };
    document.getElementById("tt").style.left = mousePos.x + 10;
    document.getElementById("tt").style.top = mousePos.y + 10;
    var cs = getComputedStyle(document.getElementById("link1"))
    console.log(cs.getPropertyValue('--visitedLink1'))
    if (cs.getPropertyValue('--visitedLink1') == "true") {
        document.getElementById("tt").innerHTML = "Visited"
    }
});

and CSS

:root {
    --visitBSA: false;
}
a {
    color: blue;
}
#link1:visited {
    --visitBSA: true;
    color: purple;
}
.tooltip {
    position: absolute;
    display: none;
    background-color: wheat;
    border-radius: 10px;
    padding: 20px;
    border: 3px solid black;
    left: 0;
    top: 0;
}
a:hover ~ .tooltip {
    display: block;
}

I would like to know about highly readable conditional branches in Javascript (Google Apps Script)

My name is mi2. And Thank you for taking a look.

I asked the question because I wanted to know how to do conditional branching in optimal if in Javascript (Google Apps Script).

This is the code I wrote.

And this code can actually be understood if you read it slowly, but it takes a little time to figure it all out.

const switchFunction = (
  OptionA,
  OptionB,
  OptionC
) => {
  if (
    OptionA === true &&
    OptionB === true &&
    OptionC === true
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === false &&
    OptionB === false &&
    OptionC === false
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === true &&
    OptionB === true &&
    OptionC === false
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === true &&
    OptionB === false &&
    OptionC === true
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === false &&
    OptionB === true &&
    OptionC === true
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === false &&
    OptionB === false &&
    OptionC === true
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === false &&
    OptionB === true &&
    OptionC === false
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

  if (
    OptionA === true &&
    OptionB === false &&
    OptionC === false
  ) {
    const resX = functionX(OptionA)
      
    const resY = functionY(OptionB)

    functionZ(OptionC);

    return;
  }

};

It would be great if you could tell me how to write what you think is a beautiful conditional branch.

It would be great if you could tell me how to write what you think is a beautiful conditional branch.

Event Listener – change not working after page load [duplicate]

I am trying to have a drop-down update and change the html page by hiding or revealing another drop-down (Or even disable it) (In this case, the “provider-selection”.)

However, the event listener is not triggering properly (It triggers on-load, but not dynamically if I change the report-selection select element.

I have tried various if conditions. Nothing triggers. If I put a console.log before the if statement, it will show the console log, but nothing else after that (Such as the logs from within the if conditions.

I have confirmed through other tests that the js file loads properly at the end of the file (I left out some other functions that take effect on page load. They are simpler such as changing text)

Looking for someone to point me in the right direction to learn and figure out what I am doing wrong. I would like to keep the functions for hide_element / unhide_element if possible for code re-usability, but if that’s not possible, I would like to know what is the best practice for this type of scenario.

HTML

<section>
    <nav>
        <select id="report-selection">
            <option id="report-types" value="null">Pick One</option>
            <option id="report-types" value="AR">Accounts Receivable</option>
            <option id="report-types" value="Production">Daily Production</option>
        </select>
        
        <br>
        <select id="office-selection">
            <option id="office-1" value="office-1">Test-Office 1</option>
            <option id="office-2" value="office-2">Test-Office 2</option>
        </select>
        <br>
        <select id="provider-selection">
            <option id="provider-1" value="provider-1">Test-Provider 1</option>
            <option id="provider-2" value="provider-2">Test-Provider 2</option>
        </select>
        </br>
</section>
<script src="test.js"></script>

Javascript

/**********  Report Selection Hide / Show Elements  ***************/
const report_type_selector = document.getElementById('report-types');
const provider = document.getElementById('provider-selection');

report_type_selector.addEventListener("change", provider_field_change);

function provider_field_change(){
    if (report_type_selector.value == 'AR') {      
        hide_element(provider);
        console.log("AR event triggered");
    } 
    if (report_type_selector.value == 'Production') {
        unhide_element(provider);
        console.log("Production event triggered");
    }
}

function hide_element(id) {
    id.style.display = 'none';
}

function unhide_element(id) {
    id.style.display = 'block';
}
/******************************************************************/

Edit:
The automated system stated this was a duplicate of this: addEventListener calls the function without me even asking it to

Edit 2:
Thanks to Nick, he was able to point out where I was wrong.

Please close this, as it is resolved.

C# Blazor file upload with progress indicator

Although I solved this problem using Javascript (xmlhttprequest) but I wanted to do it in a more C#pish way. I tried this article on CSharp corner but could not make it work:
link

  1. I came to know that Blazor(HttpClient) is using fetch which does not support progress event
  2. I tried vanila javscript with xmlhttp request and it works the way i wanted
  3. I found several problems in the above link
  4. First issue was that it throws error because of improper use of using keyword
  5. After fixing the above, Then I could not get the data posted from browser as it was either corrupt/empty/or no proper content-type was set in the controller
  6. I tried several content type and checked on backend controller side but no data could not be fetched. This was always false
Request.HasFormContentType
  1. I am using C# Blazor web assembly

Element looks through another element html

I want to make a webpage where there is a black screen over it, and a circle that follows the cursor, and some content behind the black screen. I want to be able to make the content visible but only when it is inside the circle, and only the parts that are inside the circle

I tried to use a element magnifier and then make a black screen over all of it but that didn’t work

Animate along curved/bezier path edge, or self-referential edge, in Cytoscape?

Consider the following test.html (based on https://cytoscape.org/cytoscape.js-cola/demo-compound.html – except I’ve used bezier lines for the edges)

<!DOCTYPE html>
<html>

<head>
  <title>cytoscape-cola.js demo (compound)</title>

  <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1, maximum-scale=1">

  <script src="https://unpkg.com/cytoscape/dist/cytoscape.min.js"></script>

  <!-- for testing with local version of cytoscape.js -->
  <!--<script src="../cytoscape.js/build/cytoscape.js"></script>-->

  <script src="https://unpkg.com/webcola/WebCola/cola.min.js"></script>
  <script src="https://cytoscape.org/cytoscape.js-cola/cytoscape-cola.js"></script>

  <style>
    body {
      font-family: helvetica;
      font-size: 14px;
    }

    #cy {
      position: relative;
      left: 0;
      top: 0;
      width: 100%;
      height: 300px;
      z-index: 999;
    }

    h1 {
      opacity: 0.5;
      font-size: 1em;
    }
  </style>

  <script>
    document.addEventListener('DOMContentLoaded', function () {

      var cy = window.cy = cytoscape({
        container: document.getElementById('cy'),

        layout: {
          name: 'cola'
        },

        style: [
          {
            selector: 'node',
            css: {
              'background-color': '#f92411',
              'content': 'data(id)',
            }
          },

          {
            selector: 'node:parent',
            css: {
              'background-opacity': 0.333
            }
          },

          {
            selector: 'edge',
            css: {
              'line-color': '#f92411',
              'curve-style': 'unbundled-bezier',
              'control-point-weights': '0.25 0.75',
              'target-arrow-shape': 'triangle',
              'target-arrow-color': '#f92411',
              'arrow-scale': 2.0,
            }
          }
        ],

        elements: [{ group: 'nodes', data: { id: 'n0' } },
        { group: 'nodes', data: { id: 'n1' } },
        { group: 'nodes', data: { id: 'n2' } },
        { group: 'nodes', data: { id: 'n3' } },
        { group: 'nodes', data: { id: 'n4', parent: 'n37' } },
        { group: 'nodes', data: { id: 'n5' } },
        { group: 'nodes', data: { id: 'n6' } },
        { group: 'nodes', data: { id: 'n7', parent: 'n37' } },
        { group: 'nodes', data: { id: 'n8', parent: 'n37' } },
        { group: 'nodes', data: { id: 'n9', parent: 'n37' } },
        { group: 'nodes', data: { id: 'n10', parent: 'n38' } },
        { group: 'nodes', data: { id: 'n11', parent: 'n38' } },
        { group: 'nodes', data: { id: 'n12' } },
        { group: 'nodes', data: { id: 'n13' } },
        { group: 'nodes', data: { id: 'n14' } },
        { group: 'nodes', data: { id: 'n15' } },
        { group: 'nodes', data: { id: 'n16' } },
        { group: 'nodes', data: { id: 'n17' } },
        { group: 'nodes', data: { id: 'n18' } },
        { group: 'nodes', data: { id: 'n19' } },
        { group: 'nodes', data: { id: 'n20' } },
        { group: 'nodes', data: { id: 'n21' } },
        { group: 'nodes', data: { id: 'n22' } },
        { group: 'nodes', data: { id: 'n23' } },
        { group: 'nodes', data: { id: 'n24', parent: 'n39' } },
        { group: 'nodes', data: { id: 'n25', parent: 'n39' } },
        { group: 'nodes', data: { id: 'n26', parent: 'n42' } },
        { group: 'nodes', data: { id: 'n27', parent: 'n42' } },
        { group: 'nodes', data: { id: 'n28', parent: 'n42' } },
        { group: 'nodes', data: { id: 'n29', parent: 'n40' } },
        { group: 'nodes', data: { id: 'n30', parent: 'n40' } },
        { group: 'nodes', data: { id: 'n31', parent: 'n41' } },
        { group: 'nodes', data: { id: 'n32', parent: 'n41' } },
        { group: 'nodes', data: { id: 'n33', parent: 'n41' } },
        { group: 'nodes', data: { id: 'n34', parent: 'n41' } },
        { group: 'nodes', data: { id: 'n35', parent: 'n41' } },
        { group: 'nodes', data: { id: 'n36', parent: 'n41' } },
        { group: 'nodes', data: { id: 'n37' } },
        { group: 'nodes', data: { id: 'n38' } },
        { group: 'nodes', data: { id: 'n39', parent: 'n43' } },
        { group: 'nodes', data: { id: 'n40', parent: 'n42' } },
        { group: 'nodes', data: { id: 'n41', parent: 'n42' } },
        { group: 'nodes', data: { id: 'n42', parent: 'n43' } },
        { group: 'nodes', data: { id: 'n43' } },
        { group: 'nodes', data: { id: 'n44', parent: 'n38' } },
        { group: 'nodes', data: { id: 'n45', parent: 'n38' } },
        { group: 'nodes', data: { id: 'n46', parent: 'n38' } },
        { group: 'edges', data: { id: 'e0', source: 'n0', target: 'n1' } },
        { group: 'edges', data: { id: 'e1', source: 'n1', target: 'n2' } },
        { group: 'edges', data: { id: 'e2', source: 'n2', target: 'n3' } },
        { group: 'edges', data: { id: 'e3', source: 'n0', target: 'n3' } },
        { group: 'edges', data: { id: 'e4', source: 'n1', target: 'n4' } },
        { group: 'edges', data: { id: 'e5', source: 'n2', target: 'n4' } },
        { group: 'edges', data: { id: 'e6', source: 'n4', target: 'n5' } },
        { group: 'edges', data: { id: 'e7', source: 'n5', target: 'n6' } },
        { group: 'edges', data: { id: 'e8', source: 'n4', target: 'n6' } },
        { group: 'edges', data: { id: 'e9', source: 'n4', target: 'n7' } },
        { group: 'edges', data: { id: 'e10', source: 'n7', target: 'n8' } },
        { group: 'edges', data: { id: 'e11', source: 'n8', target: 'n9' } },
        { group: 'edges', data: { id: 'e12', source: 'n7', target: 'n9' } },
        { group: 'edges', data: { id: 'e13', source: 'n13', target: 'n14' } },
        { group: 'edges', data: { id: 'e14', source: 'n12', target: 'n14' } },
        { group: 'edges', data: { id: 'e15', source: 'n14', target: 'n15' } },
        { group: 'edges', data: { id: 'e16', source: 'n14', target: 'n16' } },
        { group: 'edges', data: { id: 'e17', source: 'n15', target: 'n17' } },
        { group: 'edges', data: { id: 'e18', source: 'n17', target: 'n18' } },
        { group: 'edges', data: { id: 'e19', source: 'n18', target: 'n19' } },
        { group: 'edges', data: { id: 'e20', source: 'n17', target: 'n20' } },
        { group: 'edges', data: { id: 'e21', source: 'n19', target: 'n20' } },
        { group: 'edges', data: { id: 'e22', source: 'n16', target: 'n20' } },
        { group: 'edges', data: { id: 'e23', source: 'n20', target: 'n21' } },
        { group: 'edges', data: { id: 'e24', source: 'n22', target: 'n24' } },
        { group: 'edges', data: { id: 'e25', source: 'n23', target: 'n24' } },
        { group: 'edges', data: { id: 'e26', source: 'n24', target: 'n25' } },
        { group: 'edges', data: { id: 'e27', source: 'n26', target: 'n38' } },
        { group: 'edges', data: { id: 'e28', source: 'n26', target: 'n37' } },
        { group: 'edges', data: { id: 'e29', source: 'n26', target: 'n39' } },
        { group: 'edges', data: { id: 'e30', source: 'n26', target: 'n27' } },
        { group: 'edges', data: { id: 'e31', source: 'n26', target: 'n28' } },
        { group: 'edges', data: { id: 'e32', source: 'n26', target: 'n40' } },
        { group: 'edges', data: { id: 'e33', source: 'n21', target: 'n31' } },
        { group: 'edges', data: { id: 'e34', source: 'n21', target: 'n32' } },
        { group: 'edges', data: { id: 'e35', source: 'n31', target: 'n33' } },
        { group: 'edges', data: { id: 'e36', source: 'n31', target: 'n34' } },
        { group: 'edges', data: { id: 'e37', source: 'n33', target: 'n34' } },
        { group: 'edges', data: { id: 'e38', source: 'n32', target: 'n35' } },
        { group: 'edges', data: { id: 'e39', source: 'n32', target: 'n36' } },
        { group: 'edges', data: { id: 'e40', source: 'n16', target: 'n40' } },
        { group: 'edges', data: { id: 'e41', source: 'n46', target: 'n46' } },
        ]
      });

      document.getElementById('btn-zoom-along-line').onclick = function() {
        //let first_node = cy.nodes('[id = "n16"]')[0];
        let edge_to_zoom_along = cy.edges('[id = "e30"]')[0];
        let first_node = edge_to_zoom_along.source();
        let second_node = edge_to_zoom_along.target();
        cy.fit(first_node, 30);
        cy.animate({ // https://stackoverflow.com/q/70678336
          fit: {
            eles: second_node, padding: 20 },
          },
          {
            duration: 1000
          }
        );

      }
    }); // end DOMContentLoaded
  </script>
</head>

<body>
  <h1>cytoscape-cola demo (compound)</h1>
  <button type="button" id="btn-zoom-along-line">Do zoom along line</button>
  <div id="cy"></div>

</body>

</html>

If you run this snippet, wait for the placement to “settle” and then click on “Do zoom along line”. Here I’ve chosen edge { id: 'e30', source: 'n26', target: 'n27' } to serve as the “line” to go along to – so when clicking “Do zoom along line”, it will first zoom with cy.fit on the source (here n26), and then try to animate to cy.fit the target (to n27) – which ultimately has the effect, as if the camera is panning in straight line from n26 to n27. However, the edge connecting these is Bezier – curved. So, my first question is:

  1. How can I animate the “camera” panning, from focusing on one node to focusing to another, while following along the curved edge that connects these edges?

Note also, I have a self-referential edge: { id: 'e41', source: 'n46', target: 'n46' } – and it did get rendered:

self-referential edge

… however it starts from north, and then bends westward, and so it overlaps with node n45. So:

  1. Is there a way to specify in cytoscape, that a self-referential edge should start at a specific position (e.g. node “north”), and then bend in a specific way (say by specifying end anchor being the same node “east”)?

And talking of self-referential edges, the above code which animates between cy.fit of one source node and cy.fit of another target node will never work, since source and target node will be the same. So:

  1. How can I animate camera panning along a self-referential curved/Bezier edge in Cytoscape?

Javascript how to include external page content into a confirmation form

Sorry for possibly basic question as I’m not very familiar with JS syntacsys.

I need to use a Javascript confirmation form with a dynamic text line taken from another page on the same server. The code I’m trying to use as below:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>


<script>

function ConfirmDialog(message) {
var text = "Test"

$.get( "confirmaddress.html", function( data ) {
    // the contents is now in the variable data
    text=data;
});


  $('<div></div>').appendTo('body')
    .html('<div><h6>' + message + '?</h6></div>')
    //.load('confirmaddress.html');
    .append(text)
    .dialog({
      modal: true,
      title: 'Address',
      zIndex: 10000,
      autoOpen: true,
      width: 'auto',
      resizable: false,
      buttons: {
        Yes: function() {
          // $(obj).removeAttr('onclick');                                
          // $(obj).parents('.Parent').remove();

          $('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');

          $(this).dialog("close");
        },
        No: function() {
          $('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');

          $(this).dialog("close");
        }
      },
      close: function(event, ui) {
        $(this).remove();
      }
    });
};
</script>

However, the variable ‘text’ always stays static and doesn’t update its value from addressconfirm.html page. I know it shall be a very simple fix and I appreciate if the community point my mistake.

Creat cusotom marker from svg text

I have a vuejs google maps component that shows products array whith latlng data on map as combined markers from svg text(shape) and product price
How can i do this thing ?

I tried blob and canvas function but it dose not work

Sidebar Menu not functioning as planned using setActiveChildItem for Next Js project

I am trying to use the setActiveChildItem function to keep a child menu open when the user clicks on a child item in a sidebar menu. However, the child menu is closing when I click on a child item.

Here is the code that I am using:

const handleMenuItemClick = (name, href) => {
if (href) {
setCurrentMenuItem(href);
setActiveChildItem(name);
} else if (name === currentMenuItem) {
setActiveChildItem(activeChildItem === name ? '' : name);
} else {
setCurrentMenuItem(name);
setActiveChildItem(name);
}
};

I have tried adding a console.log statement to the handleMenuItemClick function to track what is happening, but the console is not logging anything.

I am not sure what is wrong with my code. Can anyone help me?

Here is the full code for the SidebarMenu component:

import { Disclosure } from '@headlessui/react';
import { ChevronRightIcon } from '@heroicons/react/20/solid';
import { useState, useEffect } from 'react';

const navigation = [
 {
   name: 'Racing',
   children: [
     { name: 'Horse Racing', href: '/racing/horses' },
     { name: 'Greyhound Racing', href: '/racing/greyhounds' },
     { name: 'Harness Racing', href: '/racing/harness' },
   ],
 },
 {
   name: 'Aussie Rules',
   children: [
     { name: 'AFL', href: '/aussie-rules/afl' },
   ],
 },
 {
   name: 'Basketball',
   children: [
     { name: 'NBA', href: '/basketball/nba' },
     { name: 'NBL', href: '/basketball/nbl' },
     { name: 'NCAAB', href: '/basketball/ncaab' },
   ],
 },
 {
   name: 'Baseball',
   children: [
     { name: 'MLB', href: '/baseball/mlb' },
   ],
 },
 {
   name: 'Rugby League',
   children: [
     { name: 'NRL', href: '/rugby-league/nrl' },
   ],
 },
 {
   name: 'US Football',
   children: [
     { name: 'NFL', href: '/us-football/nfl' },
     { name: 'NCAAF', href: '/us-football/ncaaf' },
   ],
 },
 {
   name: 'Soccer',
   children: [
     { name: 'A-League', href: '/soccer/a-league' },
     { name: 'Bundesliga', href: '/soccer/bundesliga' },
     { name: 'Premier League', href: '/soccer/epl' },
     { name: 'Serie A', href: '/soccer/serie-a' },
     { name: 'La Liga', href: '/soccer/la-liga' },
     { name: 'Ligue 1', href: '/soccer/ligue-1' },
     { name: 'Champions League', href: '/soccer/champions-league' },
     { name: 'Europa League', href: '/soccer/europa-league' },
   ],
 },
 {
   name: 'Ice Hockey',
   children: [
     { name: 'NHL', href: '/ice-hockey/nhl' },
   ],
 },
 // Other navigation items...
];

function classNames(...classes) {
 return classes.filter(Boolean).join(' ');
}

export default function SidebarSportsMenu({ currentMenuItem, setCurrentMenuItem }) {
 const [activeChildItem, setActiveChildItem] = useState('');

 useEffect(() => {
   const parentMenuItem = navigation.find((item) =>
     item.children.some((child) => child.href === currentMenuItem)
   );

   if (parentMenuItem) {
     setActiveChildItem(parentMenuItem.name);
   } else {
     const childMenuItem = navigation.find((item) =>
       item.children.some((child) => child.href === currentMenuItem)
     );

     if (childMenuItem) {
       setActiveChildItem(childMenuItem.name);
     }
   }
 }, [currentMenuItem]);

 const handleMenuItemClick = (name, href) => {
   if (href) {
     setCurrentMenuItem(href);
     setActiveChildItem(name);
   } else if (name === currentMenuItem) {
     setActiveChildItem(activeChildItem === name ? '' : name);
   } else {
     setCurrentMenuItem(name);
     setActiveChildItem(name);
   }
 };

 return (
   <div className="flex flex-col h-full">
     <div className="border-b border-gray-200 bg-blue px-4 py-2 sm:px-0">
       <h4 className="text-base font-semibold leading-2 text-white">Coverage</h4>
     </div>
     <nav className="flex flex-1 flex-col mt-5">
       <ul role="list" className="flex flex-1 flex-col gap-y-7">
         <li>
           <ul role="list" className="-mx-2 space-y-1">
             {navigation.map((item) => (
               <li key={item.name}>
                 {!item.children ? (
                   <a
                     href={item.href}
                     className={classNames(
                       'group flex gap-x-3 rounded-md p-2 text-base leading-6 font-bold',
                       {
                         'bg-[#47566d] text-gray-800': currentMenuItem === item.href,
                         'bg-[#47566d] text-white hover:bg-[#a3aab6] hover:text-[#1a2c49]': currentMenuItem !== item.href,
                       }
                     )}
                     onClick={() => handleMenuItemClick(item.name, item.href)}
                   >
                     {item.name}
                   </a>
                 ) : (
                   <Disclosure as="div" defaultOpen={activeChildItem === item.name}>
                     {({ open }) => (
                       <>
                         <Disclosure.Button
                           className={classNames(
                             activeChildItem === item.name
                               ? 'bg-[#30415b] text-zinc-100'
                               : 'bg-[#1a2c49] text-white hover:bg-[#47566d] hover:text-zinc-100',
                             'flex items-center w-full text-left square-md p-2 gap-x-3 text-base leading-6 font-semibold'
                           )}
                           onClick={() => handleMenuItemClick(item.name, null)}
                         >
                           {item.name}
                           <ChevronRightIcon
                             className={classNames(
                               'ml-auto h-5 w-5',
                               { 'text-[#1a2c49]': open, 'text-gray-400': !open }
                             )}
                             aria-hidden="true"
                           />
                         </Disclosure.Button>
                         {open && (
                           <Disclosure.Panel as="ul" className="mt-1 px-0">
                             {item.children.map((subItem) => (
                               <li key={subItem.name}>
                                 <a
                                   href={subItem.href}
                                   className={classNames(
                                     currentMenuItem === subItem.href
                                       ? 'bg-[#a3aab6] text-zinc-800'
                                       : 'bg-[#47566d] text-zinc-100 hover:bg-[#a3aab6] hover:text-zinc-800',
                                     'flex items-center block square-md py-2 pr-2 pl-3 text-sm leading-6 font-semibold'
                                   )}
                                   onClick={() => handleMenuItemClick(subItem.name, subItem.href)}
                                 >
                                   {subItem.name}
                                 </a>
                               </li>
                             ))}
                           </Disclosure.Panel>
                         )}
                       </>
                     )}
                   </Disclosure>
                 )}
               </li>
             ))}
           </ul>
         </li>
       </ul>
     </nav>
   </div>
 );
}

here is the code for the index.js where the sidebar menu is imported.

import '../../../app/globals.css';
import { Fragment, useState } from 'react'
import SidebarSportsMenu from '../../../components/layout/SidebarSportsMenu';
import HorsesEventsCurrentTable from '../../../components/events/racing/HorsesCurrentEventsTable';
import ResponsibleGambling from '../../../components/layout/ResponsibleGambling'
import PageHeader from '@/components/layout/PageHeader';
import HorsesPreviewTemplate from './event';
import CountrySelect from '../../../components/layout/CountrySelect'
import Footer from '@/components/layout/Footer';
import HorsesHome from './HorsesHome';

export default function HorsesHomepage() {
 const [currentMenuItem, setCurrentMenuItem] = useState('Horse Racing');
 const [selectedEventId, setSelectedEventId] = useState(null);

 const handleMenuItemClick = (name) => {
   setCurrentMenuItem(name);
   setSelectedEventId(null);
 };

 const handleEventSelection = (eventId) => {
   setSelectedEventId(eventId);
 };


 return (
   <>
     <div className="flex flex-col">
       <div className="flex min-h-full flex-col">
         <PageHeader />
         <header className="shrink-0 border-b pt-0 pb-3 border-neutral bg-[#14233a]">
         <div className="mx-auto flex h-16 max-w-7xl justify-end px-4 sm:px-6 lg:px-8">
         <CountrySelect />
       </div>

         </header>
         <div className="mx-auto w-full max-w-7xl mt-2.5">
           <ResponsibleGambling />
         </div>
         <div className="mx-auto flex w-full max-w-7xl items-start gap-x-2 px-4 py-5 sm:px-6 lg:px-8">
           <aside className="top-8 hidden w-48 shrink-0 lg:block bg-[#1a2c49] h-screen px-4 py-1">
             {/* SIDEBAR MENU - LEFT */}
             <SidebarSportsMenu currentMenuItem={currentMenuItem} setCurrentMenuItem={handleMenuItemClick} />
           </aside>
           <main className="sticky top-8 w-full lg:w-96 shrink-0 bg-white overflow-y-auto h-screen hide-scrollbar">
             {/* EVENT LIST DETAILS HERE */}
             <div className="mt-0">
               <HorsesEventsCurrentTable handleEventSelection={handleEventSelection} selectedEventId={selectedEventId} />
             </div>
           </main>
           <aside className="flex-1 w-[calc(100%-5rem)] lg:w-[calc(100%-18rem)] bg-white overflow-y-auto hide-scrollbar h-screen p-0">
             {/* EVENT PREVIEWS HERE */}
             {selectedEventId ? (
               <HorsesPreviewTemplate eventUrl={`/racing/horses/event/${selectedEventId}`} />
             ) : (
               <HorsesHome />
             )}
           </aside>
         </div>
         <div className="mx-auto w-full max-w-7xl mb-3.5">
           <ResponsibleGambling />
         </div>
         
       </div>
       <Footer />
     </div>
   </>
 );
}


Empty response when trying to send email using nodemailer package with an express server

I can’t understand what could be causing the following error in browser:
net::ERR_EMPTY_RESPONSE

TypeError: Failed to fetch

I”ll provide a link to the github repo: NodemailerUser Repository

The fetch api and XMLHttpRequest execution in app.js was working fine. I was hitting the post route, /contact, and sending the information to the express server. However, after adding the sendMail fxn in the server.js file, the fetch request and XML request would show as “pending” in the browser Network tab on the developer tools window. I’m not sure what the difference is.

I have used the same setup before, but the data sent from frontend to server was a simple string and not an object. I don’t think sending an object should make a difference, but maybe I did something wrong.

I’ve also done my due diligence to create app password for the gmail accounts I’m using to authorize this application.

Code:

//Frontend JS File:
console.log("connected");
const baseUrl = "http://localhost:3000/"
const form = document.querySelector("form");
const nameUser = document.getElementById("name-field");
const email = document.querySelector("#user-email");
const subject = document.querySelector("#subject-email");
const message = document.querySelector("#message-email");
const button = document.getElementById("send");


form.addEventListener("submit", (e)=>{
    e.preventDefault();
    const emailData = {
        nameUser: nameUser.value,
        email: email.value,
        subject: subject.value,
        message: message.value
    
    }
    // sendDataXhrPromise(baseUrl, emailData)
    // .then(console.log("data sent"))
    // .catch(err=>{console.log(err)})

    sendDataAjax(baseUrl, emailData)
});

async function sendDataXhrPromise(url, obj){
    console.log(obj.subject, " submitted :)");
    return new Promise((resolve, reject)=>{
        const xhr = new XMLHttpRequest();
        xhr.open("POST", url + "contact", true);
        xhr.setRequestHeader('content-type', 'application/json');
        xhr.onload = function(){
            console.log("Response Text: ",xhr.responseText, typeof(xhr.responseText), xhr.status, xhr.readyState);
            if(xhr.readyState === 4 && xhr.status === 200){                
                alert('Email sent');
                resolve(`resolve ${xhr.response}`);                

            }else{
                alert("Alert: Error");
                reject(`reject: ${xhr.statusText}`);
            }            
        }
        xhr.send( JSON.stringify(obj));
    });        
}

function sendDataAjax(url, obj){
    console.log(obj.subject, " submitted :)");
    if(!obj.message){return};
    fetch("http://localhost:3000/contact",{
        method: "POST",
        headers: {
            "Content-Type": "application/json",
        },
        body: JSON.stringify(obj)
    })
        .then(res=>console.log(res))
        .catch(err=>console.log(err));
}

function sendDataXhr(){
    console.log(input.value, " submitted :)");
        const xhr = new XMLHttpRequest();
        xhr.open("POST", baseUrl + "contact", true);
        xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        xhr.onload = function(){
            console.log("Status, Response: ", xhr.status, xhr.responseText, xhr.readyState);
            if(xhr.readyState === 4 && xhr.status === 200){
                alert('Email sent');

            }else{
                alert("Alert: Error");
            }            
        }
        xhr.send(JSON.stringify(data));
}

//NodemailerController.js File:

    //////////////////////
// Import Dependencies
//////////////////////
require("dotenv").config();
const express = require("express");
const nodemailer = require("nodemailer");
const path = require("path");

const EMAIL = process.env.EMAIL;
const EMAIL2 = process.env.EMAIL2;
const PASS = process.env.PASS;
const PASS3 = process.env.PASS3;

/////////////////
// Create Router Object
////////////////
const router = express.Router();

//////////
// Routes
//////////

//root:
router.get("/", (req, res)=>{
    const options = {
        root: path.join(__dirname, "../views"),
        dotfiles: "deny",
        headers: {
            "x-timestamp": Date.now(),
            "x-sent": true
        }
    }
    const fileName = "index.html";

    res.sendFile(fileName, options, (err)=>{
        if(err){
            console.log(err);
        } else{
            console.log("Sent ", fileName);
        }
    })
});

//contact
router.get("/contact", (req, res)=>{
    const options = {
        root: path.join(__dirname, "../views"),
        dotfiles: "deny",
        headers: {
            'x-timestamp': Date.now(),
            'x-sent': true
        }
    }
    const fileName = "contact.html";

    res.sendFile(fileName, options, (err)=>{
        if(err){
            console.log(err);
        }else{
            console.log("Sent ", fileName);
        }
    })
});

router.post("/contact", (req, res)=>{ 
    console.log("req.body: ", req.body)
    const contents = req.body
    if(!contents){
        return res.status(400).send({status: "failed"});
    }  
    sendEmail(contents)
});


//////////////////
// Nodemailer fxns
//////////////////
function sendEmail(obj){
        const transporter = nodemailer.createTransport({
            host: "gmail",
            auth: {
                user: "[email protected]",
                pass: PASS3
            }
        });
        const info = {
            from: "[email protected]", // sender address
            to: "[email protected]", // list of receivers
            subject: `Message from ${obj.nameUser} <${obj.email}>: ${obj.subject}`,
            text: obj.message

        };
        transporter.sendMail(info,(err, emailInfo)=>{
            if(err){
                console.log("Error: ", err);
               res.send('error');
            }else{
                console.log('Email sent ' + emailInfo.response);
                res.send('success');
            }
            
        });    
}
module.exports = router;

//server.js File:

///////////////////////
// Import Dependecies
//////////////////////
require("dotenv").config();
const express = require("express");
const NodemailerRouter = require("./controllers/NodemailerController.js");
const methodOverride = require("method-override");
const morgan = require("morgan");
const cors = require("cors");


//////////////////////
// Server Application
//////////////////////
const app = express();
const PORT = process.env.PORT;

/////////////
//Middleware
/////////////
app.use(morgan("dev")); //log requests to server
app.use(cors());
app.use(methodOverride("__method")); //overide request methods for form submissions
app.use(express.urlencoded({extended: true})) //parse html form bodies into req.body
app.use(express.json()); //needed to receive data in JSON format from frontend client
app.use("/static", express.static("static")); //serve files via express static route
app.use(NodemailerRouter);

//////////////
// app listener
//////////////
app.listen(PORT, ()=> console.log(`Email servicing on PORT ${PORT}`));

DOM Range.cloneRange to test Range.surroundContents for errors

I am trying to clone a range using the Range.cloneRange method without actually updating the DOM. I want to test if the Range.surroundContents method will throw an error before allowing the user to edit the DOM using the Range.surroundContents method.

try {
   const clone = this.EditorRange.cloneRange();
   console.log(clone);
   const element = document.createElement('span');
   clone.surroundContents(element);
   this.ShowText();
} catch (error) {
   console.log(error);
   alert('Invalid surround contents');
   return;
}

The code above actually changes the DOM even though I am creating a clone of the initial range.

My filter with ion-searchbar is not working

Initial part of my application consists of loading data from the database and displaying it using mat-accordion, as below:

async getVouchers() {
this._HttpService.get(${ServerUrl.ApiUrl}voucher).then(data => {
this.result = data;

  if (this.result.vouchers.length > 0) {
    this.hasVoucher = true;
    this.dataSource = this.result.vouchers;
  }
  else {
    this.hasVoucher = false;
  }

  this.skeleton = true;
})
}

  <div class="ion-margin-top ion-margin-bottom" *ngFor="let data of dataSource">
      <mat-accordion>
        <mat-expansion-panel>
          <mat-expansion-panel-header>
            <mat-panel-title>
              {{ data.name }}
            </mat-panel-title>
          </mat-expansion-panel-header>

          <p>{{'voucher.messageTable' | transloco}} {{data.message}}</p>
          
          ....
          </mat-expansion-panel>
      </mat-accordion>
    </div>

I am working to create a filter but not working.

<ion-searchbar show-clear-button=“always” placeholder=“Search” (keyup)=“filterVoucher($event)”>

filterVoucher(event: Event) {
const filterValue = (event.target as HTMLInputElement).value;
this.dataSource.filter = filterValue.trim().toLowerCase();
}

Anyone can give some help to finish this filter??

Defined an ion-searchbar and created basic filter with Angular / javascript but it is not working.

Why the sessionStorage stills existing after remove it

I have a click event associated with a button that calls the resetForm() function. This function clears the values of the inputs and clears the fields_entity session that stored the values in real time. When checking the log inside the resetForm function, it is observed that the session is null. However, when changing the option in the select element, the previously filled and cleared values are reinserted into the inputs that were cleared. The second session check within the roleOption() function, which is called on the change event associated with #role, shows the fields_entity session with the last inserted values as if the session still exists. It is worth noting that all of this was done without reloading the page. My question is to understand why this behavior occurs. I managed to solve it in some ways, but I would really like to understand why the fields_entity still exists. I’m not sure if there’s something I might be missing in the autosave function.


<!DOCTYPE html>
<html lang="en">

<head>
    <title>Document</title>
</head>

<body>
    <form class="form user">
        <h2>Cadastrar <span></span></h2>

        <label for="role">Choose your role</label>
        <select id="role" name="role">
            <option value="teacher" name="teacher">Teacher</option>
            <option value="student" name="student">Student</option>
            <option value="adm" name="adm">Collaborator</option>
        </select>

        <label for="name">Full name</label>
        <input type="text" id="name" name="name">

        <label for="cpf">CPF</label>
        <input type="text" id="cpf" name="cpf">

        <label for="email">Email</label>
        <input type="email" id="email" name="email" novalidate>

        <label for="password">Password</label>
        <input type="password" id="password" name="password">
        <div class="strength-pwd"></div>

        <button type="submit">Register</button>
        <button type="button" onclick="resetForm();"> Clear formulary</button>
    </form>
    <script>
        function autosave(form, id) {
            let fields = sessionStorage.getItem(`fields_${id}`);

            fields ? (fields = JSON.parse(fields)) : (fields = {});


            Array.from(form.elements).forEach(input => {
                if (input.tagName === "INPUT" || input.tagName === "SELECT") {
                    console.log("valor => ", input.value)
                    input.addEventListener("input", () => {
                        fields[input.name] = input.value;
                        sessionStorage.setItem(`fields_${id}`, JSON.stringify(fields));
                    });
                }
            });

            Object.keys(fields).forEach(key => {
                const input = document.querySelector(`input[name="${key}"], select[name="${key}"]`);

                if (input) {
                    input.value = fields[key];
                }
            });

        }
        const form = document.querySelector(".form.user");
        const title = document.querySelector("h2");
        const role = document.querySelector("#role");
        const name = document.querySelector("#name");
        const password = document.querySelector("#password");
        const email = document.querySelector("#email");
        const cpf = document.querySelector("#cpf");
        let _entities = [];

        function roleOptions() {
            console.log(sessionStorage.getItem("fields_entity")) //Second check = {name : ..., email...};
            autosave(form, "entity");
            let roleValue = role.value;
            //Part of code removed
        };
        role.addEventListener("change", roleOptions);

        function resetForm() {

            form.querySelectorAll("input").forEach(e => { e.value = ""; });
            sessionStorage.removeItem("fields_entity");
            console.log(sessionStorage.getItem("fields_entity")) //First check = null

        }

        form.addEventListener("submit", e => {
            sessionStorage.clear();
            e.preventDefault();
        });
        roleOptions();
    </script>
</body>

</html>

I’m not interested in finding the solution to this problem in this case, but rather in understanding its behavior. Everything I’ve tried to identify it was using console.log to observe the presence of values, but I didn’t come to any conclusion.