Unknown resolution: Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

I tried moving the script tag to the end, this did not work. I also tried adding the script to the and adding defer before the source. Nothing seems to work, is there something I am missing. Here is my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link rel="stylesheet" href="onclick.css" />
    <script defer src="onclick.js"></script>
  </head>
  <body>
    <div class="rotate">
      <div class="rotate-obj">Craft</div>
      <button class="rotate-btn">Spin it</button>
    </div>
  </body>
</html>

I tried moving the script to the head and adding defer as well as moving the script tag to the bottom right before the closing body tag. I’m expecting the button to rotate the text ‘Craft’ once the button is clicked. Nothing happens and I am getting an error (stated in the title above).

Reading data from Firestore database on Web app

I am so very lost on how to simply read records from Firestore.

I have a single collection called properties. In it, I have several documents all in the same form (all have name, and category). That’s it; no subcollections or anything complex.

I have set the rules as follows (many matches for testing):

rules_version = '2';

service cloud.firestore {
  match /databases/{database}/documents {
    allow read;
    
    match /{document=**} {
        allow read;
    }
  
    match /properties/{document=**} {
        allow read;
    }
    
    match /properties/{propertyid} {
        allow read;
    }
  }
}

Then, I have my web-based Expo app with the firebase npmjs package installed. I have initialized my Firebase app, and called getFirestore to grab a database instance and all called signInWithEmailAndPassword and signed in with a test account I set up in the Firebase console.

Finally, I want to grab all documents from the properties collection and display them on screen, so I wrote the following:

const query = collection(db, "properties");
const data = await getDocs(query);

I’ve also tried getting a specific property (I copied the ID from the Firebase console, so I know it exists):

const query = doc(db, "properties", "9sRm1TLWAIpYiZLfWPvo");
 const snapshot = await getDoc(query);

I am also doing the following:

  1. Printing out the user credentials that I called signInWithEmailAndPassword. I see a large object with my uid, accessToken, etc.
  2. Printing out my db variable (comes from this.db = getFirestore(this.app);). I see the correct information: firebase start options (apiKey, authDomain, projectId), my authentication credentials (current user uid matches what I see in the previous auth log, my auth object is filled out, etc. etc. (everything looks normal)

However, whatever the heck I try, I also get “Missing or insufficient permissions”.

I’ve also checked my rules with the “Rules Playground” on any document under /properties and get successful simulated reads, both unauthenticated and authenticated.

What am I doing wrong and how can I just get a list of all documents in that collection? That’s literally all I’m trying to do.

How to convert img to Image component in next.js

I have implemented all the logic in this component. But it is according to the tag. Now, I want same logic to implement in the Image component. But doing so, it is giving me error.

TypeError: Failed to construct 'Image': Please use the 'new' operator, this DOM object constructor cannot be called as a function.

Her is the code I changed “`import React, { useState, useRef, useEffect } from “react”;

const ImageUploadCard = () => {
const componentRef = useRef(null);
const [componentWidth, setComponentWidth] = useState(0);
const [componentHeight, setComponentHeight] = useState(0);

useEffect(() => {
// Function to update component width
function updateComponentWidth() {
if (componentRef.current) {
const width = componentRef.current.getBoundingClientRect().width;
const height = componentRef.current.getBoundingClientRect().height;

    console.log("Component width:", width);
    console.log("Component width:", height);
    setComponentWidth(width);
    setComponentHeight(height);
  }
}

// Update component width initially and add event listener for window resize
updateComponentWidth();
window.addEventListener("resize", updateComponentWidth);

// Clean up event listener on component unmount
return () => {
  window.removeEventListener("resize", updateComponentWidth);
};

}, []);

const inputRef = useRef(null);
const [previewImage, setPreviewImage] = useState(null);

const handleImageChange = (event) => {
const file = event.target.files[0];
if (file && file.size > 5242880) {
// File size exceeds the maximum limit
// You can display an error message or handle it as needed
console.log(“File size exceeds the maximum limit (5MB)”);

  return;
}
if (file) {
  const reader = new FileReader();
  reader.onloadend = () => {
    setPreviewImage(reader.result);
  };
  reader.readAsDataURL(file);
} else {
  setPreviewImage(null);
}

};

return (

<div
style={{ width: componentWidth }}
className=”dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center”
onClick={() => inputRef.current.click()} // Click event triggers file input
>

Image formats: JPEG, PNG, JPG . Max size: 5 MB

<input
type=”file”
accept=”.jpg, .jpeg, .png”
onChange={handleImageChange}
style={{ display: “none” }} // Hide the input visually
ref={inputRef}
// Set a max file size of 5MB (in bytes)
// 5MB = 5 * 1024 * 1024 bytes
// Adjust this value as needed
max=”5242880″
/>

  {previewImage && (
    <div
      className="dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center"
      style={{ width: componentWidth, height: 400 }} // Set width dynamically
    >
      <Image
        src={previewImage}
        alt="Preview"
        style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "cover" }}
      />
    </div>
  )}
</div>

);
};

export default ImageUploadCard;

<img> tag which is working 

import React, { useState, useRef, useEffect } from “react”;

const ImageUploadCard = () => {
const componentRef = useRef(null);
const [componentWidth, setComponentWidth] = useState(0);
const [componentHeight, setComponentHeight] = useState(0);

useEffect(() => {
// Function to update component width
function updateComponentWidth() {
if (componentRef.current) {
const width = componentRef.current.getBoundingClientRect().width;
const height = componentRef.current.getBoundingClientRect().height;

    console.log("Component width:", width);
    console.log("Component width:", height);
    setComponentWidth(width);
    setComponentHeight(height);
  }
}

// Update component width initially and add event listener for window resize
updateComponentWidth();
window.addEventListener("resize", updateComponentWidth);

// Clean up event listener on component unmount
return () => {
  window.removeEventListener("resize", updateComponentWidth);
};

}, []);

const inputRef = useRef(null);
const [previewImage, setPreviewImage] = useState(null);

const handleImageChange = (event) => {
const file = event.target.files[0];
if (file && file.size > 5242880) {
// File size exceeds the maximum limit
// You can display an error message or handle it as needed
console.log(“File size exceeds the maximum limit (5MB)”);

  return;
}
if (file) {
  const reader = new FileReader();
  reader.onloadend = () => {
    setPreviewImage(reader.result);
  };
  reader.readAsDataURL(file);
} else {
  setPreviewImage(null);
}

};

return (

<div
style={{ width: componentWidth }}
className=”dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center”
onClick={() => inputRef.current.click()} // Click event triggers file input
>

Image formats: JPEG, PNG, JPG . Max size: 5 MB

<input
type=”file”
accept=”.jpg, .jpeg, .png”
onChange={handleImageChange}
style={{ display: “none” }} // Hide the input visually
ref={inputRef}
// Set a max file size of 5MB (in bytes)
// 5MB = 5 * 1024 * 1024 bytes
// Adjust this value as needed
max=”5242880″
/>

  {previewImage && (
    <div
      className="dark:bg-jacarta-700 dark:border-jacarta-600 border-jacarta-100 group relative flex flex-col items-center justify-center rounded-lg border-2 border-dashed bg-white py-20 px-5 text-center"
      style={{ width: componentWidth, height: 400 }} // Set width dynamically
    >
      <img
        src={previewImage}
        alt="Preview"
        style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "cover" }}
      />
    </div>
  )}
</div>

);
};

export default ImageUploadCard;


I want to change the <img> tag to Image component so, same logic been implemented. Not Image as a legacy one. But latest one. 

Error submitting form on Discord server using my discord bot

So now my data is being saved into database but the form on discord is not submiting it shows something went wrong on form but the form doesnt close but still i get the success message on my discord channel

here is the code link
code link

screen shot link
screen shot link

see behind form it says You have been successfully registered!

I tried to see the database if it actually saves the data inside the DB and yes it does but my form is not submiting it just says something wrong but shows registration successful

Send form and update button with Javascript

I have a page where users can vote a post or comment with an empty form. I have written JavaScript to submit the form and update the button with the vote count without refreshing the entire page. Instead of refreshing the button, the JavaScript routes to a new page with the JSON data returned from Flask.

post.html

<form class="d-inline" id="vote_form" action="{{ url_for('main.post', id=post.id) }}" method="post">           
    <input id="csrf_token" name="csrf_token" type="hidden" value="{{ csrf_token }}">
    <button class="px-1 py-0 btn btn-outline-dark btn-sm" id="vote_post_btn" type="submit" name="submit" value="vote_post">&#8679; 2</button>
</form>

<form class="d-inline" action="{{ url_for('main.post', id=comment.id) }}" method="post">                    
    <input id="csrf_token" name="csrf_token" type="hidden" value="{{ csrf_token }}">
    <button class="px-1 py-0 btn btn-outline-dark btn-sm" id="vote_comment_btn" type="submit" name="submit" value="vote_comment">&#8679; 0</button>
</form>

routes.py

@bp.route('/post/<int:id>', methods=['GET', 'POST'])
def post(id):
    post = db.first_or_404(sa.select(Post).where(Post.id == id))
    if request.method == 'POST':
        if request.form['submit'] == 'vote_post':
            vote = db.session.scalar(sa.select(PostVote).where((PostVote.user_id == current_user.id) & (PostVote.post_id == id)))
            post = db.session.scalar(sa.select(Post).where(Post.id == id))
            if vote is None:
                vote = PostVote(user_id=current_user.id, post_id=id)
                db.session.add(vote)
                db.session.commit()              
                return jsonify({"votes": post.votes_count(), "voted": True})
            else:
                db.session.delete(vote)
                db.session.commit()              
                return jsonify({"votes": post.votes_count(), "voted": False})
        if request.form['submit'] == 'vote_comment':
            vote = db.session.scalar(sa.select(CommentVote).where((CommentVote.user_id == current_user.id) & (CommentVote.comment_id == id)))
            comment = db.session.scalar(sa.select(Comment).where(Comment.id == id))
            if vote is None:
                vote = CommentVote(user_id=current_user.id, comment_id=id)
                db.session.add(vote)
                db.session.commit()
                return jsonify({"votes": comment.votes_count(), "voted": True})
            else:
                db.session.delete(vote)
                db.session.commit()
                return jsonify({"votes": comment.votes_count(), "voted": False})

javascript

        async function sendVote() {
            let form = document.getElementById("vote_form");            
            let formBtn = document.querySelectorAll("#vote_post_btn, #vote_comment_btn");
            let url = form.getAttribute("action");
                  // Associate the FormData object with the form element
                  const formData = new FormData(form);

                  try {
                    const response = await fetch(url, {
                      method: "POST",
                    })
                    .then((response) => response.json())
                    .then((data) => {
                        formBtn.innerHTML = data["votes"];
                        if (data["votes"] === true) {
                            formBtn.className = "px-1 py-0 btn btn-secondary btn-sm";
                        }
                        else {
                            formBtn.className = "px-1 py-0 btn btn-outline-dark btn-sm";
                        }
                    });
                    console.log(await response.json());
                  } catch (e) {
                    console.error(e);
                  }
        }
        //Take over form submission
        form.addEventListener("submit", (event) => {
          event.preventDefault();
          sendVote();
        });

page rendered

{
  "voted": true,
  "votes": 1
}

The JavaScript doesn’t update the button class and vote count. It renders JSON on a new page instead.
I used this MDN Advanced forms article and MDN json method to write the javascript.

Adjusting Website Viewport for Mobile and PC Users

So I’m normally using common viewport for PC users. As I basically learnt viewport codes for cross-compatibilities (i.e, webkit for Safari and Chrome browsers content rendering). However, I want the website to be accessible for every device and browsers.

Now, the questions are:

  1. Does this require .js file to make the website accessible to every single of device and browsers?
  2. What code would be used to make the task possible? (website accessible to every device and browsers)
  3. How do I make the website landscape-only for Android or iPhone users, thereby forcing users to rotate 90 degrees?
  4. (Optional) I would like to see your recommendation about the cross-compatibility toolkit to check the viewport on different browser and devices without having the website go online.

Thank you!

I only knew basic viewport such as device-width and initial-scale=”1.0″, and I tried to figure out by looking at the Q&A out there (and not sure how I should address the problem on Google).

Uncaught TypeError: addToMovieList is not a function

// MovieList.jsx
import "./movieList.scss";
import axios from "axios";
import { useEffect, useState } from "react";
import Card from "../card/Card";

function MovieList({ savedMovies, setSavedMovies }) {
  const [movieList, setMovieList] = useState(() => {
    const storedMovieList = JSON.parse(localStorage.getItem("movieList"));
    return storedMovieList || [];
  });

  useEffect(() => {
    if (!movieList.length) {
      fetchMovieList();
    }
  }, []); // Fetch movie list only on component mount if movieList is not available

  useEffect(() => {
    localStorage.setItem("movieList", JSON.stringify(movieList));
  }, [movieList]); // Update local storage whenever movieList changes

  const fetchMovieList = () => {
    axios
      .get(
        `https://api.themoviedb.org/3/discover/movie?api_key=${import.meta.env.VITE_API_KEY}`
      )
      .then((res) => {
        setMovieList(res.data.results);
      })
      .catch((err) => {
        console.log(err);
      });
  };


  const addToMovieList = (movieId) => {
    // Find the movie to add from savedMovies
    const movieToAdd = savedMovies.find(movie => movie.id === movieId);
    
    // Check if the movie to add exists
    if (movieToAdd) {
      // Update movieList state by adding the movie
      setMovieList(prevMovieList => [...prevMovieList, movieToAdd]);
    }
  };
  

  const removeFromMovieList = (movieId) => {
    setMovieList((prevMovieList) =>
      prevMovieList.filter((movie) => movie.id !== movieId)
    );
  };

  return (
    <div className="movieList">
      <Card
        movieList={movieList}
        savedMovies={savedMovies}
        setSavedMovies={setSavedMovies}
        removeFromMovieList={removeFromMovieList}
        addToMovieList={addToMovieList}
      />
    </div>
  );
}

export default MovieList;

// Card.jsx code
import { useState, useEffect } from "react";
import "./card.scss";

function Card({ movieList, savedMovies, setSavedMovies, source, removeFromMovieList, addToMovieList }) {
  const [saved, setSaved] = useState(null);
  
  const handleButtonClick = (movie) => {
    const isSaved = savedMovies.find((savedMovie) => savedMovie.id === movie.id);

    if (isSaved) {
      // If the movie is already saved, remove it
      const updatedSavedMovies = savedMovies.filter((savedMovie) => savedMovie.id !== movie.id);
      setSavedMovies(updatedSavedMovies);
      // Add the movie back to the movieList
      addToMovieList(movie.id); // Add the movie back to movieList
    } else {
      // If the movie is not saved, add it to savedMovies
      setSavedMovies((prevSavedMovies) => [...prevSavedMovies, movie]);
      // Remove the movie from the movieList
      removeFromMovieList(movie.id);
    }
    // Toggle the saved state of the movie
    setSaved((prevSaved) => (prevSaved === movie.id ? null : movie.id));
  };

  useEffect(() => {
    localStorage.setItem("savedMovies", JSON.stringify(savedMovies));
  }, [savedMovies]);

  return (
    <div className="cardContainer">
      {(source === "saved" ? savedMovies : movieList).map((movie) => (
        <div className="card" key={movie.id}>
          <div className="save">
            <button
              onClick={() => {
                handleButtonClick(movie);
              }}
              className={`button ${saved === movie.id ? "saved" : ""}`}
            >
              {saved === movie.id ? (
                <img src="/trash.png" alt="Remove from saved" />
              ) : (
                <img src="/star.png" alt="Add to saved" />
              )}
            </button>
          </div>
          <img
            src={`https://image.tmdb.org/t/p/w500${movie.poster_path}`}
            alt=""
          />
          <p>{movie.title}</p>
        </div>
      ))}
    </div>
  );
}

export default Card;

Please help me with this. I want to have my button add the selected movie back to the original movieList local storage. My local storage has the original movie list to display on one tab, and a savedMovies array to display on a different tab. I’m trying to call the addToMovieList function in the card component to add the movie back to my original movie list array when I click on the button, however I’m getting the TypeError. How come my removeFromMovieList works fine but not addToMovieList?

Switching between system, dark, and light mode

I am using MUI in my Next.js web app to switch between system, light, and dark mode. I am having it persist between sessions by saving the theme selected in local storage. I have placed the ability to change the theme of the web app within a dropdown in the settings modal, so changing of the theme occurs through a useContext. The issue I’m encountering is that theming is not persistent across all of my components if the theme the user selects is either the “system” theme (if your system them is dark mode), or “dark” theme. In addition, I also receive this error if my theme is not “light” theme on initial load or when switching from “light” theme to one of the others:

Warning: Prop `className` did not match. Server: "MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit MuiIconButton-edgeStart MuiIconButton-sizeMedium css-134qg7o-MuiButtonBase-root-MuiIconButton-root" Client: "MuiButtonBase-root MuiIconButton-root MuiIconButton-colorInherit MuiIconButton-edgeStart MuiIconButton-sizeMedium css-6pxnsq-MuiButtonBase-root-MuiIconButton-root

After some searching, I originally thought it was because I had not been using CssBaseline within the ThemeProvider tags, however, after adding it, it appears to have only made things worse, and the error persists. I will show the different behavior in screenshots below:

Expected behavior if in “system” or “dark” mode (This is without CssBaseline between the ThemeProvider tags:
enter image description here

The actual behavior without CssBaseline on load in with “system” or “dark” mode:
enter image description here

The behavior on load when in “system” or “dark” mode with CssBaseline:
enter image description here

The behavior when switching from “light” mode to “system” or “dark” mode:
enter image description here

Listed below is my context code and how I’m getting the theme from the system, how I’m storing it in local storage, and how I’m switching it:

const ThemeContext = createContext()

const useThemeContext = () => useContext(ThemeContext)

export const ThemeModeProviderComponent = ({ children }) => {
  const systemTheme = typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'

  const [selectedTheme, setSelectedTheme] = useState(() =>
    typeof localStorage !== 'undefined' && localStorage.getItem('theme') || 'system'
  )

  const themes = {
    light: createTheme({
      palette: {
        mode: 'light',
        primary: {
          main: '#0065bd'
        },
        secondary: {
          main: '#00b6d3'
        }
      }
    }),
    dark: createTheme({
      palette: {
        mode: 'dark',
        primary: {
          main: '#0065bd'
        },
        secondary: {
          main: '#00b6d3'
        }
      }
    }),
    system: createTheme({
      palette: {
        mode: systemTheme,
        primary: {
          main: '#0065bd'
        },
        secondary: {
          main: '#00b6d3'
        }
      }
    })
  }

  useEffect(() => {
    if (selectedTheme === 'system') {
      const systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
      themes.system.palette.mode = systemTheme
    }
  }, [selectedTheme, themes.system])

  const handleThemeChange = (event) => {
    const { value } = event.target

    setSelectedTheme(value)
    localStorage.setItem('theme', value)
  }

  return (
    <ThemeContext.Provider value={{ selectedTheme, handleThemeChange }}>
      <ThemeProvider theme={themes[selectedTheme]}>
          <CssBaseline enableColorScheme/>
          {children}
      </ThemeProvider>
    </ThemeContext.Provider>
  )
}

export const ThemeSelector = () => {
  const { selectedTheme, handleThemeChange } = useThemeContext()

  if (typeof window === 'undefined') return null

  return (
    <FormControl>
      <Select
        value={selectedTheme}
        onChange={handleThemeChange}
      >
        <MenuItem value='system'>System</MenuItem>
        <MenuItem value='dark'>Dark</MenuItem>
        <MenuItem value='light'>Light</MenuItem>
      </Select>
    </FormControl>
  )
}

Another possibility is that, because of the way I’m handling the showing and hiding of the drawer, it could be affecting the style. I basically copied the persistent drawer example from the MUI website here, but I don’t think it’s the case, as, as we’ve seen in the images, it it working properly to an extent.

Generated button wont submit data to my google spreadsheet

i have these function on my google script app to generate some button on a table

FYI i have no knowledge of JS, and i just made this with chat GPT

// Function to handle button clicks
function handleButtonClick(rowIndex, colIndex) {
  google.script.run.withSuccessHandler(function(response) {
    // Do something after button click, if needed
  }).handleButtonClick(rowIndex, colIndex);
}

// Function to handle date button clicks
function handleDateButtonClick(rowIndex, colIndex) {
  google.script.run.withSuccessHandler(function(response) {
    // Do something after date button click, if needed
  }).handleDateButtonClick(rowIndex, colIndex);
}

function submitData(client, tanggalDatang, jenisBarang) {
  var sheet = SpreadsheetApp.openById('SPREADSHEET_ID').getSheetByName('Utama');
  var dataRange = sheet.getDataRange();
  var values = dataRange.getValues();
  var matchedRowData = '';
  var totalFound = 0;

  for (var i = 1; i < values.length; i++) {
    if (values[i][3] == client && Utilities.formatDate(values[i][1], Session.getScriptTimeZone(), 'dd/MM/yyyy') == tanggalDatang && (jenisBarang === '' || values[i][4] == jenisBarang)) {
      totalFound++;
      matchedRowData += '<table class="table table-bordered">';
      for (var j = 0; j < values[i].length; j++) {
        var cellValue = values[i][j];
        var orderId = values[i][0];
        var trId = orderId + '_' + (j + 1);
        if (i === 1) {
          matchedRowData += '<tr id="' + trId + '"><th style="width: 30%; font-weight:bold;">' + values[0][j] + '</th><td>' + cellValue + '</td>';
        } else {
          matchedRowData += '<tr id="' + trId + '"><td style="width: 30%;">' + values[0][j] + '</td><td>' + cellValue + '</td>';
        }
        if (j >= 13 && j <= 19) { 
          matchedRowData += '<td style="width: 15%;"><button onclick="handleButtonClick(' + i + ', ' + (j + 1) + ')">Button</button></td>';
        } else if (j >= 7 && j <= 9) { 
          matchedRowData += '<td style="width: 15%;"><button onclick="handleDateButtonClick(' + i + ', ' + (j + 1) + ')">Add Date</button></td>';
        }
      }
      matchedRowData += '</tr></table><br>';
    }
  }

  matchedRowData = '<h3>Data dari <strong>' + client + '</strong> tanggal <strong>' + tanggalDatang + '</strong> - Total: <strong>' + totalFound + '</strong> item </h3>' + matchedRowData;

  return matchedRowData;
}

and this is my script on index html to handle that GS

        function handleSubmit(event) {
            event.preventDefault();
            var client = document.getElementById("clientSelect").value;
            var tanggalDatang = document.getElementById("tanggalDatangSelect").value;
            var jenisBarang = document.getElementById("jenisBarangSelect").value;
            google.script.run.withSuccessHandler(function (matchedRowData) {
                var matchedRowDiv = document.getElementById("matchedRow");
                matchedRowDiv.innerHTML = matchedRowData;
            }).submitData(client, tanggalDatang, jenisBarang);
        }

        // Function to handle button clicks generated by submitData function
        function handleButtonClick(rowIndex, colIndex) {
            // Implement your logic to handle button clicks here
            alert("Button clicked! Row: " + rowIndex + ", Column: " + colIndex);
        }

and this is the preview when a button clicked
https://i.stack.imgur.com/Sqgc1.png

as you see when a button clicked , it could read the spreadsheet cell name that i generate inside
but it does not submit anything to my sheet.
the log from browser console is

Uncaught ReferenceError: handleDateButtonClick is not defined
at HTMLButtonElement.onclick (userCodeAppPanel:1:1)

which part is still wrong?
thank you in advance

i tried to make a dummy button to post on designated cell, it worked,
so it wasnt premission issue

Chart JS. I have configured my x axis to show the hours of the full date in data.labels. However, it still shows the original labels below

chart.js 4.4.2
date-fns 2.30
chartjs-adapter-date-fns” 3.0.0

I wanted to truancate the x-axis as it was labeling it in a YYYY:MM:DD HH:MM:SS. I achieved that via options.scales.x.ticks and options.scales.x.time. However, I am still displaying the orignal unwanted x axis.

import 'chartjs-adapter-date-fns';
import { enUS } from 'date-fns/locale';
import { ForecastObj } from './appTypes.types';

export async function renderChart(forecast: ForecastObj[]) {
  const chartCtr = document.querySelector('#temp-chart') as HTMLCanvasElement;

  new Chart(chartCtr, {
    type: 'line',
    options: {
      animation: false,
      scales: {
        xAxis: {
          adapters: {
            date: {
              locale: enUS,
            },
          },
          type: 'time',
          ticks: {
            stepSize: 3,
            major: {
              enabled: true,
            },
          },
          time: {
            unit: 'hour',
            tooltipFormat: 'HH:mm',
          },
        },
      },
    },
    data: {
      labels: forecast.map((row) => row.date),
      datasets: [
        {
          label: 'temp every 3 hrs',
          data: forecast.map((row) => row.temp),
        },
      ],
    },
  });
}

I would like to remove the lower x axis (the original).
Results

javascript extracting floating point numbers regex are not matched properly

I’ve below javascript program –

var rx = /^the values should(?: between (d+(.d+)?) and (d+(.d+)?))$/;
var sentence = "the values should between 1.1 and 2.7";
var arr = rx.exec(sentence);
console.log(JSON.stringify(arr));

I want to extract the number 1.1 and 2.7 into into an array from the matched line.

When I run the above program I get the below result

["the values should between 1.1 and 2.7","1.1",".1","2.7",".7"]

In the above program 1.1 becomes .1 and 2.7 becomes .7.

How can I match it in javascript correctly.

How to align all elements on same axis

I am trying to align all my elements on the same axis. The element can be anything: input, dropdown, button, etc. I am trying to accomplish this using only CSS. I know we can use MUI Stack component to align them but I only want to do it via CSS. The first image below shows an example of how it currently looks, which you can see is unaligned. The second image is the expected alignment that I want. Not sure how to proceed to make it aligned?

It is not aligned

It is aligned

import * as React from "react";
import Button from "@mui/material/Button";
import TextField from "@mui/material/TextField";

export default function BasicButtons() {
  return (
    <span>
      <TextField id="standard-basic" label="Standard" variant="standard" />
      <Button variant="contained">Contained</Button>
      <Button variant="outlined">Outlined</Button>
    </span>
  );
}

Using PHP inside of CSS and JavaScript

Im trying to have a text line popup once the comment button is clicked for each line(row) dynamically.

When you click on the comment button, a line should popup under the buttons within the same row.

On DOM inspect, the lines and buttons all have unique names and id’s

I just cant get it to work as a unique event for each row.

Here is an image for reference

<div class="container-xxl flex-grow-1 container-p-y">
             
<h2 align="center"><?php echo $appname?></h2><br />
   <div class="form-group">
   <form name="add_name" id="add_name">
                    
   <div class="table-responsive">
      <table class="table table-bordered" id="dynamic_field">
         <?php while ($checks = mysqli_fetch_array($checksqry)) {
            echo '<tr>';
            echo '<td style="width: 20%">'.$checks['check_name'].' <br><br> 
            <input type="radio" class="btn-check" name="btn[' . $checks['id'] . ']" id="btnpass[' . $checks['id'] . ']" value="Pass">
            <label class="btn rounded-pill btn-outline-success" for="btnpass[' . $checks['id'] . ']">Pass</label>&Tab;&Tab;
                    
           <input type="radio" class="btn-check" name="btn[' . $checks['id'] . ']" id="btnwarning[' . $checks['id'] . ']" value="Warning">
           <label class="btn rounded-pill btn-outline-warning" for="btnwarning[' . $checks['id'] . ']">Warning</label>&Tab;&Tab;
                    
           <input type="radio" class="btn-check" name="btn[' . $checks['id'] . ']" id="btnfail[' . $checks['id'] . ']" value="Fail">
           <label class="btn rounded-pill btn-outline-danger" for="btnfail[' . $checks['id'] . ']">Fail</label>&Tab;&Tab;
                    
           <button onclick="myFunction()" type="button" name="comment[' . $checks['id'] . ']" id="comment[' . $checks['id'] . ']" class="btn btn-info" style="float: right"><img src="assets/comment.png" width="20px"></button> 
<br><br>
           <div id="commentlinediv[' . $checks['id'] . ']">
           <input type="text" class="text-line" placeholder="Type Comment Here" id="commentline[' . $checks['id'] . ']"/>
</div>
</td>';
echo '<tr>';}?>
                        
</table>
<input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />
</div>
</form>
</div>
</div>
input[type="text"] {
   border:none; /* Get rid of the browser's styling */
   border-bottom:1px solid black; /* Add your own border */
}

.text-line {
   background-color: transparent;
   color: black;
   outline: none;
   outline-style: none;
   border-top: none;
   border-left: none;
   border-right: none;
   border-bottom: solid #eeeeee 1px;
   padding: 3px 10px;
   width: 300px;
}
                
#commentlinediv[<?php echo $checks['id']?>]{
   display: none;
}
function myFunction() {
document.getElementById("commentlinediv[<?php $checks['id']?>]").style.display = "inline";
}

Map input to Key Value Pair

How do I map the vals to show be in key value pair

public getSearchHelpResult(evt: Event): void {
const vals = (evt as CustomEvent).detail;

this.showContinue = false;
[this.isGridVisible, this.showNoDataAlert] = [false, false];
this.gridColumns = [];
this.gridPayload.searchfilters = [];
this.gridPayload.appid = this.appId;
this.gridPayload.searchfield = vals.id;
this.gridPayload.searchfilters.push(vals);
console.log(vals)

right now the vals come as [{“ONE”:”9999″}] to look like this [{“id”:”ONE”,”value”:”9999″}]

I tried vals.map(val: {[key: string]: string}) => {
return {id: val.key, value: val.string}} but it didn’t work to get expected output.