Dynamically update unique number input field with multiple slider range inputs (Javascript)

I have multiple fields in a form that each have a input range slider and a number input. I would like to update the individual number input field based on the range slider value. I was able to make this work for the first field with slider/number, but can’t seem to make it work with the others. I would like to avoid having to write code for each form field, ideally would have this work dynamically.

Image of form fields (can only update the first)

HTML:

<div class="form-container">

<h2>Savings and Investments:</h2>

<div class="form-group">
    Non-Registered investments (Taxable):

    <span class="range-wrap">
        <input type="range" class="form-range" min="0" max="5000000" step="5000" value="0" id="customRange">

        <span class="number-input">
            <span class="dollar-symbol">$</span>
            <input type="number" id="demo" class="submit-taxable" value=0>
        </span>
    </span>                                
</div>

<div class="form-group">
    Tax-free savings account (TFSA):

    <span class="range-wrap">
        <input type="range" class="form-range" min="0" max="5000000" step="5000" value="0" id="customRange">

        <span class="number-input">
            <span class="dollar-symbol">$</span>
            <input type="number" id="demo" class="submit-tfsa" value=0 >
        </span>
    </span>

</div>

<div class="form-group">
    Registered Retirement Savings (ex: RRSP): 

    <span class="range-wrap">
        <input type="range" class="form-range" min="0" max="5000000" step="5000" value="0" id="customRange">

        <span class="number-input">
            <span class="dollar-symbol">$</span>
            <input type="number" id="demo" class="submit-rrsp" value=0>
        </span>
    </span>

</div>

<div class="form-group">
    Other: 
    <span class="range-wrap">
        <input type="range" class="form-range" min="0" max="5000000" step="5000" value="0" id="customRange">

        <span class="number-input">
            <span class="dollar-symbol">$</span>
            <input type="number" id="demo" class="submit-investment-other" value=0>
        </span>
    </span>
</div>

Javascript:

var slider = document.getElementById("customRange");

var output = document.getElementById("demo");

output.innerHTML = slider.value; // Display the default slider value

// Update the current slider value (each time you drag the slider handle)
slider.oninput = function() {
output.value = this.value;
}

Insert an element in an existing object inside an existing array in JS

Current Situation:

                var alerts = [ 
                {num : 1, app:'helloworld',message:'message'},
                {num : 2, app:'helloagain',message:'another message'} 
                ]

Desired Situation:
This is the array being returned from a web service now after receiving need to add an element to this existing object inside the array and pass it further.

               var alerts = [ 
              {id:"New Elelment",num : 1, app:'helloworld',message:'message'},
              {num : 2, app:'helloagain',message:'another message'} 
              ]

Pass Item data value into controller using js

Hello i have problem with my project, i try to JSON but i have multiple variable so i dont know if it works, and when i try passing $id into controller snap and calling data using mysql items data is null. im stuck at here

here my view

<div class="row">
<table class="table mt-3" id="t_detail">
    <thead class="thead">
        <tr>
        <th scope="col">#</th>
        <th scope="col">Gambar</th>
        <th scope="col">Nama Barang</th>
        <th scope="col">Harga</th>
        </tr>
    </thead>
    <tbody>
        <?php $no=0;foreach ($produk as $id=>$prd): ?>
            <?php $no++?>
        <tr>
            <?php $barang []= array(
                'id' => $prd->id_barang,
                'quantity' => 1,
                'price' => $prd->harga,
                'name' => $prd->nama_barang,
            );?>
        <th scope="row"><?=$no?></th>
        <td><img height="280" width="auto" src="<?=base_url('uploads/' . $prd->gambar)?>" ></td>
        <td><?=$prd->nama_barang?></td>
        <td>Rp. <?php echo number_format($prd->harga,0,",",".");?></td>
        </tr>
        <?php endforeach;?>
        <?php $no++?>
        <tr>
        <th scope="row"><?=$no?></th>
        <td></td>
        <td>Biaya Ongkir</td>
        <td>Rp. <?php echo number_format($transaksi->ongkir,0,",",".");?></td>
        </tr>
    </tbody>
    <tfoot>
    <tr>
        <th scope="row"></th>
        <td></td>
        <td>Total Bayar</td>
        <td>Rp. <?php echo number_format($transaksi->total_bayar,0,",",".");?></td>
        </tr>
    </tfoot>
    </table>
</div>
<?php if ($produk):?>
    <div class="row">
    <div class="col-md-6 offset-md-6">
    <button class="btn btn-sm btn-success float-right" id="tombol-bayar">Bayar</button>
    </div>
</div>
<?php endif;?>
<input name="transaksi_id" value="<?=($transaksi->id)?>" type="hidden">
<input name="nama" value="<?=($transaksi->namalengkap)?>" type="hidden">
<input name="alamat" value="<?=($transaksi->alamat)?>" type="hidden">
<input name="kodepos" value="<?=($transaksi->kodepos)?>" type="hidden">
<input name="kabupaten" value="<?=($transaksi->kabupaten)?>" type="hidden">
<input name="no_hp" value="<?=($user['no_hp'])?>" type="hidden">
<input name="email" value="<?=($user['email'])?>" type="hidden">
<input name="total_bayar" value="<?=($transaksi->total_bayar)?>" type="hidden">
<input name="ongkir" value="<?=($transaksi->ongkir)?>" type="hidden">
<input name="ekspedisi" value="<?=($transaksi->ekspedisi)?>" type="hidden">
<input name="paket" value="<?=($transaksi->paket)?>" type="hidden">

and my JS

<script>
    $('#tombol-bayar').click(function(event) {

        var transaksi_id = $("input[name=transaksi_id]").val();
        var nama = $("input[name=nama]").val();
        var alamat = $("input[name=alamat]").val();
        var email = $("input[name=email]").val();
        var kodepos = $("input[name=kodepos]").val();
        var ongkir = $("input[name=ongkir]").val();
        var ekspedisi = $("input[name=ekspedisi]").val();
        var paket = $("input[name=paket]").val();
        var kabupaten = $("input[name=kabupaten]").val();
        var no_hp = $("input[name=no_hp]").val();
        var total_bayar = $("input[name=total_bayar]").val();

        $(this).attr("disabled", "disabled");

        $.ajax({
            type: "POST",
            url: '<?= base_url() ?>/snap/token',
            cache: false,
            data: {
                barang: barang,
                'transaksi_id': transaksi_id,
                'nama': nama,
                'alamat': alamat,
                'email': email,
                'kodepos': kodepos,
                'ongkir': ongkir,
                'ekspedisi': ekspedisi,
                'paket': paket,
                'kabupaten': kabupaten,
                'no_hp': no_hp,
                'total_bayar': total_bayar,
            },

            success: function(data) {
                //location = data;

                console.log('token = ' + data);

                var resultType = document.getElementById('result-type');
                var resultData = document.getElementById('result-data');

                function changeResult(type, data) {
                    $("#result-type").val(type);
                    $("#result-data").val(JSON.stringify(data));
                    //resultType.innerHTML = type;
                    //resultData.innerHTML = JSON.stringify(data);
                }

                snap.pay(data, {

                    onSuccess: function(result) {
                        changeResult('success', result);
                        console.log(result.status_message);
                        console.log(result);
                        $("#payment-form").submit();
                    },
                    onPending: function(result) {
                        changeResult('pending', result);
                        console.log(result.status_message);
                        $("#payment-form").submit();
                    },
                    onError: function(result) {
                        changeResult('error', result);
                        console.log(result.status_message);
                        $("#payment-form").submit();
                    }
                });
            }
        });
    });

and my controller

 public function token()
{

    $nama = $this->input->post('nama');
    $email = $this->input->post('email');
    $kabupaten = $this->input->post('kabupaten');
    $kodepos = $this->input->post('kodepos');
    $alamat = $this->input->post('alamat');
    $no_hp = $this->input->post('no_hp');
    $ekspedisi = $this->input->post('ekspedisi');
    $paket = $this->input->post('paket');
    $ongkir = $this->input->post('ongkir');
    $total_bayar = $this->input->post('total_bayar');
    $barang = $this->input->post('barang');

    $item_details [] = $barang;

how can i post items data into that controller.. im confuse please help

Adding query parameters to a url on page load before api call causes queries to unset

Please hear me out I have been struggling for days with this:

I am working in a big old project. When the page is loaded a useEffect uses dispatch to call the api and fetch the data.

I am trying to add query params to the URL in the url onLoad. I have a set of queryParameters held in localStorage if localStorage does not have the value in it I use a default set of parameters.

Ideally I would like to set the url queryParams on load then to make the api call using the data contained within the URL (not sure if this series of events is even possible seems like it would have to happen real quick).

Currently I have my query parameters being set in the first useEffect in the component.
Like this:

useEffect(() => {
  let theURL = new URL(window.location.href);
  const storedParams = window.localStorage.getItem("searchParams");

  if (storedParams) {
    let params = JSON.parse(storedParams);

    for (const [key, value] of Object.entries(params)) {
      let valueString = value.toString();
      theURL.searchParams.set(key, valueString);
    }
  } else {
    for (const [key, value] of Object.entries(defaultParams)) {
      let valueString = value.toString();
      theURL.searchParams.set(key, valueString);
    }
  }
  // may need to set the state of queryParams here
  loadQueries(theURL?.search);
}, []);

Following this useEffect is another that calls the api:

useEffect(() => {
  if (currentView === VIEW_RECENT_ENCOUNTER) {
    fetchFilteredEncounters();
  } 
  return () => {
    onUnload();
  };
}, [ currentView, queryParams]);

 const fetchFilteredEncounters = async () => {
    onLoad(api.Monitoring.filteredEncounters(queryParams));
    setLoading(false);
  };

I have two issues:

  1. When the page loads the query params are set in the URL then immediately unset once the api call is made. Which I think could be solved if I understood:

  2. How to use the query params from the URL to form what is now passed in
    onLoad(api.Monitoring.filteredEncounters(queryParams)). All while keeping the params in the url…

I sure hope this makes sense to someone. Thanks in advance!

How do I know what is the size limit for constructing a Set in JavaScript?

I am making a tool for deleting geometry from a model in browser.

At some step of the deletion process, I take an array full of indexes and create a Set from it to get the array of unrepeated indexes.

function GetSetFromArray(array){
    return new Set(array);
}

This function has worked good for many models at the beginning. Since I want to process the deletion as fast as possible, I wanted to avoid using solutions that require .indexOf.

But when I try to delete from a big model, for example, an array with a length of roughly 15,000,000. I get the following error on the browser’s console:

Uncaught (in promise) RangeError: Set maximum size exceeded

console error screenshot

I want to know, what is the maximum size for creating a Set?
Is it something that depends on the Browser? Or on the PC running the Browser? Is there a way to get that number? I think that maybe if I could get the size limit of the Set, I could then split the array to make a series of Sets and then use that?

How to smooth-scroll to an anchor tag from another page in NextJS?

I have 2 pages in my NextJS (1 is Home and another is Leaderboard page). And I have a navbar as such:

<div className={styles.navItem}>
        <Link href="/">
          <a className={styles.navLinks} onClick={toggle}>
            Home
          </a>
        </Link>
      </div>
      <div className={styles.navItem} onClick={toggle}>
        <Link href="/">
          <a
            className={styles.navLinks}
            onClick={setTimeout((e) => {
              document.getElementById("about") &&
                document
                  .getElementById("about")
                  .scrollIntoView({ behavior: "smooth", block: "end" });
            }, 2000)}
          >
            About Us
          </a>
        </Link>
      </div>
      <div className={styles.navItem} onClick={toggle}>
        <Link href="/">
          <a
            className={styles.navLinks}
            onClick={setTimeout((e) => {
              document.getElementById("program") &&
                document
                  .getElementById("program")
                  .scrollIntoView({ behavior: "smooth", block: "end" });
            }, 2000)}
          >
            Program Overview
          </a>
        </Link>
      </div>
      <div className={styles.navItem}>
        <Link href="/leaderboard/">
          <a className={styles.navLinks} onClick={toggle}>
            Leaderboard
          </a>
        </Link>
      </div>

I thought that maybe by using a setTimeout delay it would, redirect me first to the homepage (when I click the Link tag) and then, after 2 seconds, it would smooth scroll me to the section I wanted to go to. But this produces an error document is not defined and when I reload the page, the page would smooth-scroll to #program after 2 seconds even without clicking on the tag. What am I doing wrong?

How to use transformResponse in RTK Query to change server response

Please I am new to RTK query, I made an API call that returns an array of arrays of objects, I want to use the transformResponse option to flatten the API response to just one array of objects.

Here is my code


getStocks: builder.query({
    query: credentials => ({
        url: `stocks`,
        body: {credentials},
        transform: response => {
            console.log(response);
            return response;
        },
    }),
   })

Here is the API response data


[
    [
        {
            1. Information: "Monthly Adjusted Prices and Volumes"
            2. Symbol: "AAPL"
            3. Last Refreshed: "2022-06-28 16:00:01"
            4. Time Zone: "US/Eastern"
        }, 
        {
            1. open: "101.0000"
            2. high: "118.0000"
            3. low: "91.0600"
            4. close: "102.8100"
            5. adjusted close: "0.7848"
            6. volume: "84091200"
            7. dividend amount: "0.0000"
        }
    ],
    [
        {
            1. Information: "Monthly Adjusted Prices and Volumes"
            2. Symbol: "MSFT"
            3. Last Refreshed: "2022-06-28 16:00:01"
            4. Time Zone: "US/Eastern"
        }, 
        {
            1. open: "101.0000"
            2. high: "118.0000"
            3. low: "91.0600"
            4. close: "102.8100"
            5. adjusted close: "0.7848"
            6. volume: "84091200"
            7. dividend amount: "0.0000"
        }
    ],
    [
        {
            1. Information: "Monthly Adjusted Prices and Volumes"
            2. Symbol: "BYD"
            3. Last Refreshed: "2022-06-28 16:00:01"
            4. Time Zone: "US/Eastern"
        }, 
        {
            1. open: "101.0000"
            2. high: "118.0000"
            3. low: "91.0600"
            4. close: "102.8100"
            5. adjusted close: "0.7848"
            6. volume: "84091200"
            7. dividend amount: "0.0000"
        }
    ],
    [
        {
            1. Information: "Monthly Adjusted Prices and Volumes"
            2. Symbol: "SEC"
            3. Last Refreshed: "2022-06-28 16:00:01"
            4. Time Zone: "US/Eastern"
        }, 
        {
            1. open: "101.0000"
            2. high: "118.0000"
            3. low: "91.0600"
            4. close: "102.8100"
            5. adjusted close: "0.7848"
            6. volume: "84091200"
            7. dividend amount: "0.0000"
        }
    ]
]

Here is how I want to output the data.

Symbo Close
AAPL 120
BYD 130
CSC 123
SEC 433

Transforming a string from an API call into Markdown syntax?

Let’s say I have a (graphQL) API call that returns the following:

node {
   "body": "* Hellornrn_World_",
}

Which is

* Hello

_World_

in the original Markdown.

(To be more specific, I’m fetching github issues comments. I know there’s an option for HTML in the github API, but I’m just curious.)

Is there any easy way to turn that back to Markdown in javascript? Without regex.

How do I render markers onto a map from firebase with React.js

I am creating a web app using react.js, google maps, and firebase. This is all a little new to me. I am trying to render markers onto the map from the firestore/database. I was able to read the data on one of my other pages. However, I am not sure if I can use the same method to read/display the data as markers on the map.

How I’m reading the data on my other page

import React, { useState, useEffect } from 'react';
import { db } from '../firebase-config';
import { collection, getDocs, addDoc, deleteDoc, doc } from 'firebase/firestore';
import Navigation from './Navigation';
import '../App.css';

const Trails = () => {
    const [trails, setTrails] = useState([]);
    const trailsCollectionRef = collection(db, "trails")
    
    useEffect(() => {
        
        const getTrails = async () => {
            const data = await getDocs(trailsCollectionRef);
            setTrails(data.docs.map((doc) => ({ ...doc.data(), id: doc.id})));
        };
        getTrails()
    }, [])

    return (
    <div>  
        <div>
        <Navigation />
        </div>
        <div className="content">
            <h1>Trails</h1>
            {trails.map((trail) => {
                return (
                    <div>
                        {" "}
                        <h3>{trail.name}</h3>
                        <p>{trail.description}</p>
                        <p>Coordinates: {trail.latitude}, {trail.longitude}</p>
                    </div>    
                ) 
            })}
        </div>
    </div>
    )
}

export default Trails;

My map page that I’m trying to display the data as markers

import React, {Component, useEffect, useState} from 'react';
import {Map, GoogleApiWrapper, InfoWindow, Marker} from "google-maps-react";
import Navigation from './Navigation';
import { db } from '../firebase-config';
import { collection, getDocs } from 'firebase/firestore';


class MapContainer extends Component {
  state = {
    showingInfoWindow: false,  
    activeMarker: {},         
    selectedPlace: {},    
    trailLocation:[]
  };
 
  onMarkerClick = (props, marker, e) =>
  this.setState({
    selectedPlace: props,
    activeMarker: marker,
    showingInfoWindow: true
  });

  onClose = props => {
    if (this.state.showingInfoWindow) {
      this.setState({
        showingInfoWindow: false,
        activeMarker: null
      });
    }
  };

  render() {
    return(
      <div>
          <div>
              <Navigation />
          </div>
          <div>
              <Map
                google = {this.props.google}
                style = {{width: "100%", height: "100%"}}
                zoom = {10}
                initialCenter = {
                  {
                  lat: 47.6062,
                  lng: -122.3321
                  }
                }
              >
              <Marker
                  onClick={this.onMarkerClick}
                  name={'Washington Park Aboretum'}
                  position={{
                  lat: 47.6416,
                  lng: -122.2905
                }}
                />
                <InfoWindow
                  marker={this.state.activeMarker}
                  visible={this.state.showingInfoWindow}
                  onClose={this.onClose}
                >
                  <div>
                    <h4>{this.state.selectedPlace.name}</h4>
                  </div>
                </InfoWindow>
              </Map>
          </div>
          </div>
    );
  }
}

export default GoogleApiWrapper({
  apiKey: process.env.REACT_APP_GOOGLE_API_KEY
})(MapContainer)

enqueued js in wordpress but not executed code

hey everyone hope y’all doing fine
i have a small prob here , soo im developing a plugin for a carousel,

<?php
/* 
* @wordpress-plugin
* Plugin Name: FyStories
* Description : FyStories is a plugin that Displays edited Photos and Videos with an Instagram display ratio "9:16"
* Version: 1.0.0
* Author: Hamza KHIAR
* Requires PHP : 8.1 
*/
class FyStories
{
    // private static $dom;
    // private static $carousel;
    public function __construct()
    {
        add_action('init', [FyStories::class, 'fystory_container_sc']);
        add_action('init', [FyStories::class, 'fystory_container_item_sc']);
        // add_action('save_post',[FyStories::class,'saving_post']);
    }
    /* 
    this is for activating,and registering scripts in the plugin's page
    */
    public static function activate()
    {
        flush_rewrite_rules();
    }
    public static function deactivate()
    {
    }
    public static function register_static_files()
    {
        add_action('wp_enqueue_scripts', [FyStories::class, 'add_js']);
        add_action('wp_enqueue_scripts', [FyStories::class, 'add_css']);
    }
    public static function add_css()
    {
        // wp_register_style('fy-story-style', plugin_dir_url(__FILE__) . 'Carousel/static/css/style.css');
        // wp_register_style('flickity.min', plugin_dir_url(__FILE__) . 'Carousel/static/css/flickity.min.css');
        wp_enqueue_style('fy-story-style', plugin_dir_url(__FILE__) . 'Carousel/static/css/style.css');
        wp_enqueue_style('flickity.min', plugin_dir_url(__FILE__) . 'Carousel/static/css/flickity.min.css');
    }
    public static function add_js()
    {
        // wp_register_script('fy-story-script', plugin_dir_url(__FILE__) . 'Carousel/static/js/script.js');
        // wp_register_script('flickity.pkgd.min', plugin_dir_url(__FILE__) . 'Carousel/static/js/flickity.pkgd.min.js');
        wp_enqueue_script('fy-story-script', plugin_dir_url(__FILE__) . 'Carousel/static/js/script.js');
        wp_enqueue_script('flickity.pkgd.min', plugin_dir_url(__FILE__) . 'Carousel/static/js/flickity.pkgd.min.js');
    }
    public static function add_media_uploader()
    {
        wp_enqueue_script('media_upload');
        wp_enqueue_script('fy_media', plugin_dir_url(__FILE__) . 'Carousel/static/js/fy_media.js');
        wp_enqueue_media();
    }
    /* 
    adding the meta-box to enable adding custom fields in the container or items
    */
    public static function fystory_container_sc()
    {
        register_post_type('fystory_container', [
            'labels' => [
                'name' => __('Fystories'),
                'singular_name' => __('Fystory')
            ],
            'public' => true,
            'has_archive' => true,
            'supports' => ['title'],
            'register_meta_box_cb' => [FyStories::class, 'container_meta_box']
        ]);
    }
    public static function custom_mediaUpload($hook)
    {
        if ('edit.php' !== $hook) {
            return;
        }
        wp_enqueue_script('media_upload');
        wp_enqueue_script('fy_media', plugin_dir_url(__FILE__) . 'Carousel/static/js/fy_media.js');
        wp_enqueue_media();
    }
    public static function fystory_container_item_sc()
    {
        register_post_type('fystory_item', [
            'labels' => [
                'name' => __('Fystory Items'),
                'singular_name' => __('Fystory Item')
            ],
            'public' => true,
            'has_archive' => true,
            'supports' => ['title'],
            'register_meta_box_cb' => [FyStories::class, 'container_item_meta_box']
        ]);

        add_action('admin_enqueue_scripts', [Fystories::class, 'add_media_uploader']);
        add_action('admin_enqueue_scripts', [Fystories::class, 'custom_mediaUpload']);
    }
    public static function container_meta_box()
    {
        add_meta_box('fy_container_meta_box_id', __('Fystory', 'textdomain'), [FyStories::class, 'fystory_container_metadata_html']);
    }
    public static function container_item_meta_box()
    {
        add_meta_box('fy_container_item_meta_box_id', __('Fystory item', 'textdomain'), [FyStories::class, 'fystory_container_item_metadata_html']);
        add_action('admin_enqueue_scripts', [FyStories::class, 'add_media_uploader']);
    }
    public static function fystory_container_metadata_html()
    {
        $args = [
            'post_type' => 'fystory_item',
            'post_status' => 'publish',
            'order' => 'DESC',
            'orderby' => 'title'
        ];
        $fy_items_query = new WP_Query($args);
        if ($fy_items_query->have_posts()) {
            $form = '<form>';
            while ($fy_items_query->have_posts()) {
                $fy_items_query->the_post();
                $form .= '<label for ="' . $carousel_items_id . '">' . get_the_title() . '</label>';
                $form .= '<input id="' . $carousel_items_id . '" type="checkbox" value="' . $carousel_items_id . '">' . '<br>';
            }
            $form .= '</form>';
            return print $form;
        } else {
            print('go make items first then come back for more settings');
        }
        add_action('add_meta_boxes', [FyStories::class, 'container_meta_box']);
    }
    public static function fystory_container_item_metadata_html()
    {
        $form_content = '<label for="media"></label>
        <img src="" id="img_placeholder">
        <video src="" id="vid_placeholder" style="display:none"></video>
        <input name="media" type="hidden" id="media_field">
        <input name="media" type="file" id="media_field" value="Select Media">';
        $form = '<form method="post">';
        echo $form_content;
        $form .= '</form>';
        add_action('add_meta_boxes', [FyStories::class, 'container_item_meta_box']);
    }
}
$fystory = new FyStories();
$fystory::register_static_files();
register_activation_hook(__FILE__, [$fystory, 'activate']);
register_deactivation_hook(__FILE__, [$fystory, 'deactivate']);

my js file

var media_field=document.querySelector('input[name="media"]');
var imgPlaceholder=document.getElementById('img_placeholder');
var videoPlaceholder=document.getElementById('vid_placeholder');
var media_Uploader=wp.media({
    title:'Select a Media',
    button:{
        text:'Done'
    },
    multiple:false
});
media_field.addEventListener('click',()=>{
    console.log('hey there');
    media_Uploader.open();
});
// console.log('ha');

the tree directory

.
├── ./Carousel
│   ├── ./Carousel/static
│   │   ├── ./Carousel/static/css
│   │   ├── ./Carousel/static/js
│   │   └── ./Carousel/static/Stories pour le site web
│   └── ./Carousel/template
└── ./failed attempsts

the js get’s enqueued to the page i checked the console it says wp.media not defined , but it’s like that what should i expect if i was developing local

i wanna achieve the functionality of when i click on upload a file i wanna get the media library to pick which media i need (either an image or a video)

i followed this guy for reference
https://www.youtube.com/watch?v=ohAHU0gm6vQ
and checked this answer didn’t help
WordPress upload media using Backbone JS Client

i am reading throught the provided docs of wordpress
https://codex.wordpress.org/Javascript_Reference/wp.media
but didn’t solved my problem

i’ll appreciate your help

Creating invoice pdf within ZUGFeRD xml embeded on MERN project

I am trying to create an invoice pdf with ZUGFeRD format on my site.
After customer placing his order, the order information should be saved in ZUGFeRD xml file and then create invoice pdf file which has the xml file as an attachment.
The project is built with MERN stack.
I tried to find solutions online but there we only JAVA and C# built-in libraries.
Is there any library for javascript projects to handle ZUGFeRD invoicing?
If it needs to be built from the ground up, which steps should be needed?

Thank you for your advice!

Register page with Sveltekit + MongoDB but it keeps saying my inputs are null

Making a register page with MongoDB but it keeps saying my inputs are null. This is my first time doing backend stuff with Sveltekit and I’m a bit lost. I modified this tutorial -https://stackoverflow.com/questions/69066169/how-to-implement-cookie-authentication-sveltekit-mongodb – and fixed the breaking changes but am still left with this null problem. I’ve also tried using e.target.value instead of bind but same thing. I’m pretty sure this problem is from register.svelte, not register.js or sitedb.js. If anyone has done anything similar please let me know, your help is appreciated. Code below:

//register.svelte
<script lang="ts">
    import { createEventDispatcher } from 'svelte';

    // register function
    // Dispatcher for future usage in /index.svelte
    const dispatch = createEventDispatcher();

    // Variables bound to respective inputs via bind:value
    let email;
    let password;
    let error;

    const register = async () => {
        // Reset error from previous failed attempts
        error = undefined;

        try {
            // POST method to src/routes/auth/register.js endpoint
            const res = await fetch('/auth/register', {
                method: 'POST',
                body: JSON.stringify({
                    email,
                    password
                }),
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (res.ok) {
                dispatch('success');
            } else {
                error = 'An error occured';
            }
        } catch (err) {
            console.log(err);
            error = 'An error occured';
        }
    };
</script>

<input type="email" name="email" bind:value={email}>
<input type="password" name="password" bind:value={password}>
    
{#if error}
   <p>{error}</p>
{/if}

<button on:click={register}>Register</button>

Loading JS Library from CDN in Web worker created from Chrome exension

So I’m trying to create a chrome extension that uses the Fuse.js library through a web worker (https://cdn.jsdelivr.net/npm/[email protected], web worker is loaded through a .js file in the extension’s code.). In order to do this I’m using the importScripts function e.g. importScripts("https://cdn.jsdelivr.net/npm/[email protected]")

Initially this threw the error:

Refused to load the script 'https://cdn.jsdelivr.net/npm/[email protected]' because it violates the following Content Security Policy directive: "script-src 'self' 'wasm-unsafe-eval'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback.

To solve this I’ve tried several variations of manifest.json CSP changes but can’t seem to be able to get it to work. Here is my most recent attempt (going completely overkill adding everything I can think of)

 "content_security_policy": {
        "extension_pages": "script-src 'self'; object-src 'self'; script-src-elem 'self' 'unsafe-inline' https://cdn.jsdelivr.net/npm/[email protected] https://cdn.jsdelivr.net/npm/[email protected]/; default-src 'self' 'unsafe-inline' https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap https://cdn.jsdelivr.net/npm/[email protected] https://cdn.jsdelivr.net/npm/[email protected]/;",
        "worker-src": "unsafe-inline https://cdn.jsdelivr.net/npm/[email protected];"
    }

While it’s easy enough to change to be able to load the content from CDN within the extension itself, loading it from the web worker seems to be different. Perhaps this may be an unsupported approach, and in that case I’d welcome any recommendations for advice!

Currently another idea of mine would be to load the library to a content script, then have that spawn the web worker, then pass the result of that back to the extension, however this seems like a less elegant approach.

This isn’t my area of expertise so would appreciate any help! Thanks.

How to do an image-slider with autoplay ? Using Javascript and JQuery

I’ve been trying to figure out how to autoplay the images that I configured in the manual form and I’d like the autoplay works at the same way as the manual. Is it possible? I tried so many times ):
I can not understand why my text, bullets (dots) and images doesn’t work automatically and properly.

Anyone ?

I will let the codepen here too, cause the code and design is to extensive
[https://codepen.io/thyaladias/pen/KKowVPo]

here is part of my HTML

<div class="carousel">
              <div class="images-wrapper">
                <img src="images/1.abstract.png" class="image img-1 show" alt="">
                <img src="images/2.abstract.png" class="image img-2" alt="">
                <img src="images/3.abstract.png" class="image img-3" alt="">
              </div>

              <div class="texto-slider">
                <div class="text-wrap">
                  <div class="container-texto">
                    <h2>Create your own courses</h2>
                    <h2>Customize as you like</h2>
                    <h2>Invite students to your class</h2>
                  </div>
                </div>

                <div class="bullets">
                  <span class="active" data-value="1"></span>
                  <span data-value="2"></span>
                  <span data-value="3"></span>
                </div>
              </div>
     </div>

the css :

.carousel {
  position: absolute;
  height: 100%;
  width: 55%;
  left: 45%;
  top: 0;
  background-color: #f5e4d9;
  border-radius: 2rem;
  grid-template-rows: auto 1fr;
  padding-bottom: 2rem;
  overflow: hidden;
  transition: 0.8s ease-in-out;
}

.images-wrapper {
  display: grid;
  grid-template-columns: 1fr;
  grid-template-rows: 1fr;
}

.images-wrapper h2 {
  margin-top: 20px;
  align-items: center;
  justify-content: center;
  max-height: 2.2rem;
  overflow: hidden;
  margin-bottom: 1rem;
  text-align: center;
}


.image {
  width: 60%;
  margin: auto;
  padding-top: 30px;
  grid-column: 1/2;
  grid-row: 1/2;
  opacity: 0;
  transition: opacity 0.3s, transform 0.5s;
}

.img-1
{
  align-items: center;
  justify-content: center;
  transform: translate(0, -50px);
}

.img-2 {
  transform: scale(0.4, 0.5);
}

.img-3 {
  transform: scale(0.3) rotate(-20deg);
}

.image.show {
  text-align: center;
  opacity: 1;
  transform: none;
}

.texto-slider {
  margin-top: 20px;
  align-items: center;
  justify-content: center;

}

.text-wrap {
  max-height: 2.2rem;
  overflow: hidden;
  margin-bottom: 1rem;
  text-align: center;
}

.container-texto {
  display: flex;
  flex-direction: column;
  text-align: center;
  transform: translateY(0);
  transition: 0.5s;
}

.container-texto h2 {
  line-height: 2.2rem;
  font-weight: 600;
  font-size: 1.6rem;
}

.bullets {
  display: inline-block;
  align-items: center;
  justify-content: center;
}

.bullets span {
  width: 0.5rem;
  height: 0.5rem;
  background-color: #aaa;
  margin: 0 0.25rem;
  border-radius: 50%;
  cursor: pointer;
  transition: 0.3s;
  display: inline-block;
}

.bullets span.active {
  width: 1.1rem;
  background-color: #151111;
  border-radius: 1rem;
  z-index: 5;
  transition: 0.3s
}

and JS:

const inputs = document.querySelectorAll(".campo-input"); 
const toggle_btn = document.querySelectorAll(".toggle"); 
const main = document.querySelector("main");
const bullets = document.querySelectorAll(".bullets span");
const images = document.querySelectorAll(".image");

inputs.forEach((inp) => {
  inp.addEventListener("focus", () => {
    inp.classList.add("active");
  });
  inp.addEventListener("blur", () => {
    if (inp.value != "") return;
    inp.classList.remove("active");
  });
});

toggle_btn.forEach((btn) => {
  btn.addEventListener("click", () => {
    main.classList.toggle("sign-up-mode");
  });
});


function moveSlider() {
  let index = this.dataset.value;

  let currentImage = document.querySelector(`.img-${index}`);
  images.forEach((img) => img.classList.remove("show"));
  currentImage.classList.add("show");

  const textSlider = document.querySelector(".container-texto");
  textSlider.style.transform = `translateY(${-(index - 1) * 2.2}rem)`;

  bullets.forEach((bull) => bull.classList.remove("active"));
  this.classList.add("active");
}

bullets.forEach((bullet) => {
  bullet.addEventListener("click", moveSlider);
});


$(document).ready(function () { 
  $('.carousel > img:gt(0)').hide();

  setInterval(() => {
      $('.carousel > img:first')
          .fadeOut(1000) 
          .next() 
          .fadeIn(1000) 
          .end()
          .appendTo('.carousel') 
  }, 3000);  

})