jQuery to get childNodes of Select All input within div class container node

I want to get the span text value of all the childNodes within the container of the corresponding input if the Select All checkbox is selected.

My current code picks up the ‘span’.text() reference of each input label, however it will only log the label selected (childNodes (e.g. ‘7211’) if selected singularly, or the label of the Select All checkbox (e.g. ‘Accommodation and Food Services’). What I want is to get the labels for all the childNodes if the Select All label is selected. It has to reference the corresponding childNodes of the specific selectAll checkbox as there are multiple Select All elements.

var htmlObject = layerControl.getContainer().querySelectorAll('input');
$(htmlObject).on("change", function(e) {
  if ($(this).is(':checked'))
  console.log($(this).siblings('span').text());
})

enter image description here

I can reference the Select All input, and if equals true, iterate through the childNodes and grab the element text references. Something like this:

var htmlObject = layerControl.getContainer().querySelectorAll('input');
$(htmlObject).on("change", function(e) {
  if ($(this).is(':checked'))
  console.log($(this).siblings('span').text());
  selAll= ($(this).is('.leaflet-control-layers-selector.leaflet-layerstree-sel-all-checkbox:checked'))
  if (selAll == true) 
  $(this).each(function () { 
    var sthisVal = (this.checked ? $(this).val() : "")
    console.log(sthisVal)
  })
})

However, the childNodes are outside of the input class so this logs the value of ‘on’ for the SelectAll input checkbox. I have to reference it’s container or parentElement to cycle through the childNodes. The variable output will then log the text label.

Can anyone help me in fetching values from a csv file and substituting the values in the columns within a formula using javascript only?

I am writing a code for performing calculation of a formula on the basis of some constants and some values to be fetched from the CSV file. I would appreciate if anyone can help me solving the issue of fetching the values from the csv file and substituing them in the formula with simple javascript.

function loadFile(o){

window.onload = () => {
    //FILE READER + HTML ELEMENTS
        var reader = new FileReader(),
        picker = document.getElementById("picker"),
        table  = document.getElementById("table");

    //READ CSV ON FILE PICKER
        picker.onchange = () => reader.readAsText(picker.files[0]);

    //READ THE CSV FILE & GENERATE HTML
        reader.onload = () =>   {
        let csv = reader.result;

    // CLEAR HTML TABLE
    table.innerHTML = "";

    //SPLIT INTO ROWS
     let rows = csv.split("rn");

    //LOOP THROUGH ROWS + SPLIT COLUMNS
     for(let row of rows){
        let cols = row.match(/(?:"([^"]*(?:""[^"]*)*)")|([^",]+)/g);
        if (cols != null){
            let tr= table.insertRow();
            for (let col of cols) {
                let td = tr.insertCell();
                td.innerHTML = col.replace(/(^"|"$)/g, "");
            }
        }
        else {
            console.log("Error parsing CSV");
        }
    }


    function calculateCSV()
        { 
          var getCSVData = document.getElementById("picker").files[0];
          var values = getCSVData.FileReader;
          rows = getCSVData.split("n");
          var html = '<table border="1">';
      
          rows.forEach((data, index) => 
          {
              var value = data.split(",");
              var x_1 = values[0];
              var x_2 = values[1];
              var x_3 = values[2];
              let a,b,c,d,p1, p2, p3, p4;
              const e=2.71828; 

             if ( x_1 && x_2 ){
                     a=5.8;
                     b=0.02;
                     c=(-7.9);
                     d=0;
                     p1= 1/(1+e^(-(a+b*x_1+c*x_2+d*x_3)));
                     document.getElementById("result1").innerHTML =p1;                        
             }
             else if( x_2 && x_3 ){
                     a=4.5;
                     b=1.0;
                     c=(-6.4);
                     d=(-6.8);
                     p2= 1/(1+e^(-(a+b*x_1+c*x_2+d*x_3))); 
                     document.getElementById("result2").innerHTML =p2;                        
  
             }
             else if( x_1 && x_3 ){
                     a=0.7;
                     b=2.2;
                     c=(-0.02);
                     d=(-6.8);
                     p3= 1/(1+e^(-(a+b*x_1+c*x_2+d*x_3)));
                     document.getElementById("result3").innerHTML =p3;                        
  
             }
             else if( x_1 && x_2 && x_3 ){ 
                     a=4.6;
                     b=0.96;
                     c=0.02;
                     d=(-6.8);
                     p4= 1/(1+e^(-(a+b*x_1+c*x_2+d*x_3)));
                     document.getElementById("result4").innerHTML =p4;                        
  
                 
             }
             html += '</table>'; 
             html += '<span>' + p1 + '</span>';
             html += '<span>' + p2 + '</span>';
             html += '<span>' + p3 + '</span>';
             html += '<span>' + p4 + '</span>';
             document.getElementById("data").innerHTML = html;
             document.getElementById("data").style.color="blue";
            });
        }
    
} 
}
};

I am trying this and I want the values in th erespective columns of the csv file to be fetched and substituted by x_1,x_2,x_3 and x_4

Laravel jetstream livewire user dashboard header not found when logged in

i’m building a laravel application following a tutorial but ran into this problem @vite([‘resources/css/app.css’, ‘resources/js/app.js’]) which i solved using this solution provider here (JetStream CSS and JS not working and showing @vite([‘resources/css/app.css’, ‘resources/js/app.js’])) but when i login, the user dashboard header is not found and i can’t see logout button nor profile page. I’m running laravel 8.

I’m new to laravel…..Please can someone help me out.

How can I show a Leaflet map in a modal with the pin or marker centered, without it going to a single corner as shown in the image:

I am working on javascript, html and apps script and the Leaflet map, so how can I show a Leaflet map in a modal with the pin or marker centered, without going to a single corner as shown in the image, this only happens in a modal or in a secondary html, when it is the main html it is displayed correctly:

enter image description here

// Obtener la referencia al elemento del mapa
var mapa = L.map('mapa').setView([0, 0], 13);
mapa.doubleClickZoom.disable();
// Crear una capa de mapa con Leaflet
L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
  attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors',
  maxZoom: 18,
}).addTo(mapa);

// Crear un marcador con una ubicación predeterminada
var marcador = L.marker([0, 0]).addTo(mapa);

// Obtener la ubicación del usuario utilizando la API de geolocalización del navegador
navigator.geolocation.getCurrentPosition(function(posicion) {
  // Actualizar la ubicación del marcador y el centro del mapa con la ubicación del usuario
  marcador.setLatLng([posicion.coords.latitude, posicion.coords.longitude]);
  mapa.setView([posicion.coords.latitude, posicion.coords.longitude], 18);
}, function(error) {
  // En caso de error, mostrar un mensaje de error en la consola del navegador
  console.error('Error al obtener la ubicación: ' + error.message);
});

// Agregar un controlador de eventos de clic al mapa
mapa.on('click', function(evento) {
  // Actualizar la ubicación del marcador y el centro del mapa con la ubicación del clic
  marcador.setLatLng(evento.latlng);
  mapa.setView(evento.latlng, 18);
});
HTML: <div id="mapa" style="height: 200px;"></div>

next.js: How to wait for a first render to use document.getElementById()?

I have a script that accesses a canvas element by id. It is based on this tutorial. He uses plain JavaScript and explains his method at about 5:10. I extrapolated to next.js below.

import React, { useEffect } from 'react';

export default function Simulator() {
    useEffect(() => {
        var canvas = document.getElementById("myCanvas");
        var c = canvas.getContext("2d");

        //deleted for simplicity, but similar code to his is below...
        
    }, [])
    
    return (
        <div className="mt-10">
            <canvas id="myCanvas" className="border-2"></canvas>
        </div>
    )
}

This fails without useEffect–I believe because document.getElementById is run before the element is rendered. I found several solutions, including making a custom hook, but useEffect appears to be the most elegant.

Is this how react is meant to be used? Is this my if "__name__" == "__main__" from Python but to guard against running on first render? Is the custom hook the preferred method? Thank you for your insights in advance.

I Can’t Use Two Carousel in index.php

I have a carousel that I wrote below and it works fine. But when I take another copy of it, nothing shows on the screen:

and I Use splide.js lib

<div class="MySlider">
        <div class="title">
            <h1><?php echo get_theme_mod('landingpage_learnslider_title'); ?></h1>
            <h3><?php echo get_theme_mod('landingpage_learnslider_description'); ?></h3>
        </div>
        <div class="slider_wrapper">
            <div class="splide">
                <div class="splide__track">
                    <div class="splide__list">

                        <?php
                        $args = array(
                            'post_type' => 'my_carousel',
                            'posts_per_page' => 5,
                        );
                        $carousel_query = new WP_Query($args);

                        if ($carousel_query->have_posts()) :
                            while ($carousel_query->have_posts()) :
                                $carousel_query->the_post();
                        ?>
                                <div class="splide__slide">
                                    <div class="card">
                                        <img src="<?php echo get_field('post_image')['url']; ?>" alt="<?php echo get_field('alt_img'); ?>">
                                        <div class="main_text">
                                            <a href="<?php the_permalink(); ?>">
                                                <h1><?php the_title(); ?></h1>
                                            </a>
                                            <div class="author">
                                                <h2><i class="fa-solid fa-chalkboard-user"></i>
                                                    <?php echo get_field('Author'); ?> </h2>
                                            </div>
                                            <div class="text_child_box">
                                                <div class="text_child_rate">
                                                    <h3><?php echo get_field('price'); ?> $ </h3>
                                                    <div class="main_rate">
                                                        <?php
                                                        $rating = get_field('rating_stars');
                                                        for ($i = 1; $i <= 5; $i++) {
                                                            if ($i <= $rating) {
                                                                echo '<i class="fa-solid fa-star"></i>';
                                                            } else {
                                                                echo '<i class="fa-regular fa-star"></i>';
                                                            }
                                                        }
                                                        ?>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                        <?php
                            endwhile;
                            wp_reset_postdata();
                        else :
                            echo '<p>There is no content to display</p>';
                        endif;
                        ?>


                    </div>
                </div>
            </div>
        </div>

    </div>

To solve the problem in the first place, I changed the names and then I used other libraries, but they also face the problem in different ways. So I wrote it with vanilla javascript and it still has problems. I am completely stuck.

How to add typescript rules in NextJs Project without losing next/core-web-vitals?

I have a typescript NextJS project with the following .eslintrc.json:

{
    "extends": "next/core-web-vitals"
}

I would like to add some additional typescript rules (like do not allow the type any (no-explicit-any)).

  1. I added npm install --save-dev @typescript-eslint/parser @typescript-eslint/eslint-plugin
  2. Extend the config by the no-explicit-any rule, updated the parser and added the plugin.
{
    "extends": "next/core-web-vitals",
    "parser": "@typescript-eslint/parser",
    "plugins": [
        "@typescript-eslint"
    ],
    "rules": {
        "@typescript-eslint/no-explicit-any": "warn"
    }
}
  1. Now the no-explicit-any works. However all the default rules from the next/core-web-vitals are not working anymore.

So I can either have the next or use the typescript-eslint rules. How can I use booth?

Why does this throw a TypeError?

There is a task to find a middle of Linked List. Could you please explain why does fast.next in while() loop throw a “TypeError: Cannot read properties of null (reading ‘next’)”?

const middleNode = (head) => {
    let fast = head
    let slow = head

    if (head !== null) {
        while (fast.next !== null) {
            fast = fast.next.next
            slow = slow.next
        }
    }
    return slow
}

How to save user input, update array, and render updated array on button press

I have a react web application that I am developing. The code from the component in question renders semesters of a degree 2 at a time. The user is able to see each class in a semester. There are buttons to go to the next two semesters as well as the previous two semesters. There is also a button to view all semesters at once. This is where my problem lies. In the 2 semester view the user has the option to edit any class that contains ‘Elective’ or ‘Cognate’. There is also a save button under each semester to manage the changes made (the handleSave function does nothing yet). When I make a change in the 2 semester view and then click on the button to display all semesters, my changes are not being reflected.

I have tried creating state variables that are a copy of the splitArray array and then updating that through the handleSave function but it didnt work. I also know that in the 2 semester view a new ‘items’ array is created every time out of the splitArray array. The items[1] is the name of the class to be edited. So i have no idea how to create a copy of the splitArray array with the edited items[1] being in the correct place. The first paragraph (following the showAll? is rendered when the display all button is pressed). The second paragraph is the 2 semester view in which the user is able to make edits.

{showAll
              ? splitArray.map((item, index) => (
                  <li key={index} style={{ display: 'inline-block', marginRight: '10px' }}>
                    <p>Semester {index + 1}:</p>
                    <div className="semester-lines">
                      <div>
                        <p style={{ display: 'flex', flexDirection: 'column' }}>
                          {item
                            .replace(/],/g, ']<br/>')
                            .replace(/[[]]/g, '')
                            .split('<br/>')
                            .map((line, index) => {
                              const items = line.split(',').map(item => item.trim());
                              
                              return (
                                <div key={index} style={{ display: 'flex', justifyContent: 'space-between' }}>
                                  <span style={{ padding: '5px', margin: '5px', backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)' }}>
                                    {items[0]}
                                  </span>
                                  <span style={{ padding: '5px',maxWidth: '300px' ,margin: '5px', backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)' }}>
                                    {items[1]}
                                  </span>
                                  <span style={{ padding: '5px', margin: '5px', backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)', alignSelf: 'flex-end' }}>
                                    {items[2]}
                                  </span>
                                </div>
                              );
                            })}
                        </p>

                        
                      </div>
                    </div>
                  </li>
                ))


              : splitArray.slice(page, page + 2).map((item, index) => (
                  <li key={index} style={{ display: 'inline-block', marginRight: '10px' }}>
                    <p>Semester {index + 1 + page}:</p>
                    <div className="semester-lines">
                      <div>
                      <p style={{ display: 'flex', flexDirection: 'column' }}>
  {item
    .replace(/],/g, ']<br/>')
    .replace(/[[]]/g, '')
    .split('<br/>')
    .map((line, index) => {
      const items = line.split(',').map(item => item.trim());
      const isEditable = items[1].toLowerCase().includes('elective') || items[1].toLowerCase().includes('cognate');

      return (
        <div key={index} style={{ display: 'flex', justifyContent: 'space-between' }}>
          <span style={{ padding: '5px', margin: '5px', backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)', maxWidth: '100px', height: 'auto' }}>
            {items[0]}
          </span>
          {isEditable ? (
            <input
              type="text"
              defaultValue={items[1]}
              style={{ height: 'auto', minHeight: '40px', overflow: 'hidden', resize: 'none', padding: '5px', maxWidth: '300px', margin: '5px', color: 'white', backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)', textAlign: 'center' }}
              
              onChange={e => (items[1] = e.target.value)}
            />
          ) : (
            <span style={{height: 'auto',boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)', padding: '5px', maxWidth: '300px', margin: '5px', backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)' }}>
              {items[1]}
            </span>
          )}
          <span style={{ padding: '5px', margin: '5px',  backgroundColor: '#323232', boxShadow: '6px 6px 6px rgba(0, 0, 0, 0.30)', alignSelf: 'flex-end' }}>
            {items[2]}
          </span>
        </div>
      );
    })}
</p>


<button onClick={() => handleSave()}>
                  Save
                </button>
              </div>
            
          </div>
        </li>
      ))}
  </ul>

convert complex and nested json to table in excel using javascript

I am trying to convert a JSON in which some items can contains arrays as well. I get a very nicely structured table if I convert my JSON in json2table.com. I want similar table to be created in Excel using Javascript/nodejs. I tried some packages like ‘json2xls’, ‘xlsx’ etc. However I am not getting the desired output. Here’s my JSON.

JSON:

{
"name":"Gopi",
"id":"01",
"subjects":[{
"subject":"maths",
"marks":"84"
},
{
"subject":"science",
"marks":"85"
}],
"teachers":{
"name": "teacherA"
}
}

enter image description here

I am using below code. But I see [object Object],[object Object] under the column ‘subjects’

var json2xls = require('json2xls');
const fs = require('fs')
var json = {
  "name": "Gopi",
  "id": "01",
  "subjects": [{
    "subject": "maths",
    "marks": "84"
  },
  {
    "subject": "science",
    "marks": "85"
  }],
  "teachers": {
    "name": "teacherA"
  }
}
var xls = json2xls(json);
fs.writeFileSync('stackof.xlsx', xls, 'binary');

Acomodar elementos de izquierda a derecha [closed]

Estoy desarrollando una barra de busqueda, ya logre que funcione correctamente. mi problema es que los articulos aparecen listados uno debajo del otro cuando yo quiero que aparezcan de izquierda a derecha. Si alguien pudiera ayudarme con eso, lo agradeceria mucho.

trato de que los productos de mi lista se acomoden de izquierda a derecha sin que mi barra de busqueda deje de funcionar

Started studying code and January, and I lost a lot of time on deprecated tutorials

Im new into programming,I started studying really hard, 10-14 hrs a day, and I made some bad decisions buying online deprecated courses. I took the JS-NodeJS-Rect/Vue path. For that I thought UDEMI was ok and I got the 2023 full stack course. Now it’s been ok so far, but EJS and mongoose are deprecated and I can’t go along with the course. Are there any resources you can recommend me???? Thanks!!!!!

Some up to date guided way to learn

Get type for an object’s values where each object is of type , and each function have different argument

The object looks like this

export const templates = {
  [EventType.EventType1 + OutputSources.Email]: (params: { documentName: string; link: string }) => {
    return "some html data";
  },
  [EventType.EventType2 + OutputSources.Email]: (params: { documentName: string }) => {
    return "some html data";
  },
  [EventType.EventType1 + OutputSources.Notification]: (params: { documentName: string }) => {
    return "some html data";
  },
} as const;

I want to have a type that contains parameters of each of these function as a union, for example the result for above will look like.
type possibleFunctionArgs = {documentName:string,link:string} | {documentName:string}

What I’ve already tried and failed
type lastFailingAttemptToGetTypes = Parameters<typeof templates[keyof typeof templates]>
For the above code I’m always getting only {documentName:string,link:string} , always getting the one with highest number of parameters

Is there a way in Zod to create a new schema from an object schema by type?

Let’s say I have the following example schema:

const Z_GlobalSettings = z.object({
  crust: z.enum(["thin", "thick"]).default("thin"),
  toppings: z.array(z.string()).min(1).max(5).default(["cheese"]),
  sauce: z.enum(["marinara", "bbq", "ranch"]).default("marinara"),
  delivery_time: z.string().optional(),
  order_notes: z.string().max(50).optional(),
  contact_email: z.string().email().optional(),
  setting_1: z.boolean(),
  setting_2: z.boolean().optional(),
});

type GlobalSettings = z.infer<typeof Z_GlobalSettings>;

How can I programmatically extract the types that contain booleans, or whichever arbitrary type I’m looking for? For example, if I want the booleans from the schema, I’d want my new schema to look like:

const Z_OnlyBoolean = z.object({
  setting_1: z.boolean(),
  setting_2: z.boolean().optional(),
});

I was initially able to accomplish this using Typescript:

type BooleanSettings = {
  [K in keyof GlobalSettings as GlobalSettings[K] extends boolean | undefined
    ? K
    : never]?: boolean;
};

However, this wasn’t working when I wanted to differentiate between z.string() and z.enum(["example1", "example2"]), since they’d both come through as strings. This is why I’m hoping to find a way to filter a schema by type since Zod is keeping track of the difference between strings and enums, but the only way I can find in the documentation is to use the .pick() method and choose them one-by-one. This won’t be great if I add properties in the future, since I’ll need to update the filtered schema as well, and won’t be great for usability since I’ll need to make a new schema for every type I want to extract.

Any ideas on how to accomplish this?

is there a way to use getElementbyid but for multiple of the same id’s

I’m trying to use a function that appends a text onto an answer choice on a multiple choice quiz but I can only seem to access the first answer value.

<!doctype html>
<html>
    
    <head>
        <meta charset="utf-8" />
        <title>name</title>

    </head>
    <h1>
        name
    </h1>
    <body style="background-color:rgb(73, 88, 83);">

            <div id="question1">
                <p>1. which planet is considered earth's sister planet?</p>
                <a href = "#">
                    <p id = "answer" value = "wrong">a. moon</p>
                </a>
                <a href = "#">
                    <p id = "answer"  value = "correct">b. venus</p>
                </a>
                <a href = "#">
                    <p id = "answer" value = "wrong">c. mars</p>
                </a>
            </div>

            <div id="question2">
                <p>2. when did apollo 11 land?</p>
                <a href = "#"> 
                    <p id = "answer" value = "correct">a. 1969</p>
                </a>
                <a href = "#">
                    <p id = "answer"  value = "wrong">b. 1970</p>
                </a>
                <a href = "#">
                    <p id = "answer" value = "wrong">c. 1968</p>
                </a>
            </div>

            <div id="question3">
                <p>3. which is the planet mars?</p>
                <a href = "#">
                    <p id = "answer" value = "wrong">a. <img src = "https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg" width="50" height="50"> </p>
                </a>
                <a href = "#">
                    <p id = "answer"  value = "wrong">b. <img src = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Africa_and_Europe_from_a_Million_Miles_Away.png" width="50" height="50"> </p>
                </a>
                <a href = "#">
                    <p id = "answer" value = "correct">c. <img src = "https://upload.wikimedia.org/wikipedia/commons/0/02/OSIRIS_Mars_true_color.jpg" width="50" height="50"> </p>
                </a>
            </div>

            <div class="buttons">
                <button id="reset-button"> Reset </button>
            </div>


            <script>
                const reset = document.getElementById("reset-button")
                var clicked = document.getElementById("answer")
                var text = document.createTextNode(" correct")
                var text_2 = document.createTextNode(" wrong")
        
                reset.addEventListener('click', resetquestions)
                clicked.addEventListener('click', giveAnswer)
                
    
                function giveAnswer() {
                    if(clicked.value === "correct") {
                        clicked.appendChild(text)
                    }
                    else {
                        clicked.appendChild(text_2)
                    }
                }

                function resetquestions() {
                    if(clicked.value === "correct") {
                        text.remove()
                    }
                    else {
                        text_2.remove()
                    }
                }
            </script>
    </body>
</html>

I want to be able to append a correct or wrong text to every answer choice that I click. I tried changing the ID’s to answer_1_1, answer_1_2 and adding an event listener to them individually but unfortunately I wasn’t even able to get the first response’s answer anymore. How can I fix this? sidenote: i’m not allowed to use buttons or input for the answer choices.