Find Asp.net Web Forms control in script in Js (JavaScript) file

I have the following script in a Web Forms project:

function myScriptInAspxFile() {
         var obj = document.getElementById("<%= TextBox1.ClientID %>");
         if (obj) {                 
             obj.value = "My Text";                 
         }
     }

this works fine when I put the script inside the Web forms aspx file, but when I change the script to a Js (JavaScript) file the line:

var obj = document.getElementById("<%= TextBox1.ClientID %>");

The assignment returns me a null value for the obj variable. How could I find a control from a script in a Js (JavaScript) file? Greetings and thank you in advance.

Sveltekit on change function not being called when added to a component

I’ve got the following component called NumericField:

<script>
    import {isNumber} from "../../helpers/index.js";
    import {onMount} from "svelte";

    export let name;
    export let id;
    export let value;
    export let readOnly=false;
    export let disabled=false; // use disabled so we don't submit the value.
    export let styleClass="input w-full py-4 font-medium bg-gray-100 border-gray-200 text-smn" +
        "                                  focus:outline-none focus:border-gray-400 focus:bg-white";


    onMount(() => {
        // if a value is provided for the field then format it and place it in it.
        if (value !== null && value !== undefined) {
            value = formatNumber(value);
            return;
        }

        // if a value was not provided or is not a valid numeric field then set the field value to empty.
        value="";
    });

    const formatNumber = e => {

        // on keyup validate if the value is "", if so return. This is to avoid placing a NaN on the field.
        if (e.target?.value == "") {
            return
        }

        if (parseInt(String(e).replace(/,/g,'')) === NaN) {
            e.target.value = "";
            return
        }

        // if e is not an event (event is of type object) but a number (this will apply for on edit mode or read only fields).
        if (typeof e !== 'object' && (isNumber(e) || isNumber(parseInt(e)))) {
            console.log("not an event. value = ", e)
            // remove all commas (,) from the number and return it.
            return parseInt(String(e).replace(/,/g,'')).toLocaleString("en-US");
        }

        // reformat the given number by adding commas to it but since this is recalculated on the fly first we
        // have to remove any existing commas.
        e.target.value = parseInt(e.target.value.replace(/,/g,'')).toLocaleString("en-US");
    }


</script>

<input
        id={id}
        on:keyup={formatNumber}
        name={name}
        readonly={readOnly}
        disabled={disabled}
        type="text"
        bind:value
        class={styleClass}
    />

And I’ve got a form in which I’m using the component:

<NumericField
                            on:change={updateTotal}
                            bind:purchasedPrice
                            id="purchasedPrice"
                            name="purchased_price"
                    />

I’m calling updateTotal to calculate the total based on the value inputed in the component, but my function is never called:

const updateTotal = () => {
        console.log("here in updateTotal")
    }

what am I doing wrong?

Thanks

Assistance with codes [closed]

I m new and this world is totally unknown for me. I need help with reading I guess on some computer codes that I have.

Im not even sure how to explain but its conected to something – arrays stringw, json, node something…

Im totally out of that computer stuff world but ill attach some part of what I need help.

If someone is willing message me. Picture
(https://i.stack.imgur.com/2AcIJ.jpg)

Im not sure where to get help or what I should look.for

Create new array using values from another array

I’ve simplified the below array to prevent confusion. Here’s my progress up to now… I’ve attempted various methods to generate a fresh array, but haven’t succeeded yet. I’ve even scoured Stack Overflow for solutions. The result is accurate, but unfortunately, I’m only receiving a single object in the fieldsArray. I believe I’m close to the solution with my current approach. Any assistance you can offer would be greatly appreciated. Thank you.

I have the following array.

[
    {
        fileName: 'Home_AIT_Spraying-1_29062023.agdata',
        fileType: 'AgData',
        metadata: {
            tags: [
                {
                    type: 'Field',
                    value: 'Home',
                    uniqueId: null,
                },
                {
                    type: 'Farm',
                    value: 'OTF',
                    uniqueId: null,
                },
                {
                    type: 'Grower',
                    value: 'Jim Smith',
                    uniqueId: null,
                }
            ],
        },
    },
    {
        fileName: 'AIT_AIT_Spraying-1_30062023.agdata',
        fileType: 'AgData',
        metadata: {
            tags: [
                {
                    type: 'Field',
                    value: 'Oscar',
                    uniqueId: null,
                },
                {
                    type: 'Farm',
                    value: 'OTF',
                    uniqueId: null,
                },
                {
                    type: 'Grower',
                    value: 'Jasper Jones',
                    uniqueId: null,
                }
            ],
        },
    }
]

I’d like the output to look like the following:

[
    {
        Field: 'AIT',
        Farm: 'OTF',
        Grower: 'Jim Smith',
    },
    {
        Field: 'Oscar',
        Farm: 'OTF',
        Grower: 'Jasper Jones',
    },
];

And my current solution:

const fieldsMetaArray = [] as [];

data.forEach((val, key) => {
    console.log('key', key);
    val.metadata.tags.map((tag) => {
        console.log(`key: ${tag.type} value: ${tag.value}`);
        fieldsMetaArray[tag.type] = tag.value;
    });
});

console.log(fieldsArray);

Trouble with and framework materialize

I’m trying to learn how to use the materialize framework (it’s for a uni assignment) I have added the framework to my project but it seems that the framework has somehow vanished the <select>, why this is happening?

here is my code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Inscripción en línea</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <!--Import Google Icon Font-->
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <!--Import materialize.css-->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!--Let browser know website is optimized for mobile-->
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

    <script>
        $(document).ready(function(){
            $("#nivel").on("change", function(){
                var nivel = $(this).val();
                crearListaCarreras(nivel);
            });
        });

        var oferta = {
            'lic_e':['Administración y Dirección de Empresas', 'Derecho', 'Comunicación y Entornos Digitales', 'Ingeniería en Sistemas Computacionales', 'Psicología'],
            'lic_m':['Administración', 'Derecho', 'Ingeniería Industrial', 'Informática'],
            'mae_e':['Administración y Gestión de Instituciones Educativas', 'Derecho Fiscal', 'Derecho Privado', 'Redes y Telecomunicaciones', 'Impuestos'],
            'doc_e':['Ciencias Administrativas', 'Derecho', 'Ingeniería en Tecnologías Emergentes', 'Educación']
        };

        function crearListaCarreras(nivel){
            var carreras = $("#carrera").empty().append($("<option value=''>Seleccione una opción</option>"));
            if(nivel !== ""){
                var lista_carreras = [];
                var costo = 0;
                switch(nivel){
                    case 'lic_e': lista_carreras = oferta.lic_e; costo = 1500; break;
                    case 'lic_m': lista_carreras = oferta.lic_m; costo = 2500; break;
                    case 'mae_e': lista_carreras = oferta.mae_e; costo = 3000; break;
                    case 'doc_e': lista_carreras = oferta.doc_e; costo = 3500; break;
                }

                if(lista_carreras.length > 0){
                    $.each(lista_carreras, function(k,v){
                        carreras.append(
                            $("<option>").text(v)
                        )
                    });

                    $("#costo").val(costo);
                }
            }
        }
    </script>
</head>
<body>
<div class="container">
<img src="https://servicios.ver.ucc.mx/icecc/img/logo_ucc_transparente.png" style="background:#002449"/>
<h1>Inscripción en línea</h1>
<h3>Ingreso</h3>
Nivel<br>

<select id="nivel">
    <option value="">Seleccione una opción</option>
    <option value="lic_e">Licenciatura escolarizada</option>
    <option value="lic_m">Licenciatura mixta</option>
    <option value="mae_e">Maestría</option>
    <option value="doc_e">Doctorado</option>
</select><br>

Carrera<br>
<select id="carrera">
    <option value="">Seleccione una opción</option>
</select>

<h3>Datos personales</h3>
C.U.R.P<br />
<input type="text" /><br>

Nombre<br />
<input type="text" /><br>

Apellidos<br />
<input type="text" /><br>

E-mail<br />
<input type="text" /><br>

Celular<br />
<input type="text" /><br>

Teléfono<br />
<input type="text" /><br>

Escuela de procedencia<br />
<input type="text" />

<h3>Información de pago</h3>
Total a pagar<br />
<input type="text" id="costo" readonly/><br>

Método de pago<br />
<input type="checkbox" /> depósito referenciado<br>
<input type="checkbox" /> tarjeta de crédito o débito<br>
<input type="checkbox" /> en cajas de la UCC<br>

<input type="button" value="Enviar"/>
    </div>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>

</body>
</html>

I have tried to read the documentation but it has prove unhelpful.

Select value within form select

I want to create a form field with select, that shows additional fields when a certain field is selected.

<div class="col-md-12">
                      <label for="event" class="form-label"
                        >Habt ihr schon nähere Infos zu eurem Event</label
                      >
                      <select id="event" class="form-select">
                        <option
                          value="choose"
                          selected
                          aria-label="Disabled select example"
                          disabled
                        >
                          Bitte auswählen
                        </option>
                        <option value="no">Nein</option>
                        <option value="yes">Ja</option>
                      </select>
                    </div>

                    <div class="col col-md-4 extended">
                      <label for="eventtype" class="form-label"
                        >Art der Veranstaltung</label
                      >
                      <input type="text" class="form-control" id="eventtype" />
                    </div>
                    <div class="col col-md-4 extended">
                      <label for="guests" class="form-label"
                        >Anzahl Gäste</label
                      >
                      <select id="guests" class="form-select">
                        <option
                          selected
                          aria-label="Disabled select example"
                          disabled
                        >
                          Bitte auswählen
                        </option>
                        <option>30 - 100</option>
                        <option>100 - 200</option>
                        <option>mehr als 200</option>
                      </select>
                    </div>
                    <div class="col col-md-4 extended">
                      <label for="duration" class="form-label"
                        >Auftrittsdauer</label
                      >
                      <input type="text" class="form-control" id="duration" />
                    </div>
                    <div class="col col-md-6 extended">
                      <label for="place" class="form-label">Ort</label>
                      <input type="text" class="form-control" id="place" />
                    </div>
                    <div class="col col-md-6 extended">
                      <label for="date" class="form-label">Datum</label>
                      <input type="date" class="form-control" id="date" />
                    </div>

All the divs with the class “.extended” should hide, when “Nein” is selected.

I wrote that JavaScript but somehow, the selValue always only gives back the value of “choose”

var Extended = document.querySelectorAll(".extended")
var selObj = document.getElementById("event");
var selValue = selObj.options[selObj.selectedIndex].value;

  console.log(selValue)

if (selValue === "no") {
Extended.forEach(el=>el.classList.add("visually-hidden"));
}

I read certain posts, how to get values from select and this is what I found, but somehow it doesn’t work.
I would appreciate any help, that shows me, where my mistake is.

How to make parallax image with locomotive scroll?

I have two images

enter image description here

I want to achieve the same effect as on this site: https://evm.elektramontreal.ca/en/about
That is, the parallax of the image. The images themselves should remain in place, but parallax occurs when scrolling. When I add the data-scroll data-scroll-speed=”-5″ img tag, it “goes” to the top and no parallax occurs

Code:

            <div class="intro__bottom grid">
                <span class="intro__brief">
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
                </span>
                <div class="intro__images"> 
                    <div class="intro__image">
                        <img src="one.webp" alt="First intro image">
                    </div>
                    <div class="intro__image">
                        <img src="two.webp" alt="Second intro image">
                    </div>
                </div>
            </div>
.intro__images {
    display: flex;
    column-gap: 20px;
    grid-area: 1 / 6 / 1 / 11;
    height: 533px;
}

.intro__image {
    width: 100%;
}

.intro__image > img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
}

I’ve tried swapping out data-scroll, creating div containers

WebGL on Android unable to render texture due to possible rounding issue

I’m currently working on WebGL to do number of post processing to 2d image. The Problem arises when I try to use copyTexImage2D API to send my initial texture to fragment shader with using device’s display dimensions, it resulting with solid black texture unless I artificially add any positive number that greater than one which leads to me believe issue came from some kind of rounding problem. The interesting part of the issue it’s exclusive to Android platform and won’t reproduced in iOS, OSX, Windows platforms with across different browsers.

Here is snippet from my code that copies scene that came from MapLibre to renderTexture variable.

            // render-to-texture
            gl.bindTexture(gl.TEXTURE_2D, this.renderTexture!);
            let w = gl.canvas.width;
            let h = gl.canvas.height;
            gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, w, h, 0); // Solid black texture sent to fragment shader
           // gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, w + 1, h, 0); // Texture correctly sent to fragment shader 
           // gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, w + 1, h - 1, 0); // Also works vice versa
           // gl.copyTexImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 0, 0, w - 1, h, 0); // Doesn't work

            getDeviceDimensions();

            gl.useProgram(this.program!);

            gl.uniform1i(this.sharpenLoc!, this.sharpen ? 1 : 0);
            gl.uniform1i(this.lookupLoc!, this.lookup ? 1 : 0);
            gl.uniform1i(this.grainLoc!, this.grain ? 1 : 0);

            const { lat, lng } = map.getCenter();
            gl.uniform2f(this.mapCoordsLoc!, lat, lng);

            gl.uniform2f(this.resolutionLoc!, gl.canvas.width, gl.canvas.height);

            // Pass texture
            gl.activeTexture(gl.TEXTURE0);
            gl.bindTexture(gl.TEXTURE_2D, this.renderTexture!);
            gl.uniform1i(this.renderTexLoc!, 0);

            // Pass LUT
            gl.activeTexture(gl.TEXTURE1);
            gl.bindTexture(gl.TEXTURE_2D, this.lutTexture!);
            gl.uniform1i(this.lutTexLoc!, 1);

            gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);

Here is how I initialise the renderTexture

            this.renderTexture = gl.createTexture()!;
            gl.bindTexture(gl.TEXTURE_2D, this.renderTexture);
            gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.canvas.width, gl.canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
            gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);

Additional Context

  • Dimensions not always power of 2 but rounding them does not solve the issue
  • gl.canvas.width & gl.canvas.height dimensions matches with destination HTML element
  • Issue can be reproduced both WebGL 1 and WebGL 2 in Android
  • Using gl.viewPort to with additional one pixel size won’t effect the issue
  • In fragment shader texture(…) function returns black color when renderTexture used as an input

Device: Google Pixel 5

Resolution: 1080×2340, Scale Factor 2.75

Browser: Google Chrome 103.0.5060.71

jQuery .val() does NOT change value for one select element, but does change value for another select

I’m working on a time submission application for contractors that work on special projects. I have two select elements, projectSelect and payPeriodSelect.

I use JavaScript promise chains to retrieve and load projects and pay periods. The pay period select is populated with options once a project is selected in the project select.

After the user clicks Submit, I save the time entries to the database and update the select option highlight colors, based on the timesheet status (green for approved, red for rejected, gray for submitted). I need to refresh the project and pay period select option lists so that the options are highlighted with the proper color.

In order to do this, I need to call getProjects() and getPayPeriods() again, and programmatically change the value of projectSelect and payPeriodSelect. I am able to change the value of payPeriodSelect with jQuery’s .val() function. However, projectSelect value is set to null when I used the same method. Why does it work for one select but not the other?

The select elements are defined like this:

<select id='projectSelect' class="form-select"></select>
<select id='payPeriodSelect' class="form-select"></select>

The promise chain to load projects gets called when the page first loads:

getProjects()
    .then(data => {
        return loadProjects(data);
    })
    .then(data => {
        $('#projectSelect').change();    // select the default project to display (1st option in list)
    })
    .catch(error => {
        // display error in modal
    });

function loadProjects(projectData) {
    return new Promise((resolve, reject) => {
  
        let select = document.getElementById("projectSelect");
        select.length = 0;
    
        projectData.reduce((previousPromise, project) => {        // map each project object in the array to a new promise
                

                return previousPromise
                    .then(x => getPayPeriods(project.id))
                    .then(payPeriods => {
                        let option = document.createElement("option")

                        if (payPeriods.length) {
                            // if all timesheets for the project have been approved, change highlight color of option to green
                            if (payPeriods.every(payPeriod => payPeriod.approvalStatus)) {
                                option.setAttribute('class', 'approvedColor')
                            }
                            // If all timesheets are rejected, change color to red
                            else if (payPeriods.every(payPeriod => payPeriod.rejectionStatus)) {
                                option.setAttribute('class', 'rejectedColor')
                            }
                            // if all timesheets are submitted, change color to gray
                            else if (payPeriods.every(payPeriod => payPeriod.submissionStatus)) {
                                option.setAttribute('class', 'submittedColor')
                            } 
                        }

                        option.text = project.code + ' - ' + project.name  
                        option.value = project.id
                        select.appendChild(option)

                        select.value = select.options[0].value    // set 1st option's project ID as default value
                        
                        return resolve(true)
                    })     
                    .catch(error => {
                        return reject(error)
                    })
            }, Promise.resolve())       // Promise.resolve() is the initial promise function that starts the chain

        return resolve(true);
    })
}

The change event for the projectSelect and the load pay period functions is shown below:

$('#projectSelect').on('change', function (e) {
    
    $('tr').find("input.timeBox").val("")       // clear timesheet inputs

    let projectId = this.value

    getPayPeriods(projectId)
        .then(data => {
            return loadPayPeriods(data)
        })
        .then(x => {
            $('#payPeriodSelect').trigger('change')
        })
        .catch(error => {
               
        })
})

function loadPayPeriods(data) {
    return new Promise((resolve, reject)=>{

        var select = document.getElementById("payPeriodSelect")
        select.length = 0

        if (!data.length) {
            $('#payPeriodSelect').attr('disabled', true)
            return reject(false)
        }

        // enable dropdown if there are pay periods to load into it
        $('#payPeriodSelect').attr('disabled', false)

        for (let payPeriod of data) {

            let option = document.createElement("option")
            option.text = payPeriod.start_d + ' - ' + payPeriod.end_d
            option.value = payPeriod.start_d + '|' + payPeriod.end_d

            // change pay period option highlight colors based on timesheet status
            if (payPeriod.approval_d) {
                option.setAttribute('class', 'approved')
            } else if (payPeriod.rejection_d) {
                option.setAttribute('class', 'rejected')
            } else if (payPeriod.submission_d) {
                option.setAttribute('class', 'submitted')
            }

            select.appendChild(option) 
        }

        select.value = select.options[0].value
        return resolve(true)
    })     
}

The payPeriodSelect change event:


    $('#payPeriodSelect').on('change', function (e) {
   

                    // get and populate timesheet data for the selected pay period
                    getTimeData(this.value)
                        .then(data=> {
                            return loadTimeData(data)
                        })
                        .then(data => {

                            if (data) {
                                let payPeriodSelect = document.getElementById('payPeriodSelect')

                            
                                if (data.approvalStatus) {
                                    payPeriodSelect.options[payPeriodSelect.selectedIndex].setAttribute('class', 'approvedColor')
                                } else if (data.rejectionStatus) {
                                    payPeriodSelect.options[payPeriodSelect.selectedIndex].setAttribute('class', 'rejectedColor')
                                } else if (data.submissionStatus) {
                                    payPeriodSelect.options[payPeriodSelect.selectedIndex].setAttribute('class', 'submittedColor')
                                }
                            }
   
                        })
                        .then(x => {
                            return calculateTotalTime()
                        })
                        .catch(error => {
          
                        })
                })

The function for submitting time. I get and load projects, and change the values for both select elements. projectSelect value is set to null while payPeriodSelect value is set to the correct value.

$('#submitTol').on('click', function (e) {
    return saveDataToDatabase()
        .then(data => {
            return getProjects()
        })
        .then(data => {
            return loadProjects(data)
        })
        .then(x => {
            return new Promise((resolve, reject) => {
                    $('#projectSelect').val(project.id).change()
                    return resolve(true)
                })
        })
        .then(x => {
            return new Promise((resolve, reject) => {
                    $('#payPeriodSelect').val( payPeriod.start_d + '-' + payPeriod.end_d).change()
                    return resolve(true)
                })
        }
}

Sorry for the heap of code, but I wanted to give some context about how I retrieve and display data in the select elements. I am so confused as to why changing payPeriodSelect‘s value works, but not projectSelect.

Error: Operation `bootcamps.insertOne()` buffering timed out after 10000ms

I am having an issue inserting a document into MongoDB. I am able to successfully connect to the database, but when i try to insert a new document i get the following error:

Error: Operation `bootcamps.insertOne()` buffering timed out after 10000ms
[nodemon] app crashed - waiting for file changes before starting...

URI Connection string:

MONGO_URI=mongodb+srv://blahblah:<password>@cluster0.ohppr.mongodb.net/devcamper?retryWrites=true&w=majority&appName=Cluster0

db.js

const mongoose = require('mongoose')

const connectDB = async () => {
  const conn = await mongoose.connect(process.env.MONGO_URI)

  console.log(`MongoDB Connected: ${conn.connection.host}`.cyan.underline.bold)
}

module.exports = connectDB

MongoDB Network:

enter image description here

server.js

const express = require('express')
const dotenv = require('dotenv')
const connectDB = require('./config/db')

// Load env variables.
dotenv.config({ path: './config/config.env' })

// Connect to DB
connectDB()

bootcamp.js

const Bootcamp = require('../models/Bootcamps')

// @desc    Create new bootcamp
// @route   POST /api/v1/bootcamps
// @access  Private
exports.createBootcamp = async (req, res, next) => {
  //console.log(req.body)
  //res.status(201).json({success: true})
  const bootcamp = await Bootcamp.create(req.body);
  res.status(201).json({
  sucess: true,
  data: bootcamp
  })
}

if i comment out the following lines of code everything runs ok.

const bootcamp = await Bootcamp.create(req.body);
  res.status(201).json({
  sucess: true,
  data: bootcamp
  })
}

Postman

enter image description here

JavaScript fetch() unable to set Content-Type header to “application/json”

Currently attempting to fetch some JSON to an API. I am testing my fetch requests using requestcatcher.com. Here is an example, which highlights the problem I am having:

fetch("https://example.requestcatcher.com",
{
    method: "POST",
    mode: "no-cors",
    headers: new Headers({ "Accept":"application/json", "Content-Type":"application/json" }),
    body: "{}"
});

Upon sending this request, I expected the request catcher API to receive the header Content-Type: application/json. However, this is not happening – the Content-Type keeps getting reset to text/plain;charset=UTF-8. This happens whether I pass in a Headers object or simply an Object. The Content-Type is also the only header to be modified in this way – the Accept header doesn’t suffer this issue.

Interestingly, this substitution doesn’t happen if I pass in Content-Type: application/x-www-form-urlencoded: that header, unlike application/json, is received unaltered by the request catcher. It seems to have an unique problem with application/json. I’ve seen no successful explanation online regarding why this would happen – if anyone is able to shed some light on this I would be much grateful.

How to modify Hide/Show button for class instead of ID

I have found this code for a hide/show ID effect. I am building with Elementor in WP.

<button onclick="myFunction()">show / hide</button>
function myFunction() {
  var x = document.getElementById ("showprice");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
} 

This works, but I would like to modify the code to hide/show a Class instead of ID – but changing it to the following doesn’t work. Any tips?

function myFunction() {
  var x = document.getElementsByClassName("showprice");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
} 

How to convert a uploaded CSV file to UFT-8 with “;” delimiter?

I have an importer that is supposed to upload a special file from a third-party program. The file is structured as follows:

TITLE,DESCRIPTION,PRICE,CURRENCY_CODE,QUANTITY,TAGS
"This is the file title","This is the file description and it can include line breaks

Size: 16x16
Weight: 1,5
for example here

more information.",12.99,USD,10,"Tag1,Tag2,Tag3"
"Next line","This is the file description and it can include line breaks

Size: 16x16
Weight: 1,5
for example here

more information.",12.99,USD,10,"Tag1,Tag2,Tag3"
"Next line","This is the file description and it can include line breaks

Size: 16x16
Weight: 1,5
for example here

more information.",12.99,USD,10,"Tag1,Tag2,Tag3"

I am trying to read this file line by line, which unfortunately does not work in JS.

    const reader = new FileReader();
    reader.onload = async (evt) => {
        const file = evt.target.result.split('rn')

When I open the file in Numbers (Mac = Excel) and save via File > Export > CSV > Text encoding Unicode (UTF-8), the file is spit out as follows:

TITLE;DESCRIPTION;PRICE;CURRENCY_CODE;QUANTITY;TAGS
"This is the file title";"This is the file description and it can include line breaks

Size: 16x16
Weight: 1,5
for example here

more information.";12.99;USD;10;"Tag1;Tag2;Tag3"
"Next line";"This is the file description and it can include line breaks

Size: 16x16
Weight: 1,5
for example here

more information.";12.99;USD;10;"Tag1;Tag2;Tag3"
"Next line";"This is the file description and it can include line breaks

Size: 16x16
Weight: 1,5
for example here

more information.";12.99;USD;10;"Tag1;Tag2;Tag3"

I can work wonderfully with this file formatting. As i can see, all columns are now marked via ; and the line break evt.target.result.split('rn') works as well.

Unfortunately, I cannot assume that my users will be able to convert this file.

Therefore, I would like to convert the file as Numbers does when uploading it.

How does this work via JavaScript new FileReader() ?

why is my redux state null when accessing in another component?

So in my application I have a profile page which I have checked successfully sets the redux state with the profile data after dispatching when the page is loaded, I then try to access this state in another component within my app after a redirect (not a browser refresh) and using the useSelector hook but it tells me that the redux data in null and I cannot figure out why have I done something wrong in my reducers, component or store?

profileSlicer:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

export const fetchProfileByUsername = createAsyncThunk("profile/fetchByUsername", async (username) => {
    console.log("fetching by username in redux ")
    const response = await axios.get('http://localhost:3002/userProfile', {
        params: {
            username: username
        }
    });
    return response.data;
});

export const fetchProfileByQrId = createAsyncThunk("profile/fetchByQrId", async (qr_id) => {
    console.log("fetching by qr_id in redux ")
    //const response = await axios.get('https://lovinglegacy.onrender.com/getProfile', {
    const response = await axios.get('http://localhost:3002/getProfile', {
    params: {
            qr_id: qr_id
        }
    });
    return response.data;
});

const profileSlice = createSlice({
    name: 'profile',
    initialState: {
        isLoading: false,
        data: null,
        error: false,
    },
    reducers: {},
    extraReducers: (builder) => {
        builder
            .addCase(fetchProfileByUsername.pending, (state) => {
                state.isLoading = true;
            })
            .addCase(fetchProfileByUsername.fulfilled, (state, action) => {
                state.isLoading = false;
                state.data = action.payload;
            })
            .addCase(fetchProfileByUsername.rejected, (state) => {
                state.isLoading = false;
                state.error = true;
            })
            .addCase(fetchProfileByQrId.pending, (state) => {
                state.isLoading = true;
            })
            .addCase(fetchProfileByQrId.fulfilled, (state, action) => {
                state.isLoading = false;
                state.data = action.payload;
            })
            .addCase(fetchProfileByQrId.rejected, (state) => {
                state.isLoading = false;
                state.error = true;
            });
    }
});

export default profileSlice.reducer;

store:

import {configureStore} from '@reduxjs/toolkit';
import profileReducer from '../redux/ProfileSlicer';

export const store = configureStore({
    reducer: {
        profile: profileReducer,
    }
})

Component trying to access redux state in after it has been set:

import React, { useEffect } from "react";
import CreateNewMedallionProfile from "../../CreateMedallionProfile";
import { useSelector } from "react-redux";

const ProfileDetails = () => {
    const profileData = useSelector(state => state.profile.data);

    useEffect(() => {
        console.log("Profile data in profile details ", profileData);
    }, [profileData]); // Add profileData to dependency array to listen for changes

    const handleClick = () => {
        console.log("clicked profile data ", profileData);
    }

    // Render the component only if profileData exists
    if (!profileData) {
        return <div>Loading...</div>;
    }

    return (
        <div>
            <button onClick={handleClick}>Click</button>
            <CreateNewMedallionProfile />
        </div>
    );
}

export default ProfileDetails;

Snippet from where redux state is set component:

const profileData  = useSelector(state => state.profile.data);
  const dispatch = useDispatch();
  console.log("profile data from redux store = ", profileData);

 

  useEffect(() => {
    const username = localStorage.getItem('username');
    const qr_id = localStorage.getItem('qr_id');
    if(username) {
      console.log("username from local storage ")
      dispatch(fetchProfileByUsername(username));
      
    }
    else if(qr_id) {
      console.log("qr_id from local storage");
      dispatch(fetchProfileByQrId(qr_id));
    }
    // Dispatch action to fetch profile data only on page refresh
    
  }, [])

  // Effect to make GET request to sever function when profileData changes
  useEffect(() => {
    if(profileData) {
      // Extract the username from profileData
      const username = profileData.username;
      console.log("in here");
    

    // make a GET request to the server-side function
    const fetchData = async () => {
      try {
        const response = await axios.get(`http://localhost:3002/userProfile`, {
          params : {
            username: username
          }
        });
        console.log("Response from server: ", response.data);
        setMedallionProfile(response.data.medallionProfile); // store fetched data in the state
        // Handle the response data as needed here 
      } catch(error) {
        console.error('Error fetching data: ', error);
        // Rest of handling the error show error msg client side??
        }
      };
    fetchData() // Call the fetchData function
    }
  }, [profileData])   // dependancy to run the effect when ever profile data changes

Javascript not executing properly on wordpress site for guest related to encoding

I used elementor html box tool to inject a small calculator into a blog. The calculator has chinese character as javascript objects used for mapping. The calculator works fine when I’m logging but it does not when I’m in not logging in. I used console command and saw the chinese characters are not getting interpreted properly. It’s showing ASCII like

&#19985
&#20133

I made sure the encoding is set to utf-8.I tried different solution from Google and nothing seems to work.