How to hide checkboxes that aren’t checked?

Is there a way to hide checkboxes that aren’t checked? I have three checkboxes and I’m looking for a way to hide the ones that aren’t checked. The code I have now hides all checkboxes and I’m trying to hide the ones that aren’t checked.

This is my code:

$('input[type=checkbox]').each(function ()
        {
            //Check if the box is checked
            var x = $(this).is(':checked');
                      
            //if checkbox is NOT checked
            if(x === false) 
                {
                    //Hide the choice
                    $(this).parent().hide();
                }

        });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="testing" value="B">A</label><br />
<input type="checkbox" name="testing" value="I">B</label><br />
<input type="checkbox" name="testing" value="A">C</label><br />

json to pdf in javasript without any libraries

is there any method that may be able to convert JSON data to pdf with using only pure Javascript, without using any libraries or packages

There is a requirement to create a single html page (done with help of webpack) for offline work . so i need to download some json as pdf and should not not use any libraries

Why is AudioBuffer.getChannelData() returning values greater than 1.0?

I have used AudioContext.decodeAudioData() to decode a FLAC file into an AudioBuffer and then called getChannelData to get a Float32Array of audio samples. The samples are supposed to be in the range of -1 and 1 (I’m not sure if it’s inclusive or exclusive) but I am actually getting values like 1.006. The audio source is 16-bit signed integer, so it seems to me like the only way you get values greater than 1 is if your method for converting/scaling integers to floats is seriously off somehow.

Brower is latest Chrome on Windows 11.

How to show loader and animation once per session?

I’ve coded a personal portfolio website and added all the things I’ve wanted to add. Now, I am just cleaning it up and working on the UX/ IX stuff to make it more pleasant to navigate and interact with.

With that said, I am trying to make my loader/ loader animation (the spinning bubbles AND the “fade in” aspect) only occur once, when you FIRST enter the website! This is what I have so far, and it works rather nicely. HOWEVER, when you refresh the page or try to navigate back to the homepage from my projects page, there is a rather long waiting screen and then the “fade in” animation comes back.

If anyone could help me, I am trying to make it so that when you refresh or nav back to the home page AFTER you’ve already seen the loader/ animation, the home page instantly loads without delay, loader, or animation/

Thank you

const navToggle = document.querySelector('.nav-toggle');
const navLinks = document.querySelectorAll('.nav__link')
const loader = document.querySelector('.loader');
const main = document.querySelector('.main'); 

function init() {
    setTimeout(() => {
        loader.style.opacity = 0;
        loader.style.display = 'none';
    
        main.style.display = 'block';
        setTimeout(() => (main.style.opacity = 1), 50);
    },2000);
}

init();


navToggle.addEventListener('click', () => {
    document.body.classList.toggle('nav-open');
});

navLinks.forEach(link => {
    link.addEventListener('click', () => {
        document.body.classList.remove('nav-open');
    })
})

window.addEventListener("load", function () {
    if (!sessionStorage.viewed){
        const loader = document.querySelector(".loader");
        loader.className += " hidden";
        sessionStorage.viewed = 1;
    }else{
        const loader = document.querySelector(".loader");
        loader.style.display = "none";
    }
})
.loader {
    position: fixed;
    z-index: 999;
    overflow: show;
    margin: auto;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    width: 50px;
    height: 50px;
    text-align: center;
    transform-origin: bottom center;
    animation: rotate 3s linear infinite;
}

.circle {
    display: inline-block;
    background-color: #16e0bd;
    height: 50px;
    width: 50px;
    border-radius: 50%;
    transform: scale(0);
    animation: grow 1.5s linear infinite;
    margin: -10px;
}

.circle:nth-child(2) {
    background-color: #303030;
    animation-delay: 0.75s;
}

@keyframes rotate {
    to {
        transform: rotate(360deg);
    }
}

@keyframes grow {
    50% {
        transform: scale(1);
    }
}
 <div class="loader">
        <div class="circle"></div>
        <div class="circle"></div>
    </div>

<div class="main" >

Errors while doing ‘Angular frontend – Blockchain in Javascript (part 5)’ with Simply Explained

Video link: Blockchain video

File I am editing that is causing errors: Blockchain.service.ts

  1. Around 9:48 in the video, when you have to import the Blockchain from your folder, the source, then ‘Blockchain’ (for example, SavjeeCoin/src/blockchain), I have an error saying, “Cannot find module ‘owencoin/src/blockchain’ or its corresponding type declarations.”
  2. Around 10:23 in the video, when you have to import EC from elliptic, I am getting an error saying, “Module ‘”C:/Users/peter/Desktop/owencoin/node_modules/@types/elliptic/index”‘ has no default export.”
  3. Around 12:50-13:07 in the video, when you have to create a keyObj, public key, and private key, an error for each of them says, “(property) privateKey: any
    Type ‘any’ is not assignable to type ‘never’.”

Why does returning one arrow function work and the other not? [duplicate]

Both arrow functions should return the result, but why does only the first one work?

It works:

const createUser = (name, email) => ({name, email})
const user1 = createUser("User Test", "[email protected]")
console.log(user1)

Does not work:

const createUser = (name, email) => {name, email}
const user1 = createUser("User Test", "[email protected]")
console.log(user1)

How to run css transition using javascript when element is in the middle of the screen

I’m currently making my website more mobile-friendly, but :hover doesn’t work on mobile. I have buttons and other elements with hover transition effects so I thought the next best solution would be running the effect when the element is in the middle of the user’s screen, like how on the youtube app it will start playing the beginning of a video if it is in the middle of your screen. How do I use Javascript to detect when an element is vertically in the middle of a user’s screen, let’s say somewhere in the range of 300px to 600px, and to apply a css transition, like changing the color from white to red over 1 second?

How to reference my site’s server’s IP address in JavaScript?

I have a contact form on my website that I created with Node.js. When I run the site as a local host (localhost:5000), everything works fine. I fill out the contact form and when I hit send, I get a thank you alert and the email goes through.

However, once I connected my site to a domain and had it live, it no longer works – I get the “invalid login” message. Could it be that I am not connecting to the correct server?

Here is my Server.js file. I believe my problem lies in the 4th line where I define the PORT varaible. How can I define the PORT variable as the site’s IP address? I’m assuming this will let my code run on the correct server.

const express = require('express');
const app = express();

const nodemailer = require("nodemailer");

const PORT = process.env.PORT || 5000;

//Middleware
app.use(express.static('public'));
app.use(express.json())

app.get('/', (req, res)=>{
    res.sendFile(__dirname + '/public/Request.html')
})

app.post('/', (req, res)=>{
    console.log(req.body);

    const transporter = nodemailer.createTransport({
        service: 'gmail',
        auth: {
            user: '//kept hidden',
            pass: //kept hidden 
        }
    })

const mailOptions = {
    from: req.body.email,
    to: '//kept hidden',
    subject: 'New message from Ogma',
    text: [req.body.email, req.body.password, req.body.amount, `req.body.service, req.body.details].join('nn')`
}

transporter.sendMail(mailOptions, (error, info) =>{ 
    if(error){
        console.log(error);
        res.send('error');
    } else {
        console.log('Email sent: ' + info.response);
        res.send('success')
    }
})

})

app.listen(PORT, ()=>{
    console.log('Server running on port ${PORT}')
})

Module parse failed: Unexpected character ” (1:4) You may need an appropriate loader to handle this file type

I am trying to use a .glb file into a react-fiber-three app.

Error says about a GLB file:

Module parse failed:
Unexpected character ” (1:4)
You may need an appropriate loader to handle this file type

My file using this file:

export default function Blender() {
const gltf = useLoader(GLTFLoader, gumballmachinepink);

return (
    <primitive
        object={gltf.scene}
        position={[0, 0, 0]}
        scale={10}
        rotation={[0, 0, 0]}
    />
) }

useGLTF.preload(gumballmachinepink);

My Webpack.config file:

module.exports = {
mode: ‘production’,
entry: path.join(__dirname, ‘App.tsx’),
devtool: “source-map”,
output: {
path: path.join(__dirname, ‘dist’),
filename: ‘own-me-gumball-machine.prod.js’,
},
module: {
rules: [
{

            test: /.(ts|js)x?$/,
            exclude: /node_modules/,
            use: {
                loader: "babel-loader",
                options: {
                    presets: [
                        "@babel/preset-env",
                        "@babel/preset-react",
                        "@babel/preset-typescript",
                    ],
                },
            },
        },
        {
            test: /.(glb|gltf)$/,
            use:
            [
                {
                    loader: 'file-loader',
                    options:
                    {
                        outputPath: 'assets/models/'
                    }
                }
            ]
        },
        {
            test: /.css$/i,
            use: ['style-loader', 'css-loader'],
        },
        {
            test: /.(png|jpe?g|gif|woff(2)?|svg)$/i,
            type: 'asset/resource'
        },
    ]
},
resolve: {
    extensions: [".tsx", ".ts", ".js", ".css"],
},
plugins: [
    new HtmlWebpackPlugin({
        inject: true,
        template: path.join(__dirname, 'index.html'),
    }),
    // new CopyPlugin({
    //     patterns: [
    //         { from: "media/favicons/", to: "media/favicons/" },
    //     ],
    // }),
] };

Hope someone can help!

Creating custom filter function. Type ‘boolean’ is not assignable to type ‘T[]’

I have this code:

this.dataType1 = x.stats.dataType1;
this.dataType2 = x.stats.dataType2;
this.dataType3 = x.stats.dataType3;
this.dataType4 = x.stats.dataType4;

Each dataTypeX is an array of objects each object has name property

I want to filter each array according with jointArray so I implemented this filter:

  this.dataType1 = x.stats.dataType1.filter((f) =>
    jointArray
      .filter((x) => x.type.includes('sometext'))
      .some((item) => item.name === f.name)
  );

Now I want to apply same filter to all dataTypes but I do not want to replicate that, so I want to create a custom filter function to be able to call it for each array:

this.dataType1 = x.stats.dataType1.filter((x) => this.setFilter<DataType1>(x, 'sometext'));
this.dataType2 = x.stats.dataType1.filter((x) => this.setFilter<DataType2>(x, 'sometext'));
...

So I tried to refactor my code creating that filter function

  private setFilter1<T>(f: any, type: string): T[] {
    return jointArray
        .filter((x) => x.type.includes(type))
        .some((item) => item.name === f.name)
  }

Got an error:

Type 'boolean' is not assignable to type 'T[]'

Any ideas how to fix?

Fail to send JSON HTTP POST, but succeed to send text HTTP POST. why?

I want to send a JSON http POST from an HTML page. The Fetch API is used here.
It can be successfully posted if the content-type is “application/x-www-form-urlencoded” or “text/plain”, but fails to post if the content-type is “application/json”. I have tried Both Fetch and Axios API. But JSON can be posted successfully posted from an online http tool (https://reqbin.com/)
enter image description here

Here is my client code in HTML:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>test</title>
</head>
<body>
<h1 id ="h1">post test</h1>
<input type="submit" value="post" onclick="sendpost()">
<script>
    function sendpost()
    {
        const Url = 'https://my-worker.sgcloud.workers.dev/';

        const data = {
            name: 'moe',
            age: '50'
        };

        fetch(Url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        })
            .then(response => response.text()
                .then(text => {
                    document.getElementById("h1").innerHTML = text;
                }))
            .catch(err => console.log(err))
    }
</script>
</body>
</html>

The error in development tool is:

POST https://my-worker.sgcloud.workers.dev/ net::ERR_FAILED

The server is in my cloudflare workers: https://my-worker.sgcloud.workers.dev/ , Access-Control-Allow-Origin is on. You can try to post to my server.
the server code is:

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  if (request.method == 'GET') {
  return new Response('Hello Worker!', {
    headers: { 'content-type': 'text/plain', 'Access-Control-Allow-Origin': '*' },
  });
  } else if (request.method == 'POST') {
  return new Response('Response for POST!', {
    headers: { 'content-type': 'text/plain', 'Access-Control-Allow-Origin': '*' },
  });
  } else {
    response = new Response('Expected POST', { status: 500 });
  }
}

because I can post json from the online tool, so my client code should have some problem to send application/json (the client code can send text/plain or application/x-www-form-urlencoded, tested). How shoud I change my code to send json? Thank you

Update object in useState works only once

I’m trying to update the selected object from my useState called choosenProducts and it works fine but only if it has an object, having more than one doesn’t work anymore and it sends me the error:

Uncaught ReferenceError: Cannot access ‘newQuantity’ before
initialization

This is my code:


    const onChangeQuantityHandler = (id, e) => { 
      const newQuantity = chosenProducts.map( p => {
        if(p._id === id){
          return {
            ...p, quantity:e, subtotal: e * p.price 
          }
        }
        return newQuantity
      })

      setChosenProducts(newQuantity)
     }


My input:

<input type="number" value={product.quantity} onChange={ (e)=> onChangeQuantityHandler(product._id, e.target.value)  }/> 

I don’t understand why it only works once with a single object. Thanks for your help.

create-react-app Failing to create a new React app in MACos

I have problem using npx create-react-app but i have the pproblem below. I have tried using npm cache clean –force and then npx but the problem persist… Any suggestions?? i have tried using different nodes versions

npx: installed 67 in 4.058s

Creating a new React app in /Users/nestorvargas/Documents/React/myfirstreactapp.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template…

npm ERR! cb.apply is not a function

npm ERR! A complete log of this run can be found in:
npm ERR! /Users/nestorvargas/.npm/_logs/2022-06-26T02_40_25_044Z-debug.log

Aborting installation.
npm install –no-audit –save –save-exact –loglevel error react react-dom react-scripts cra-template has failed.

Deleting generated file… package.json
Deleting myfirstreactapp/ from /Users/nestorvargas/Documents/React
Done.