Javascript not working as intended, code copied from W3 schools website

I’ve copied the code for a product filtering system from the W3 schools website (includes JavaScript, CSS and html) but it’s not working as intended. I’m doing this for a school project and the code is working perfectly fine for my classmates who also copied it straight from the W3 schools website. I showed my teacher my code and they couldn’t see the issue. There are 6 buttons, including a “show all” option which can be used to filter through a range of products. This is what it looks like when the products page is first opened (hasn’t been interacted with yet):

enter image description here

The “Show all” option is selected by default (shown by the grey colour)

However, when I try selecting another button, the previous button selected doesn’t revert to the colour white, instead it stays grey:

enter image description here

This eventually results in all the buttons turning grey (in this example I haven’t selected the two rightmost buttons). This makes it difficult to tell which filter is currently selected.

I know it’s a very minor detail, but I would greatly appreciate any help because my project is due very soon (:

As I said, all my code was copied directly from the W3 schools website, and I have checked many times that the code is identical, however the problem persists. I will paste and screenshot the CSS and JavaScript code because I don’t think the problem is in the HTML, but if you think the problem could be in my html code, then I can show you that as well. Another option is that the issue could be to do with my ‘over-arching’ CSS code which is used to style both the home and products pages, so I can include that if you’d like it.

This is the JavaScript code:

            filterSelection("all") // Execute the function and show all columns
            function filterSelection(c) {
              var x, i;
              x = document.getElementsByClassName("column");
              if (c == "all") c = "";
              // Add the "show" class (display:block) to the filtered elements, and remove the "show" class from the elements that are not selected
              for (i = 0; i < x.length; i++) {
                w3RemoveClass(x[i], "show");
                if (x[i].className.indexOf(c) > -1) w3AddClass(x[i], "show");
              }
            }
            
            // Show filtered elements
            function w3AddClass(element, name) {
              var i, arr1, arr2;
              arr1 = element.className.split(" ");
              arr2 = name.split(" ");
              for (i = 0; i < arr2.length; i++) {
                if (arr1.indexOf(arr2[i]) == -1) {
                  element.className += " " + arr2[i];
                }
              }
            }
            
            // Hide elements that are not selected
            function w3RemoveClass(element, name) {
              var i, arr1, arr2;
              arr1 = element.className.split(" ");
              arr2 = name.split(" ");
              for (i = 0; i < arr2.length; i++) {
                while (arr1.indexOf(arr2[i]) > -1) {
                  arr1.splice(arr1.indexOf(arr2[i]), 1);
                }
              }
              element.className = arr1.join(" ");
            }
            
            // Add active class to the current button (highlight it)
            var btnContainer = document.getElementById("myBtnContainer");
            var btns = btnContainer.getElementsByClassName("btn");
            for (var i = 0; i < btns.length; i++) {
              btns[i].addEventListener("click", function(){
                var current = document.getElementsByClassName("active");
                current[0].className = current[0].className.replace(" active", "");
                this.className += " active";
              });

}

If a screenshot is easier to read:

enter image description here

This is the CSS code (for the entire products page, not just the button filters):

products {
  
  margin-bottom: 100px;

    /* Center website */
  .main {
    max-width: 1000px;
    margin: auto;
  }

  h1 {
    font-size: 50px;
    word-break: break-all;
    align-items: center;
    text-align: center;
    justify-content: center;
  }

  .row {
    margin: 8px -16px;
  }

  /* Add padding BETWEEN each column (if you want) */
  .row,
  .row > .column {
    padding: 8px;
  }

  /* Create three equal columns that floats next to each other */
  .column {
    float: left;
    width: 33.33%;
    display: none; /* Hide columns by default */
  }

  /* Clear floats after rows */
  .row:after {
    content: "";
    display: table;
    clear: both;
  }

  /* Content */
  .content {
    background-color: white;
    padding: 10px;
  }

  /* The "show" class is added to the filtered elements */
  .show {
    display: block;
  }

  /* Style the buttons */
  .btn {
    border: none;
    outline: none;
    padding: 12px 16px;
    background-color: white;
    cursor: pointer;
  }

  /* Add a grey background color on mouse-over */
  .btn:hover {
    background-color: #ddd;
  }

  /* Add a dark background color to the active button */
  .btn.active {
    background-color: #666;
    color: white;
  }

}

Screenshot of the CSS:

enter image description here

Error: “A tag read consent state before a default was set” for Google consent mode v2

I’m configuring Google consent mode v2 for PHP based project. And after I open the web page in browser, in Google tag assistant I receive the data I sent (such as ‘ad_user_data’) but receive and error “A tag read consent state before a default was set”
Google Tag Assistant result

This is the beginning of the html code of my project which contains the code for Google consent mode v2.

<head>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments)};
        gtag('consent', 'default', {
            'ad_user_data': 'denied',
            'ad_personalization': 'denied',
            'ad_storage': 'denied',
            'analytics_storage': 'denied',
        })

I want to find out where this error is coming from and remove it.

Localisation German: jquerys’ DatePicker “ä” is not recognized

I have an odd behavior:
I use datepicker. It works fine. As long it is in English. I want it in German. Ok, reading reading reading, I found out, that I had to include a localisation file.

Januar, Februar works fine. But März don’t work. I got a “?” inside a Rhombus. More reading. Checked the files to utf8, ok.

Inserted ` No change.

Just for fun I added the french localisation. Eh voila. März looks like it should be. But the file blocks previous month.
I changed min-month from 0 to -2 and -2 M and -60 d.
Now I could go in the past, but the actual month is displayed correctly only once, and when going back and forward, it fall back to english. Neither French nor German

Then I tried another localisation file. Same problem.
Here some code:

<script src="./js/jquerymini.js" type="text/javascript" charset="UTF-8"></script>
<script src="./js/jquerymini2.js" type="text/javascript" charset="UTF-8"></script>
<link rel="stylesheet" href="../maincss/jquerycss.css"  type="text/css" media="all" />
<script src="./js/jquery-datepicker-de.js" type="text/javascript" charset="UTF-8"></script>
<link rel="stylesheet" type="text/css" href="../maincss/datepicker.css">

and here the form:

include_once('includes/header.php');
<table><td>...
<script type="text/javascript">
$(function() {$("#datepicker<?php echo $anzahlteileinsaetze;?>").datepicker();});
</script>
</td>
</tr>
<tr>
<td class="datenzelle2">Datum des Teil-Einsatzes <?php echo $anzahlteileinsaetze;?></td>
<td class="datenzelle2">
<?php echo '<input type="text" name="datum[]" size="75" value="'.$value;?>" id="datepicker<?php     
echo $anzahlteileinsaetze;?>"  class="textfeld" readonly></td>
</tr> 

There are more than 1 datepicker. It is like: basket1 on 2024/03/01, basket2 on 2024/03/03, basket on 2024/03/08

So the var is date1,date2 date3, …
The whole file is php and utf-8.
Any idea
regards
Oliver

Is there a way to block countries IPs for my Nuxt website?

I’m using Nuxt.JS and host my Website on Vercel
I already tried things like this:

const response = await useFetch('https://api.ipify.org/?format=json');
const ipAddress = response.data._value.ip;
ipAddress.trim()
const details = await useFetch(`https://freeipapi.com/api/json/${ipAddress}`)
const countrycode = details.data._rawValue.countryCode
if(countrycode != 'CH' && countrycode != 'DE'){
  await navigateTo('/restricted')
}

But then the IP-Address is the one from Vercel I think. But definitely not mine. And also the country code isnt the one from me (as a user on my website)

How to get objects from array of objects whose property “name” contains similar value in JavaScript

I have an array of object,I need to get those objects only whose property “name” having similar value.I have provided the expected output also.Here is the code below.

 <!DOCTYPE html>
    <html>
    <body>
    <h2>JavaScript</h2>
    <script>
    const value = 

    [
        {
            "id": 2,
            "name": "Pumpkin"
        },
        {
            "id": 1,
            "name": "Ladies Finger"
        },
        {
            "id": 4,
            "name": "Spinach"
        },
        {
            "id": 5,
            "name": "Spinach"
        }
    ]
    console.log("get same value property")
   /*Expected output 
[
    {
        "id": 4,
        "name": "Spinach"
    },
    {
        "id": 5,
        "name": "Spinach"
    }
]
*/
</script>
</body>
</html> 

How to use Tooltip with virtualSelectInput in R Shiny to show filter values if text is long and hidden by ellipsis

I’ve a R shiny application in which I am using virtualSelectInput to show list of values for my filter. But some of my text values are long and the dropbox hides them by ellipsis(…).

I see that the Virtual Select documentation mentions using Tooltip for displaying these long values while hovering cursor during value selection. But I couldn’t figure out a way to use it in R Shiny.

I also found that R shiny has another function called tooltipOptions from same shinyWidgets library to show tooltip for a dropdown menu button. But again, there isn’t any usage example.

I tried using it in below form through a dummy shiny app –

library(shiny)
library(shinyWidgets)

options <- c(
  "This is short text",
  "This is a longer text",
  "This is a very very very very long text",
  "This is a super ultra pro max very very very very long text"
)

ui <- fluidPage(
  titlePanel("Virtual Select Input Example"),
  
  virtualSelectInput("selected_option", "Select Digital Thread:", choices = options, 
                     multiple = TRUE, search = TRUE, searchNormalize = TRUE, position = "auto", dropboxWidth = "250px", 
                     showSelectedOptionsFirst = TRUE, placeholder = "All", markSearchResults = TRUE, selectAllOnlyVisible = TRUE,
                     tooltipOptions = tooltipOptions(placement = "right", title = "Params", html = FALSE)),
  
  textOutput("selected_value")
)

server <- function(input, output, session) {
  output$selected_value <- renderText({
    paste("You selected:", input$selected_option)
  })
}

shinyApp(ui, server)

But it doesn’t work. I know I am not correctly using these together, so I would appreciate if someone can guide on using it either through this or any other simple way.
I am not very inclined towards using a custom css or js code because in my real application I have Virtual Select at almost 100 different places.

How to filter rows independently in AG-grid tree data?

I’m actually checking the documentation on filtering in AG-Grid, specifically focusing on tree data: https://www.ag-grid.com/angular-data-grid/tree-data/ In the demo section titled “Example: Organisational Hierarchy,” I made adjustments to the example code by adding: filter: 'agTextColumnFilter' in the defaultColDef to have a basic filter option in each column.

When attempting to filter for rows with “Erica Rogers” in the “Organisation Hierarchy” column and “Sales Executive” in the “Job Title”, the resulting dataset is empty. However, the issue is that I don’t want that output and I don’t know how to counter this behavior, I would like my grid to display tree data with these filters by applying them idependently.

I get why this is happening. It’s because the filters have a “AND” logic between them. So, I don’t have any result because there is no row with “Erica Rogers” in the “Organisation Hierarchy” column AND “Sales Executive” in the “Job Title”.

I think the solution would be to apply each filter independently while taking the view updated by the previous filters. I tried to create custom filters for each column of my grid but at some point, I’m unable to get the view updated by the previous filters.

The issue is that, in the documentation, I didn’t manage to find the solution to solve my problem. My goal is to be able to filter rows independently. Is it possible with the current ag-grid tree data ?

Module resolution with yarn / npm

I am playing around with remix and mui v5.
Using npm I get the following error when running npm run dev

Error: Directory import '.../playground/remix-mui-dev/node_modules/@mui/material/styles' is not supported resolving ES modules imported from .../playground/remix-mui-dev/build/index.js

I expected that this should work.

I have seen a lot of hints on the net what might be the problem.
But then I tried yarn (4.1.1) with pnp resolution: No error

So I switched to yarn with node-modules: Same error as with npm.

I am not at all an expert in TS / frontend development and tooling.
I would like to better understand what the interplay between the TS / JS module resolution and the package managers is.
But lacking the knowledge, I do not really find the references on the net, that point me in the right direction.

I have created a repo (remix-mui-dev)[https://github.com/rattermeyer/remix-mui-dev] with two branches (main=> npm and yarn for yarn)

{SQL] What program can I use to practice and run X amount of coding languages? [closed]

I’m fairly new to, well, practically all of this, with only below intermediate level programming skills. I am currently a student and was just wondering what program(s) would be best for learning, as far as practicing writing code(in many various coding languages) and being able to run them in the same window(or split, preferred). Any and all help and suggestions are very welcome. Thank you in advance!

I have experimented with PyCharm and have worked in VSC(Visual Studio Code), the latter with most compatibility, but am wondering if there are more/better options to try out??

How to Stop list of Items from Disappearing from page refresh, even though list is saved in local storage?

I am creating a to-do list.

The app can do the following:

  • Create a task
  • Render the Task
  • storing the data in local storage

Need help on

When the browser refreshes, the local storage does not stay on the DOM, instead it disappears.

I created a function that creates the task and stores the new task in an object and pushes that object into an empty array.

`let taskArray = [];

let taskListEl = document.getElementById("tasklist");

function createTask() { 

/Time Stamp/ 

let currentDate = new Date();

let year = currentDate.getFullYear(); 
let month = (currentDate.getMonth() + 1).toString().padStart(2, "0"); 
let day = currentDate.getDate().toString().padStart(2, "0"); 
let hours = currentDate.getHours().toString().padStart(2, "0"); 
let minutes = currentDate.getMinutes().toString().padStart(2, "0"); 
let seconds = currentDate.getSeconds().toString().padStart(2, "0");

let timeStamp = ${year}-${month}-${day} ${hours}:${minutes}:${seconds}; let randomId = Math.round(Math.random() * parseInt(${year}${month}${day}, 10) * 100);

let taskObj = { timeStamp: timeStamp, id: randomId, task: InputTask.value, date: InputDate.value, };

taskArray.push(taskObj); 
renderTask() 
storeTaskArrayLocally();

} 

I created another function that renders the new item to the DOM

function renderTask(){
    taskListEl.innerHTML = '';
    taskArray.forEach((task) => {
        let divEl = document.createElement("div");
        divEl.classList.add("task-flex");
    
        divEl.innerHTML = `<div class="task-buttons">
            <img src="./resources/icons/edit.png" alt="Edit Buttin"/>
            <img src="./resources/icons/bin.png" alt="Bin Buttons" />
            <img src="./resources/icons/completed-task.png" alt="Complete Task Button" />
          </div>
    
          <div class="task-to-do" data-id="${task.id}" data-value = "${task.timeStamp}">
              <div class="list" id="list-item-date">Due: ${task.date}</div>
              <div class="list" id="list-item-task">${task.task}</div>
          </div>`;
    
        taskListEl.append(divEl);
        
      });
}

Because the array is taking in objects, I made sure the local storage was turning the obejcts into a JSON and then parsing the JSON.

function storeTaskArrayLocally() {   
    localStorage.setItem("taskLocalstorage", JSON.stringify(taskArray)); 
}  

function initializeTaskAraryFromLocalStoraege(){   
    const storedTask = localStorage.getItem("taskLocalstorage");    
    if(storedTask){
    taskArray.JSON.parse(storedTask);
    renderTask();
    }    

}  

initializeTaskAraryFromLocalStoraege();

I do get an error in the consol command with the taskArray.JSON.parse(storedTask); the error is as follows:

main.js:139 Uncaught TypeError: Cannot read properties of undefined (reading 'parse')
    at initializeTaskAraryFromLocalStoraege (main.js:139:22)
    at main.js:145:1

How can I end a session on my webpage when I click on the X or close button on browser?

When clicking X or close button my session does’t end and I can get to my dashboard page without linking at login page. I couldn’t figure out how can I end session when I click on close(X) button. I would appreciate if you got something helpful to show me…

I can end session when I click on logout button on the navbar and I can’t get to pages without logging in and thats totally ok. What I expect to end the session when I click on close(X)
button as the same when I click on log out button.

Difficulty Building Dynamic Table from JSON Data Using JavaScript

I’m facing challenges in creating a dynamic table from JSON data using JavaScript. I’ve attempted several approaches, but none seem to be working as expected. Essentially, I’m trying to populate a table dynamically based on the data provided in JSON format. Despite my efforts, I’m unable to achieve the desired outcome.

What I’ve Tried:

I attempted to iterate through the JSON data using JavaScript and dynamically create table rows and cells accordingly.
I explored various JavaScript libraries and frameworks like jQuery to simplify the process, but still encountered difficulties.
I experimented with different methods for parsing the JSON data and injecting it into the table structure, but none produced the desired result.

What my expected result:
enter image description here

However, I’m struggling to achieve this. I have team data and want to generate a table like this using the provided data.

    {
        "name": "GSW",
        "year": [
            "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030",
            "2031", "2032", "2033", "2034", "2035"
        ],
        "wins": [
            10, 11, 12, 13, 13, 13, 13, 14, 15, 16, 17, 18, 19, 20, 21
        ],
    },
    {
        "name": "LAL",
        "year": [
            "2021", "2022", "2023", "2024", "2025", "2026", "2027", "2028", "2029", "2030",
            "2031", "2032", "2033", "2034", "2035"
        ],
        "wins": [
            9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23
        ],
    },
    {
        "name": "PHX",
        "year": ["2000", "2001"],
        "wins": [1, 4]
    }
]

Technically, I want to create a table with a maximum of 7 columns. When it reaches 7 columns, it should wrap, starting from the next row of the table. If the data for one team is not enough to fill the table, it should take data from the next team. The last row can be an empty row.

The vue router fails after vite vue3 is built. A blank page is displayed

I was using wails of golang to build a desktop program, in which the front-end introduced the Vue Router. When npm run dev was used, the page could be normally opened and displayed. However, when npm run build was used to build packages, the page content was displayed blank, and no error occurred on the console. I don’t know where the problem is at the moment

vite.config.js

import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path' 

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    vue()
  ],
  resolve: {
    alias: {
      '@': path.resolve(__dirname, 'src'),
    },
  },
})

main.ts

import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import {create, NBreadcrumb, NBreadcrumbItem, NButton, NCard, NCode, NConfigProvider, NFlex, NForm, NFormItem, NGi, NGradientText, NGrid, NInput, NLayout, NLayoutSider, NLog, NMessageProvider, NModal, NSelect, NSpin, NTree} from 'naive-ui'
import './style.css';

const naive = create({
    components: [
        NButton,
        NInput,
        NCard,
        NFlex,
        NGrid,
        NGi,
        NForm,
        NFormItem,
        NSelect,
        NMessageProvider,
        NLayout,
        NLayoutSider,
        NBreadcrumb,
        NBreadcrumbItem,
        NConfigProvider,
        NLog,
        NCode,
        NSpin,
        NTree,
        NModal,
        NGradientText
    ]
})

createApp(App).use(router).use(store).use(naive).mount('#app')

router.ts

import {createRouter, createWebHashHistory, createWebHistory} from 'vue-router'
import Layout from '../components/layout/index.vue'

const routes: any[] = [
    {
        path: '/', 
        component: Layout,
        name: 'layout',
        redirect: '/index',
        children: [
            {
                name: 'index',
                path: '/index',
                component: import('@/pages/index/index.vue')
            },
            {
                name: 'get_token',
                path: '/get_token',
                component: import('@/pages/interior/get_token.vue')
            },
            {
                name: 'iot_sync_package',
                path: '/iot_sync_package',
                component: import('@/pages/iot/sync_package.vue')
            },
            {
                name: 'permissions',
                path: '/permissions',
                component: import('@/pages/interior/permissions.vue')
            },
            {
                name: 'permissions',
                path: '/gen_code',
                component: import('@/pages/core/gen_code.vue')
            }
        ]
    }
]

const router = createRouter({
    history: createWebHashHistory(),
    routes
})

router.onError((handler) => {
    console.error(handler)
})

export default router

How do I display properly in wails

How to access authentication state inside middleware.js in my Next JS app?

I am working on a Next JS app using Firebase Authentication. I have successfully implemented this and also made an AuthContext file to store Authentication functions (login, signup, signout) and manage the Auth state. Here is my AuthContext file:

const AuthContext = createContext();

export default AuthContext;

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState();
  const router = useRouter();

  useEffect(() => {
    const unsubscribe = onAuthStateChanged(auth, (currentUser) => {
      setUser(currentUser);
    });
    return () => unsubscribe();
  }, [user]);

  const handleRegister = async (e) => {
   ...
  };

  const handleLogin = async (e) => {
    const formData = new FormData(e.currentTarget);
    const email = formData.get("email");
    const password = formData.get("password");

    await signInWithEmailAndPassword(auth, email, password)
      .then((userCredential) => {
        router.push("/dashboard");
      })
      .catch((error) => {
        ...
      });
  };

  const handleLogout = () => {
    signOut(auth);
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        handleRegister,
        handleLogin,
        handleLogout,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

Also, from NextJS documentation I learnt that:

Middleware in Next.js helps you control who can access different parts
of your website. This is important for keeping areas like the user
dashboard protected while having other pages like marketing pages be
public. It’s recommended to apply Middleware across all routes and
specify exclusions for public access.

So, I have my middleware.js file in the root directory. And have the following code:

import type { NextRequest } from 'next/server'
 
export function middleware(request: NextRequest) {
  const currentUser = request.cookies.get('currentUser')?.value
 
  if (currentUser && !request.nextUrl.pathname.startsWith('/dashboard')) {
    return Response.redirect(new URL('/dashboard', request.url))
  }
 
  if (!currentUser && !request.nextUrl.pathname.startsWith('/login')) {
    return Response.redirect(new URL('/login', request.url))
  }
}
 
export const config = {
  matcher: ['/((?!api|_next/static|_next/image|.*\.png$).*)'],
}

However, it seems that I am unable to get currentUser as described above. So, how can I access the same using my user’s state from Context? Is there any way to do so? If not what’s ideal way to get user state in the middleware?

Why can’t I grab state from one component to another component?

  • I have two function component (component1) and it’s a main component and (component2) which i want to grap state data from it
import { useState, createContext, useContext } from "react";
import ReactDOM from "react-dom/client";

const TestContext = createContext();

function Component1() {
  const test = useContext(TestContext);
  return (

      <h1>{`${test}`}</h1>
      
  );
}

function Component2() {
      const [test, setTest] = useState("From Component 3");

  return (
    <TestContext.Provider value={test}>
      <Component1 />
    </TestContext.Provider>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Component1 />);

In this question:

  • I want to use only useContext Hook to bring state
  • I want Component1 is the rendered component.

I try a lot but always the result is “undefined