Turning JSON file into HTML radio quiz

I need to fetch JSON file, sort it’s Question,Possible aswers and then display correct answer but I cant fetch and sort it properly

    <script>
            fetch("quiz.json").then(function (response) {

                response.json()

            }).then(function(quiz){
                for(let i = 0; 1 <quiz.length; i++){
                    document.body.innerHTML += '<h2>' +quiz[i].question + '</h2>';
                    document.body.innerHTML += '<imput type="radio">' +quiz[i].options ;
                    document.body.innerHTML += '<p>' +quiz[i].answer + '</p>';
                }
            })
    </script>

When I try it it says “

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'length')
    at (index):30:40
```"

JSON file : 

{
“quiz”: {
“q1”: {
“question”: “Which one is correct team name in NBA?”,
“options”: [
“New York Bulls”,
“Los Angeles Kings”,
“Golden State Warriros”,
“Huston Rocket”
],
“answer”: “Huston Rocket”
},
“q2”: {
“question”: “‘Namaste’ is a traditional greeting in which Asian language?”,
“options”: [
“Hindi”,
“Mandarin”,
“Nepalese”,
“Thai”
],
“answer”: “Hindi”
},
“q3”: {
“question”: “The Spree river flows through which major European capital city?”,
“options”: [
“Berlin”,
“Paris”,
“Rome”,
“London”
],
“answer”: “Berlin”
},
“q4”: {
“question”: “Which famous artist had both a ‘Rose Period’ and a ‘Blue Period’?”,
“options”: [
“Pablo Picasso”,
“Vincent van Gogh”,
“Salvador Dalí”,
“Edgar Degas”
],
“answer”: “Pablo Picasso”
}
}
}


Also Im using XAMPP and only vanilla js

I want open videos, audios, or images from ZIP js

I have searched in other forums and can’t find any good results.

I tried to load the path of the ZIP file in js, but it doesn’t work for me.

here the code:

function open_file_from_ZIP(path, zip_path, type){

   var zip_path = path+'://'+zip_path;
   var loader = new ZipLoader(path);

   switch (type) {
    case "folder" : 
        $("#folder-manager-table tr").remove(); 
        break;
    case "image" : 
        window.top. open_responsive(); 
        window.top. $("#image-viewer-panel").attr("src", loader.load(zip_path) ); 
        break;
    case "audio" : 
        window.top. $('#audio-player-tag').attr('src', loader.load(zip_path)); 
        window.top. document.getElementById("audio-player-tag").play(); 
        break;
    case "video" : 
        window.top. open_video(); 
        window.top. $('#popup-video-viewer').attr('src', loader.load(zip_path)); 
        window.top. document.getElementById("popup-video-viewer").play(); 
        break;
    }
}

Polygon Generator

I’m trying to generate a polygon with circles inside (JS canvas). Here’s a sample expected output:enter image description here

It’s basically a 4-sided polygon (square) with circles next to the vertices. Here is what I tried:

However, I don’t get the expected outcome.
Note: I want this to work for any sized polygon and not just a square. Also, stopping the draw() function to execute gives me a proper square. I believe there’s a problem in the draw() function. Any help is appreciated 🙂

function draw(x, y, ctx){
    ctx.arc(x, y, 4, 0, Math.PI * 2);
    ctx.fillStyle = "#283149";
    ctx.fill(); // create circle
}
function createPolygon(n){
    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext('2d');
    ctx.reset();
    var size = 60, Xcenter = 80, Ycenter = 80;
    ctx.beginPath();
    ctx.moveTo (Xcenter +  size * Math.cos(0), Ycenter +  size *  Math.sin(0));          
    
    for (var i = 1; i <= n; i++) {
        ctx.lineTo (Xcenter + size * Math.cos(i * 2 * Math.PI / n), Ycenter + size * Math.sin(i * 2 * Math.PI / n));
        draw(Xcenter + Math.cos(i * 2 * Math.PI / n), Ycenter +  Math.sin(i * 2 * Math.PI / n), ctx);
    }
    ctx.fillStyle = "#00818A"
    ctx.fill();
}
<button onclick="createPolygon(4)">Create 4</button>
<canvas id="canvas"></canvas>

How to show content () as per selection options ()?

I want to show content based on user’s selection from

Like, when user selects the option “Option A” then only show the div containing “Orange”.

HTML:
`

 <div id="main-container">
        <select name="" id="user-selector" class="selector-dropdown">
            <option selected="true" style='display: none'>Select</option>
            <option value="Option A">Fruit</option>
            <option value="Option B">Animal</option>
            <option value="Option C">Language</option>
            <option value="Option C">Stationary</option>
        </select>

        <div class="output">Orange</div>
        <div class="output">Lion</div>
        <div class="output">English</div>
        <div class="output">Pen</div>

    </div>

`

Can you please help me with the JS code?

Thanks in advance.

I have searched in codepens, stackoverflow, and most were using jQuery which i could’nt understand. It really helps if you can help me the JS code.

Variance in Array vs TypedArray performance test

I am comparing the operation of reverse in Typed vs Standard Arrays i.e:

const a = new Array(1e6).fill(0).map( () => Math.random())
a.reverse()
const b = new Float64Array(1e6).map( () => Math.random())
b.reverse()

Certainly we expect Typed to be faster and maybe also to be narrow in variation from the mean time.

However, the standard arrays are slower (expected) but the variation around the mean is very large in comparison. In my computer this shows 3% in TypedArrays, 30% in Arrays.

Conceptually, what is the cause of this ?

See Test

How to limit the search scope without lookbehinds?

Given a regular expression, I can easily decide where to start looking for a match from in a string using lastIndex.
Now, I want to make sure that the match I get doesn’t go past a certain point in the string.

I would happily enclose the regular expression in a non-capturing group and append, for instance, (?<=^.{0,8}).

But how can I achieve the same goal without lookbehinds, that still aren’t globally supported?

Note:

  • While it might be the only reasonable fallback, slicing the string is not a good option as it results in a loss of context for the search.

Example

https://regex101.com/r/7bWtSW/1

with the base regular expression that:

  • matches the letter ‘a’, at least once and as many times as possible
  • as long as an ‘X’ comes later

We can see that we can achieve our goal with a lookbehind: we still get a match, shorter.
However, if we sliced the string, we would lose the match (because the lookahead in the base regular expression would fail).

Changing values in column in table using buttons

i would like create a table, where one column would be variables and i want to have “+” and “-” buttons next to it. So when i click button “+” it would show number input and after submit, it would add to the value.
It works for one value, but do not get the other right, without copying whole script.


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Table</title>
</head>
<style>
    body {
        background-color: lightslategray;
    }
    #PLA {
        float: left;
        width: 30%;
        padding: 10px;
    }
    th, td {
        border: 1px solid;
    }
    .header {
        text-align: center;
        font-size: 20px;
    }
    .celltext {
        font-size: 15px;
    }
    .number {
        text-align: center;
    }
    .vbutton {
        background-color: gray;
        border: 1px solid black;
        border-radius: 6px;
        color: white;
        text-align: center;
        text-decoration: none;
        font-size: 10px;
        padding: 0px;
        margin-right: 4px;
        width: 20px;
        height: 20px;
        float: right;        
    }
    button:hover {
        background-color: lightgray;
        color: black;
    }
    .input {
        padding: 0px;
        width: 48px;
        height: 16px;
        font-size: 14px;
        -webkit-appearance: none;
    }
    input[type = number] {
        -moz-appearance: textfield;
    }  
    input:focus {
        border: 0px;
        outline: 0px;
    } 
</style>
<body>
    <table id="PLA">
        <div>
            PLA
            <span id="test"></span>
            <input type="number" class="input" id="nwpla" onchange="changewpla1()" onkeypress="return onlyNumberKey(event)">
        </div>
        <tr class="header">
            <td>Barva</td>
            <td>Výrobce</td>
            <td>Hmotnost (g)</td>
            <td>Cena (kg)</td>
        </tr>
        <tr class="celltext">
            <td>černá <div class="box black"></div></td>
            <td>Polymaker PolyLite</td>
            <td class="number" id="pla1">
                <span id="wpla1"></span> 
                <button class="vbutton" onclick="addpla()"> + </button>  
                <button class="vbutton" onclick="subpla()"> - </button>  
            </td>
            <td class="number"> 
                800  
            </td>
        </tr>
        <tr class="celltext">
            <td>černá <div class="box black"></div></td>
            <td>Polymaker PolyLite</td>
            <td class="number" id="pla2">
                <span id="wpla2"></span> 
                <button class="vbutton" onclick="addpla()"> + </button>
                <button class="vbutton" onclick="subpla()"> - </button>  
            </td>
            <td class="number"> 
                800  
            </td>
        </tr>
    </table>
</body>
<script>
    // test
    test = document.getElementById("test");

    // Weight of pla1
    wpla1 = document.getElementById("wpla1");
    nwpla = document.getElementById("nwpla");
    nwpla.style.display = "none"; 
    var pla1weight = localStorage.pla1weight;
    localStorage.setItem("pla1weight", pla1weight); 

    if (localStorage.pla1weight == "undefined" || localStorage.pla1weight == isNaN) {
        localStorage.pla1weight = 0
        pla1weight = 0;
        wpla1.innerHTML = localStorage.pla1weight;
        wpla1.value = localStorage.pla1weight;
    }
    else {
        wpla1.innerHTML = localStorage.pla1weight;
        wpla1.value = localStorage.pla1weight;
    } 
    function changewpla1() {
        x = parseInt(wpla1.value, 10); 
        y = parseInt(nwpla.value, 10);       
        if (p == 1) {
            pla1weight = x - y; 
        } else {
            pla1weight = x + y;
        }            
        wpla1.innerHTML = pla1weight;
        wpla1.value = pla1weight;
        localStorage.setItem("pla1weight", pla1weight); 
        nwpla.style.display = "none";       
    }

    // Weight of pla2
    wpla2 = document.getElementById("wpla2");
    nwpla = document.getElementById("nwpla");
    nwpla.style.display = "none"; 
    var pla2weight = localStorage.pla2weight;
    localStorage.setItem("pla2weight", pla2weight); 

    if (localStorage.pla2weight == "undefined" || localStorage.pla2weight == isNaN) {
        localStorage.pla2weight = 0
        pla2weight = 0;
        wpla2.innerHTML = localStorage.pla2weight;
        wpla2.value = localStorage.pla2weight;
    }
    else {
        wpla2.innerHTML = localStorage.pla2weight;
        wpla2.value = localStorage.pla2weight;
    } 
    function changewpla2() {
        x = parseInt(wpla2.value, 10); 
        y = parseInt(nwpla.value, 10);       
        if (p == 1) {
            pla2weight = x - y; 
        } else {
            pla2weight = x + y;
        }            
        wpla2.innerHTML = pla2weight;
        wpla2.value = pla2weight;
        localStorage.setItem("pla2weight", pla2weight); 
        nwpla.style.display = "none";       
    }


    function addpla() {
        nwpla.value = 0;    
        p = 0;    
        nwpla.style.display = "";
    }
    function subpla() {
        nwpla.value = 0
        p = 1;
        nwpla.style.display = "";
    }
    function onlyNumberKey(evt) {
        var ASCIICode = (evt.which) ? evt.which : evt.keyCode
        if (ASCIICode > 31 && (ASCIICode < 48 || ASCIICode > 57))
            return false;
        return true;
    }

</script>
</html>

Any idea?
I would like to have a database as last option. Every value would be saved in local storage.

Thanks.

How can I pass the value of a javascript variable to django?

How can I send the value of “const token” to django?

function getToken() {
    PagSeguroDirectPayment.createCardToken({
        cardNumber: '4111111111111111', 
        brand: 'visa', 
        cvv: '123', 
        expirationMonth: '12', 
        expirationYear: '2030', 
        success: function(response) {
            const token = response.card.token;
        },
        error: function(response) {
            
        },
        complete: function(response) {
             
        }
     });
}

the getToken() function is being executed like this:

 <form action="{% url 'payments' %}" method="POST" onsubmit="getToken()">

I had tried to pass the Token value to a hidden input, and then I tried to get that value in django as shown below, but the input takes a while to receive the value and is already sent to the other page immediately. That way I would need to make sure that the input has the token value to let it forward to the other page

success: function(response) {
            document.getElementById('cardToken').value = response.card.token;
        },

JQuery .mask doesn’t allow more than 6 digits

I’m trying to add dots to separate thounsands in html input tags of type number. It works only for numbers of 6 digits, after adding one more digit to the input, the number disapears.

Here is the code

js

$(document).on("change", 'input[type="number"]', function () {
    const inputSelectors = $('input[type="number"]')
    inputSelectors.mask("000.000.000.000.000.000", {reverse: true});
    
})

html

<input class="detail-input" name="detail-unit-price" type="number" step="any" value="0" required>

I’ve tried commenting every other javascript line to make sure that the problem is related only to this method and the problem persists. If I omit the .mask() method, everythong works perfectly.

When I call a REST API I get JSON response with unencoded chars

While working on a NodeJS project I needed to make a REST call to a Mexican API to get profesional licensing information. Everything works fine except for the fact that all special chars such as ñ, á, ó etc. appear as �.

This is my code:

const express = require('express')
const fetch = require('node-fetch')
const cors = require('cors')
// const querystring = require('querystring')
// const qs = require('qs')

const app = express()
const license = '0987655' // This is hardcoded for debugging 

app.use(cors({credentials: true}))
  
  const responseAPI = async (license) => {
  const query = fetch("https://cedulaprofesional.sep.gob.mx/cedula/buscaCedulaJson.action", {
    credentials: "include",
    headers: {
      "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0",
      Accept: "*/*",
      "Accept-Language": "es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
      "Content-Type": "application/x-www-form-urlencoded; charset=utf-8",
      "X-Requested-With": "XMLHttpRequest",
      "Sec-Fetch-Dest": "empty",
      "Sec-Fetch-Mode": "cors",
      "Sec-Fetch-Site": "same-origin",
      "Sec-GPC": "1",
    },
    referrer: "https://cedulaprofesional.sep.gob.mx/cedula/presidencia/indexAvanzada.action",
    body: `json=%7B%22maxResult%22%3A%221000%22%2C%22nombre%22%3A%22%22%2C%22paterno%22%3A%22%22%2C%22materno%22%3A%22%22%2C%22idCedula%22%3A%22${license}%22%7D`,
    method: "POST",
    mode: "cors",
  });
    // The idea is to return the result but i log it for debugging
    const result = await (await query).json()
    console.log('Result >>', result)
  };
responseAPI(license)

The result is:


Result >> {
  items: [
    {
      anioreg: 1985,
      carArea: null,
      carCons: null,
      carNivel: null,
      carSarea: null,
      curp: null,
      desins: 'UNIVERSIDAD NACIONAL AUT�NOMA DE M�XICO',
      foja: null,
      idCedula: '0987655',
      inscons: 1,
      insedo: 9,
      libro: null,
      materno: 'RAMIREZ',
      maternoM: null,
      nombre: 'AURORA',
      nombreM: null,
      numero: null,
      paterno: 'PARRA',
      paternoM: null,
      sexo: '2',
      tipo: 'C1',
      titulo: 'LICENCIATURA COMO CIRUJANO DENTISTA'
    }
  ],
  filename: null,
  idCedula: null,
  idProfesionista: null,
  sessionId: null,
  theStream: null,
  token: null,
  urlVideo: null
}

The expected output shouls be:

// Omitted output
      desins: 'UNIVERSIDAD NACIONAL AUTÓNOMA DE MÉXICO',

// Omitted output

The thing is that the official site displays everything as it should, but when I use Firefox to copy the fetch call it shows the ‘error’.

I tried:

  • using qs
  • using querystring

So that’s it. I would really appreciate any input

How to control local web page(overlay)

There is a problem. I have an overlay for a game that takes data from the game and inserts it into the page. I paste this page into OBS as a browser.
At the bottom of this page (which is not visible on the stream) there is a small menu for managing.Something add an information about winning games(score), turn on / off some kind of blocks. But when I change something in the browser, of course nothing changes in OBS, tell me how to solve it.

I have tried the webserver but it doesn’t change.

Environment Variables Not Working with SWR

I’m finding it hard to use ENV variables with the SWR hook for data fetching.

I’ve been using it this way:

const videoURLWithEnv = `https://youtube.googleapis.com/youtube/v3/search?part=snippet&channelId=UCwkj9jcrMZCcbcIa6nF5LNQ&maxResults=3&order=date&key=${process.env.GOOGLE_API_KEY}`;

When I dont put my API key in the ENV file, it works like magic.

I’ve tried to implement the best practices of ENV files like not surrounding the varibale value with quotes, but it’s still not working.

While thinking it could be due to the YouTube API or the Google API key, I fetched data with another API but the problem remains the same — SWR still didn’t read the ENV variable.

How can I pull the just the keys out of object.values();?

I’ve been stuck on a teaching exercise for the better part of 2 days, and I decided I needed some help. I have to write a function called keys that returns an array of all the keys in the object without using object.keys();. I was able to turn everything into a string simply enough, and print everything using object.values(); but now I want to take what I obtained using object.values, and return just the key(As right now it returns key and value I.E – A:1, B:2, C:3 I want just ABC).

So far, this is a code I was trying. Please be kind, I am doing my best!

function keys(json) {
    var obj = JSON.parse(json);

*//My code starts here*
    const keys = Object.values(obj);
    keys.toString();
    for (const [key] of Object.Entries(obj)) {
        return(key);
    }
*//My code ends here*

}

There is “inputs” that test my code, they are below and represented in obj

first input:

{"a":"1","b":"2","c":"3"}

second input:

{"first":"Matt","last":"Lane"}

third input:

{}

How do I get multiple Modal instances to properly function in one page?

I’m creating a team page with modal popups for bio.

I’m using Hugo with Babel JS as the framework. There is no bootstrap on this project.

HTML

<div class="team-ui">
{{ with .Params.executive_team }}
   {{ range . }}
      {{ partial "components/modalTeammate.html" . }}
   {{ end }}
{{ end }}
</div>

{{ with .Params.executive_team }}
   {{ range . }}
      {{ partial "components/modalTeammateBio.html" . }}
   {{ end }}
{{ end }}

modalTeammate.html

<div class="teammate-card trigger" data-id="#myBio-{{ .modal_id }}" data-toggle="modal" data-target="myBio-{{ .modal_id }}" id="trigger">
    <img src="{{ if .img_overwrite }}/uploads/headshot-{{ .img_overwrite }}.png{{ else }}/uploads/headshot-{{ .name }}.png{{ end }}" alt="{{ .name }} | {{ .job_title }}" loading="lazy" class="teammate-img">
    <p class="teammate-name">{{ .name }}</p>
    <p class="teammate-jobtitle">{{ .job_title }}</p>
</div>

modalTeammateBio.html

<div class="modal myBio-{{ .modal_id }}" tabindex="-1" role="dialog" aria-hidden="true" id="myBio-{{ .modal_id }}">
    <div class="modal-content">
        <div class="modal-body">
            <div class="bio-box">
                <div class="bio-box-sidebar">
                    <img src="{{ if .img_overwrite }}/uploads/headshot-{{ .img_overwrite }}.png{{ else }}/uploads/headshot-{{ .name }}.png{{ end }}" alt="{{ .name }} | {{ .job_title }}" loading="lazy" class="teammate-img">
                    <p class="teammate-name">{{ .name }}</p>
                    <p class="teammate-jobtitle">{{ if .job_title_long }}{{ .job_title_long }}{{ else }}{{ .job_title }}{{ end }}</p>
                </div>
                <div class="bio-box-content">
                {{ with .bio }}
                    {{ range . }}
                    <p class="has-margin-bottom-half">{{ .p }}</p>
                    {{ end }}
                {{ end }}
                </div>
                <button class="modal-close is-large" aria-label="close"></button>
            </div>
        </div>
    </div>
</div> 

Current JS

var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var videoID = trigger.getAttribute('data-id');
var closeButton = document.querySelector(".modal-close");

// YouTube Player API Reference
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: videoID
    });
}

function toggleModal(e) {
    if (!modal.classList.contains("is-active")) {
        modal.classList.add("is-active");
        player.playVideo()
    }
    else {
        modal.classList.remove("is-active");
        player.pauseVideo()
    }
}

function windowOnClick(e) {
    if (e.target === modal) {
        toggleModal();
    }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

I know I’m missing something, but I’m not sure what else I can do.

I’m using this oringal code as an example and a base.

<a href="#" data-id="{{.Get "youtube"}}" class="button is-warning trigger" data-toggle="modal" id="trigger">Watch the Video</a>
<div class="modal" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-content">
        <div class="modal-body" id="player">
            Content
        </div>
    </div>
    <button class="modal-close is-large" aria-label="close"></button>
</div>

<script src="/js/modal.js"></script>

Make div disappear when clicking anywhere outside of it?

I am trying to make my div element disappear when clicking anywhere out side of it. The div is created when clicking a path from my SVG element and is supposed to close and open a new one when clicking the another path in the SVG. I think I may have set this up wrong and have been trying to figure out the most effective way to get it working. The div that has been created will hold an X button that will close the div and reload the page to bring back the styling options. Would that be the best way to go about this because I am thinking that may not be the most efficient way to do this.

$(document).ready(function(){
    $("#SVGGraphic").load("/src/Areas-of-Focus.svg", function(event){
        $("#SVGGraphic svg").css("height", "1000", "width", "1000px");

        console.log("loaded successfully")
        
        $("path").on("click", function(evt) {
            var parsedStringArray = evt.target.id.split('_');
            var pathID = ("#" + (evt.target.id))
            console.log(parsedStringArray);
            areaOfFocusBody(parsedStringArray[0]);
            colorChanger(pathID); 
        });
    })
})
function colorChanger(pathName){
    $("path").css("filter", "opacity(25%)")
    $("circle").css("filter", "opacity(25%)")
    $(pathName).css("fill", "#f1562c")
    $(pathName).css("filter", "opacity(100%)")
}

function areaOfFocusBody(areaOfFocus) {
    $("#DOM").append(`
    <div class="textbox" id="menucontainer">
        <span id="close" onclick="this.parentNode.remove(); location.reload(); return false;" class="btn btn-default large">
            <img src="/src/Esc X.svg" height="33" width="33"></img>
        </span>
        <h2>${focusCard[areaOfFocus]?.title ?? 'none'}</h2>
        <div class="card-body" id="card-div">
            <p class="card-body" style="padding: 1rem">${focusCard[areaOfFocus]?.body ?? 'none'}</p>
            <div class="container">
                <div class="row">
                    <div class="col text-center" style="padding-bottom: 1rem;">
                        <a target="_blank" rel="noopener noreferrer" href="${focusCard[areaOfFocus]?.url ?? 'none'}">
                            <button class="btn btn-primary" role="button">
                                Show Employees in this Section <img src="/src/opens-new-tab-arrow.svg" height="20">
                            </button>
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>`)
}

Before Click Event
After Click Event