MUI data table row selection checkbox opacity issue

In MUI Data Table I’m using first column as checkboxes as sticky.enter image description here

when I scroll horizontal to left the data is overflowing need to fix this.

enter image description here

Please find below code
Table component

import React, { useState, useEffect } from 'react';
import PropTypes from 'prop-types';
import './customtable.css';
import { styled } from '@mui/material/styles';
import {
  TableContainer,
  Table,
  TableHead,
  TableRow,
  TableCell,
  TableBody,
  Checkbox,
  IconButton,
  Button,
  Paper,
  TablePagination,
  Switch,
  FormGroup,
  FormControlLabel,
} from '@mui/material';
import { makeStyles } from '@mui/styles';
import { CSVLink } from 'react-csv';
import jsPDF from 'jspdf';
import 'jspdf-autotable';
import image from '../../assets/images/Excel.png';
import pdf from '../../assets/images/pdf.png';
import { TextDecrease } from '@mui/icons-material';
import MUIDataTable from 'mui-datatables';
import { createTheme, ThemeProvider } from '@mui/material/styles';

const getMuiTheme = () =>
  createTheme({
    components: {
      MUIDataTableToolbar: {
        styleOverrides: {
          root: {
            minHeight: '50px',
            display: 'flex',
          },
          actions: {
            display: 'flex',
            flex: 'inherit',
          },
        },
      },
      MUIDataTableBodyCell: {
        styleOverrides: {
          // padding: '10px',
          root: {
            border: 'none',
            padding: 'none',
            fontSize: '12px',
            fontFamily: 'helvetica !important',
            opacity:1,
          },
          simpleHeader: {
            // padding: '10px',
          },
          simpleCell: {
            // padding: '10px',
          },
          stackedHeader: {
            verticalAlign: 'top',
          },
          stackedCommon: {
            // padding: '10px',
          },
          stackedCommonAlways: {
            // padding: '10px',
          },
          stackedParent: {
            // padding: '10px',
          },
          stackedParentAlways: {
            // padding: '10px',
          },
          cellStackedSmall: {
            // padding: '10px',
          },
          responsiveStackedSmall: {
            // padding: '10px',
          },
          responsiveStackedSmallParent: {
            // padding: '10px',
          },
        },
      },
      MUIDataTableSelectCell: {
        styleOverrides: {
          root: {
            opacity:1,
            borderBottom: 'none',
          },

          headerCell: {
            borderBottom: '1px solid #d9d9d9',
          },
        },
      },
      MUIDataTableHeadCell: {
        styleOverrides: {
          root: {
            // borderBottom: 'none !important',
            opacity:1,
            borderTop: '1px solid #d9d9d9',
            fontSize: '14px !important',
            fontFamily: 'helvetica !important',
            fontWeight: 'bold !important',
            padding: '10px 16px 10px 16px',
            // borderRight: 'none',
          },
          toolButton: {
            fontSize: '14px !important',
            fontFamily: 'helvetica !important',
            fontWeight: 'bold !important',
          },
        },
      },
      MUIDataTableHeadRow: {
        styleOverrides: {
          root: {
            opacity:1,
            // borderBottom: 'none !important',
            borderTop: '1px solid #d9d9d9',
            fontSize: '14px !important',
            fontFamily: 'helvetica !important',
            fontWeight: 'bold !important',
            // borderRight: 'none',
          },
        },
      },
      MUIDataTableFooter: {
        styleOverrides: {
          root: {
            opacity:1,
            borderTop: 'solid 1px #dee2e6',
          },
        },
      },
      MuiTableCell: {
        styleOverrides: {
          root: {
            zIndex:1,
            opacity:1,
            color: "#000000"
          },
        },
      },
    },
  });

const useStyles = makeStyles({
  root: {
    width: '100%',
    fontSize: '12px',
    fontWeight: 400,
    fontStyle: 'helvetica',
    textAlign: 'center',
    opacity:1
  },
  container: {
    opacity:1,
    zIndex:1 

  },
});

const AntSwitch = styled(Switch)(({ theme }) => ({
  width: 28,
  height: 16,
  padding: 0,
  marginRight: 5,
  display: 'flex',
  '&:active': {
    '& .MuiSwitch-thumb': {
      width: 15,
    },
    '& .MuiSwitch-switchBase.Mui-checked': {
      transform: 'translateX(9px)',
    },
  },
  '& .MuiSwitch-switchBase': {
    padding: 2,
    '&.Mui-checked': {
      transform: 'translateX(12px)',
      color: '#fff',
      opacity:1,
      '& + .MuiSwitch-track': {
        opacity: 1,
        backgroundColor: theme.palette.mode === 'dark' ? '#177ddc' : '#9D1D27',
      },
    },
  },
  '& .MuiSwitch-thumb': {
    boxShadow: '0 2px 4px 0 rgb(0 35 11 / 20%)',
    width: 12,
    height: 12,
    borderRadius: 6,
    transition: theme.transitions.create(['width'], {
      duration: 200,
    }),
  },
  '& .MuiSwitch-track': {
    borderRadius: 16 / 2,
    opacity: 1,
    backgroundColor:
      theme.palette.mode === 'dark'
        ? 'rgba(255,255,255,.35)'
        : 'rgba(0,0,0,.25)',
    boxSizing: 'border-box',
  },
}));

const CustomTable = (props) => {
  const classes = useStyles();
  const {
    data,
    columns,
    docTitle,
    isReports,
    handleShowMoreColumns,
    showMoreColumns,
  } = props;
  const [page, setPage] = useState(0); // add state for current page
  const [rowsPerPage, setRowsPerPage] = useState(5); // add state for rows per page
  const [selectedRows, setSelectedRows] = useState([]);
  useEffect(() => {
  }, [selectedRows]);
  const handleSelectAllClick = (event) => {
    if (event.target.checked) {
      const newSelectedRows = data.map((row) => row.id);
      setSelectedRows(newSelectedRows);
    } else {
      setSelectedRows([]);
    }
  };
  const handleClick = (event, rowId) => {
    const selectedIndex = selectedRows.indexOf(rowId);
    let newSelectedRows = [];

    if (selectedIndex === -1) {
      newSelectedRows = [...selectedRows, rowId];
    } else if (selectedIndex > -1) {
      newSelectedRows = [
        ...selectedRows.slice(0, selectedIndex),
        ...selectedRows.slice(selectedIndex + 1),
      ];
    }

    setSelectedRows(newSelectedRows);
  };

  const isSelected = (rowId) => selectedRows.indexOf(rowId) !== -1;
  const selectedData = data.filter((row, index) =>
    selectedRows.includes(index)
  );
  const handleChangePage = (event, newPage) => {
    // function to handle page changes
    setPage(newPage);
  };

  const handleChangeRowsPerPage = (event) => {
    // function to handle rows per page changes
    setRowsPerPage(parseInt(event.target.value, 10));
    setPage(0);
  };
  

  const handleExportPDF = () => {
    const unit = 'pt';
    const pageSize = jsPDF.getPageSize('landscape', 'pt');
    const orientation = 'landscape';
    const marginLeft = 40;
    const doc = new jsPDF(orientation, unit, [pageSize.width, pageSize.height]);

    const headers = columns.map((column) => column.label);
    const data = [];
    selectedData.forEach((row) => {
      const rowData = [];
      columns.forEach((column) => {
        rowData.push(row[column.name]);
      });
      data.push(rowData);
    });

    let totalPages = 1;

    const content = {
      startY: 50,
      head: [headers],
      body: data,
      didParseCell: function (data) {
        data.cell.styles.cellPadding = 5;
        data.cell.styles.fontSize = 10;
        data.cell.styles.overflow = 'linebreak';
        data.cell.styles.cellHeight = 'auto';
      },
      columnStyles: {
        // Set the width of each column here
        // For example, this sets the width of the first column to 80pt
        0: { cellWidth: 80 },
      },
      // Add a hook to check the height of the table on each page
      didDrawPage: function (data) {
        const { settings, table } = data;
        const height = table.height + settings.margin.top;
        if (totalPages === 1 && height > pageSize.height / 2) {
          // Set the startY position to half the page height
          content.startY = pageSize.height / 2;
          // Add a new page and continue the table
          doc.addPage();
          // Increment the total page count
          totalPages++;
          // Draw the table again from the start row
          this.startRowIndex = 0;
          this.drawTable({ startRowIndex: this.startRowIndex });
        } else if (totalPages > 1) {
          // Increment the total page count
          totalPages++;
          // Draw the table again from the start row
          this.startRowIndex = 0;
          this.drawTable({ startRowIndex: this.startRowIndex });
        }
      },
    };

    doc.text(docTitle || 'Report', marginLeft, 40);
    doc.autoTable(content);

    doc.save(fileNamePdf);
  };

  const headers = columns.map((column) => {
    return { label: column.label, name: column.name, key: column.name };
  });

  const options = {
    filter: true,
    resizableColumns: false,
    print: false,
    download: false,
    rowHover: false,
    pagination: true,
    selectableRowsHeader: true,
    // tableBodyHeight:'320px',
    tableBodyMaxHeight: '320px',
    selectableRows: 'multiple',
    rowsPerPage: 5,
    rowsPerPageOptions: [5, 10, 20, 50, 100],
    filterType: 'textFiled',
    responsive: 'vertical',
    onRowSelectionChange: (rowsSelectedData, allRows, rowsSelected) => {
      setSelectedRows(rowsSelected);
    },
    selectToolbarPlacement: 'none',
    onRowsDelete: (rowsDeleted, newData) => {
      return false;
    },
    customToolbar: () => {
      return (
        <div style={{ display: 'flex', justifyContent: 'end' }}>
          
        
         

          <Button
            // variant="contained"
            // color="primary"
            type="button"
            style={{
              float: 'right',
              borderRadius: '12px',
              paddingTop: '3px',
              paddingBottom: '3px',
            }}
          >
            {/* Export */}
            <CSVLink
              data={selectedData}
              headers={headers}
              filename={fileNameCSV}
            >
              <img
                src={image}
                width='30px'
                height='30px'
                style={{ marginLeft: '10px' }}
              />
            </CSVLink>
            <img
              src={pdf}
              width='20px'
              height='20px'
              onClick={handleExportPDF}
              style={{ marginLeft: '10px' }}
            />
          </Button>
        </div>
      );
    },
  };

  let fileDateTime = new Date().toJSON().slice(0, 10);
  let fileName = 'Report_' + fileDateTime; //+".csv";
  let fileNameCSV = fileName + '.csv';
  let fileNamePdf = fileName + '.pdf';

  return (
    <Paper className={classes.root}>
      
      <TableContainer className={classes.container}>
        <ThemeProvider theme={getMuiTheme()}>
          <MUIDataTable className={classes.container}
            // title='Search Results'
            // components={{
            //   TableFooter: CustomFilterList,
            // }}
            data={data}
            columns={headers}
            options={options}
            // components={components}
          />
        </ThemeProvider>
      </TableContainer>
    </Paper>
  );
};
export default CustomTable;

I don’t want to see data overflows inside checkboxes when I scroll horizontal left.

Play a audio file through multiple html files

I’m making a game using a HTML and CSS because I’m still a beginner. The game is a choice based story game where you choose to what you want to do. So I use multiple HTML and CSS files to do this. But I ran into a problem when I tried to add a music to the game. The problem is that if I do the <audio> tag then the music will start the beginning. I need a way to store the data of the audio file then load it to another HTML file. If anyone has a solution to the audio let me know

React Redux , reading Redux state inside an asyncThunk?

I have two components in a React + Redux application, Parent and Children.

The workflow is: Parent component needs to make a first fetch when it’s mounted. Parent renders Child, that should provide the user to make the same exact fetch again (and again). Since Parent is subscribed to the data fetched that is stored in the Redux store, it passes such data to Child via updated props to trigger a re-renderization, and after the first fetch dispatched by the parent, all the other fetch for data are dispatched by its Child, that is going to update and re-render after each fetch completion.
These are the components:

Parent.jsx

// imports

export const Parent = () =>
{
   const dataFetched = useSelector(getRandomlyFetchedData);
   const dispatch = useDispatch();

   useEffect(() => {
     dispatch(fetchRandomData(generateRandomIndex()));  // fetchRandomData is the asyncThunk imported from the slice
     }, [dispatch]);

   return (
     <Child data={dataFetched}>
    );

}

Child.jsx

// imports

export const Child = (props) =>
{
   const dispatch = useDispatch();

   return (
     <div>
       <p>{props.dataFetched}</p>
       <button onClick={dispatch(fetchRandomData(generateRandomIndex())}>Fetch!</button> 
     </div>);
}

The situation in the store is as follows:

slice.js

import { arrayIDs } from "../arrayids";

const initialState = {
   arrayID : [...arrayID],
   dataFetchedRandomly: null,
   numberOfFetch: 0
}

export const fetchRandomData = createAsyncThunk('app/fetchRandomData',
async ({randomIndex}, { getState }) =>
{
   const response = await fetch("myurl/" + getState().arrayID[randomIndex]);
   
   // (...)

   // return randomDataFetched

}

So, I have an array stored in an external file that’s loaded into the Redux state at app initialization.

At first render of the Parent component, I want to make a fetch request that takes as a parameter a random ID picked from the array. Such fetch operation, since it’s asynchronous, must be handled by the AsyncThunk fetchRandomData(), that I dispatch at Parent’s mounting.

Now, is it an anti-pattern to access the Redux state inside the asyncThunk function to refer to the arrayID? The thunk function would receive the randomIndex as parameter, and then execute fetch:

I know the asynchThunk receives the getState as a second parameter, but I’ve always refrained from using it. I’ve always written asynchronous Thunks that never needed to access Redux state themselves.
Is there a way to abstract the state access from the thunk in my example?

I then thought about using useSelector(getArrayID) in the component that first dispatches the thunk, in order to access arrayID inside the component that calculates randomIndex, and thus dispatching the thunk with something like:

Parent.jsx alternative version

// imports

export const Parent = () =>
{
   const dataFetched = useSelector(getRandomlyFetchedData);
   const dispatch = useDispatch();

   const arrayID = useSelector(getArrayIDFromStore);

   useEffect(() => {
     dispatch(fetchRandomData(arrayID[generateRandomIndex()]));
     }, [dispatch]);

   return (
     <Child data={dataFetched}>
    );

}

But then, I would need to subscribe Child component to getArrayID with useSelector(), thus carrying my arrayID from the store into two compoennts, the Parent only using it once.

Accessing the arrayID in the store into the asyncthunk body still seems the most elegant solution to me, cause I would just need to call dispatch(fetchRandomData(generateRandomIndex())) in both components, PArent and Child.

What is the best solution?

Button Dropdown Feature – HTML/CSS

I have the following code:

document.querySelector('.rectangle')
  .addEventListener('click', function() {
    this.classList.toggle('expanded');
    const plus = this.querySelector('.plus');
    plus.style.transform = this.classList.contains('expanded') ? 'rotate(45deg)' : 'rotate(0)';
  });
.tile-container {
  padding: 5px;
  font-size: 25px;
}

.rectangle {
  background-color: #0051a5;
  padding-right: 1em;
  padding-top: 1em;
  cursor: pointer;
  border-radius: 1em;
  display: grid;
  grid-template-rows: 1fr auto;
  grid-template-columns: auto 1em;
  grid-template-areas: "sample plus" "extratext extratext";
}

.plus {
  grid-area: plus;
  background: linear-gradient(#0051a5 0 0), linear-gradient(#0051a5 0 0), #fff;
  background-position: center;
  background-size: 60% 2.5px, 2.5px 60%;
  background-repeat: no-repeat;
  transition: transform 0.3s ease;
}

.radius {
  border-radius: 50%;
  width: 1em;
  height: 1em;
  margin-right: 1em;
}

.tile-label {
  grid-area: sample;
  font-family: 'PT Sans Narrow', sans-serif;
  font-size: 1em;
  text-transform: uppercase;
  font-weight: 600;
  color: #fff;
  padding-left: 1em;
  height: 2em;
}

.tile-accent {
  color: #FFC72C;
}

.hidden-text {
  grid-area: extratext;
  display: none;
  font-family: 'PT Sans Narrow', sans-serif;
  font-size: 0.75em;
  background-color: #fff;
  color: #000;
  margin: 1em;
  padding-top: 0.5em;
  padding-left: 1em;
}

.expanded>.hidden-text {
  display: block;
   animation: fade-in 1s;
}
@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fade-out {
  from {
    opacity: 1;
  }
  to {
    opacity: 0;
  }
}
<head>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=PT+Sans+Narrow:wght@400;700&display=swap" rel="stylesheet">
</head>

<body>
  <div class="tile-container">
    <div class="rectangle">
      <div class="plus radius"></div>
      <div class="tile-label">
        Sample <span class="tile-accent">Text</span>
      </div>
      <div class="hidden-text">
        <ul>
          <li>Not Dropdown Text</li>
          <li>Dropdown Text</li>
          <li>Not Dropdown Text</li>
        </ul>
      </div>
    </div>
  </div>
</body>

In this code, the “Not Dropdown Text” represents any text which doesnt have dropdown capabilities; however, “Dropdown Text” refers to a text that can be further expanded to show hidden text.

How can I achieve the dropdown within this dropdown box? When I click the text that has further dropdown capabilities, it should display hidden text inside the box.

Jest configuration to import package in node_modules

I have a basic test for the entry App.tsx:

import * as React from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HomeScreen from './Screens/HomeScreen';
import { StudentProps, RootStackParamList } from './types/StudentInfo';

export default function App(props: StudentProps): React.JSX.Element {
  const Stack = createNativeStackNavigator<RootStackParamList>();
  return (
    <NavigationContainer>
      <Stack.Navigator initialRouteName="ReactNative">
        <Stack.Screen
          name="ReactNative"
          component={HomeScreen}
          initialParams={{ studentList: props }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

This App.tsx component retrieves props as JSON string:

Running "RNProject" with {"initialProps":{"studentList":["{"name":"John Doe","course":"Jest"}","{"name":"Jane Doe","course":"Reac Native"}"]},"rootTag":21}

App.test.tsx:

import 'react-native';
import React from 'react';
import renderer from 'react-test-renderer';
import App from '../App';


test('renders correctly', () => {
  const tree = renderer
    .create(
      <App
        appList={[
          '{"name":"John Doe","course":"Jest"}',
          '{"name":"Jane Doe","course":"React Native"}'
        ]}
      />
    )
    .toJSON();
  expect(tree).toMatchSnapshot();
});

My configuration in jest.config:

module.exports = {
  preset: "react-native",
  verbose: true,
  transformIgnorePatterns: [
    "node_modules/(?!(@react-native|react-native|@react-navigation|uuid|react-native-shared-group-preferences)/)",
  ],
};

package.json:

{
  "name": "rnproject",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "lint": "tsc --noEmit && eslint --ext .js,.jsx,.ts,.tsx",
    "lint-and-fix": "tsc --noEmit && eslint --ext .js,.jsx,.ts,.tsx --fix",
    "prettier-format": "prettier --config .prettierrc '**/*.{js,jsx,ts,tsx}' --write",
    "start": "react-native start",
    "postinstall": "npx patch-package",
    "test": "jest"
  },
  "dependencies": {
    "@react-navigation/native": "^6.1.7",
    "@react-navigation/native-stack": "^6.9.13",
    "@react-navigation/stack": "^6.3.17",
    "eslint-plugin-jsx-a11y": "^6.7.1",
    "patch-package": "^8.0.0",
    "react": "18.2.0",
    "react-native": "0.72.4",
    "react-native-get-random-values": "^1.9.0",
    "react-native-launcher-kit": "^1.0.4",
    "react-native-safe-area-context": "^4.7.2",
    "react-native-screens": "^3.25.0",
    "react-native-shared-group-preferences": "^1.1.23",
    "uuid": "^9.0.1"
  },
  "devDependencies": {
    "@babel/core": "^7.20.0",
    "@babel/preset-env": "^7.20.0",
    "@babel/runtime": "^7.20.0",
    "@jest/globals": "^29.7.0",
    "@react-native/metro-config": "^0.72.11",
    "@tsconfig/react-native": "^3.0.0",
    "@types/jest": "^29.5.5",
    "@types/react": "^18.0.24",
    "@types/react-native-shared-group-preferences": "^1.1.1",
    "@types/react-test-renderer": "^18.0.0",
    "@types/uuid": "^9.0.4",
    "@typescript-eslint/eslint-plugin": "^6.7.2",
    "@typescript-eslint/parser": "^6.7.2",
    "babel-jest": "^29.2.1",
    "eslint": "^8.49.0",
    "eslint-config-prettier": "^9.0.0",
    "eslint-plugin-prettier": "^5.0.0",
    "eslint-plugin-react": "^7.33.2",
    "eslint-plugin-react-hooks": "^4.6.0",
    "jest": "^29.2.1",
    "jest-cli": "^29.7.0",
    "metro-react-native-babel-preset": "0.76.8",
    "prettier": "^3.0.3",
    "react-test-renderer": "18.2.0",
    "ts-jest": "^29.1.1"
  },
  "engines": {
    "node": ">=16"
  }
}

When running npm run test I get the following error:

> [email protected] test
> jest


ReferenceError: You are trying to `import` a file after the Jest environment has been torn down. From __tests__/App.test.tsx.
      at Object.get BackHandler [as BackHandler] (node_modules/react-native/index.js:109:12)
      at node_modules/@react-navigation/native/lib/commonjs/useBackButton.js:50:37
      at commitHookEffectListMount (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:12999:26)        
      at commitPassiveMountOnFiber (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14422:11)        
      at commitPassiveMountEffects_complete (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14382:9)      at commitPassiveMountEffects_begin (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14369:7)   
      at commitPassiveMountEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:14357:3)
      at flushPassiveEffectsImpl (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16248:3)
      at flushPassiveEffects (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16197:14)
      at node_modules/react-test-renderer/cjs/react-test-renderer.development.js:16012:9
      at workLoop (node_modules/react-test-renderer/node_modules/scheduler/cjs/scheduler.development.js:266:34)
      at flushWork (node_modules/react-test-renderer/node_modules/scheduler/cjs/scheduler.development.js:239:14)
      at Immediate.performWorkUntilDeadline [as _onImmediate] (node_modules/react-test-renderer/node_modules/scheduler/cjs/scheduler.development.js:533:21)
  console.error
    The above error occurred in the <ForwardRef(NavigationContainerInner)> component:
    
        at NavigationContainerInner (C:GithubbcgovIASReactNativeProjectnode_modules@react-navigationnativesrcNavigationContainer.tsx:107:23)
        at App
    
    Consider adding an error boundary to your tree to customize error handling behavior.
    Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

      at logCapturedError (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8661:23)

The App.tsx component receives the JSON string containing students as props. Then, HomeScreen is called which is calling to another component Students which executes an async function. How could I allow jest to wait until the children of App component finish?

Telegram Login widget doesn’t render in React SPA app

I have a React frontend app (was bootstraped by create-react-app) and django at the backend. We have dev and production environments, they have different domains. Now I attempt to implement widget at dev env.

I want to login users via telegram login widget. I follow official core telegram docs. But button doesn’t render at login page though there is the script into DOM tree

I try to move script to , but behaviour was the same.
No errors in console

enter image description here

Regex that validates if a 6 digit string has 3 consecutive numbers i.e. 123908 [duplicate]

I’m learning Regex and I’m trying to create a regular expression that validates if there is any sequence of three consecutive numbers on a 6 digit string.

Valid string examples:
908347
212290
108763

Not valid string examples:
123709
159876
103219

I’ve tried some stuff like:

^(?!.*(d)(?=d1d(1|d)))[0-9]{6}$
^(?!.*(d)(d)(d)(?=d*321)).{6}$
^(?!.*(d)(?=d1d1))(?!.*d{3}).{6}$

But I am not getting the desired output. Either I get a valid string where it should be failing or a failing string where it should be valid.

Any ideas?

Thanks a lot in advance!

Is there a way to remove a button and then recreate it to generate different text with JavaScript?

this is my first post and I am very new with JavaScript. For an assignment, I need to create a multiple-choice quiz that has several questions. My code pulls from an array of objects and creates buttons that have the four answer options. My issue(one of them anyway), is that after answering correctly, the buttons do not disappear but rather the function adds more buttons underneath them. I’m looking to remove the created buttons in order to replace them with the next series of buttons after the question has been answered correctly. I tried the .remove method but the only way I could was by the div ID which deleted all of it and when I tried getElementsByClassName, I encountered an error. It’s definitely due to my inexperience but if anyone can help me solve this issue, I’d greatly appreciate it. I need to use vanilla JS, please no jQuery. This is what my conflicting code looks like presently after trying to experiment. If I need to supply more information, I can. Thank you!

function renderQuestion() {
    var newQuestion = document.getElementById("question");
    var newAnswers = document.getElementById("answerBtns");
        newQuestion.textContent = questions[currentQuestion].question;
        for (i = 0; i < questions[currentQuestion].answers.length; i++){
        let btnEl = document.createElement('button');
        btnEl.setAttribute("class", "btn btn-success bg-gradient btn-lg");
        btnEl.setAttribute("value", questions[currentQuestion].answers[i]);
        btnEl.textContent = questions[currentQuestion].answers[i];
        newAnswers.append(btnEl);
        btnEl.addEventListener("click", answerCheck);
        }
};


//Function to check chosen answer with answer in data

function answerCheck(btnEl) {
    // var btnEl = document.getElementsByClassName(".btn")
    if (questions[currentQuestion].correct == btnEl.target.textContent) {
        score += 1;
        console.log("Correct! You got this! Your score is " + score);
        let element = document.querySelectorAll("button");
        element.remove()
        currentQuestion++
        renderQuestion();
    } else {
        secondsLeft -= 5;
        console.log("Wrong :( Try again!");
    }

Disable Radio Button Group Depending on Prior Group

I have 2 sets of 2 radio buttons. The 2nd group should be disabled unless Yes is selected in the 1st group. However, the 2nd group needs to be cleared and disabled if the user switches from yes then selects something in group 2 and then goes back and selects no in the first group. Here is an example scenario:

HR Department is submitting a pay change request for an employee. If they select yes (there is a change) then they can select promotion or demotion. Should not be able to click yes then demotion then change to no. I’m overthinking this. Thanks

                <!-- First Pair Yes or No -->  
                <input id="rd1" name="radioGroup1" type="radio" value="Yes"> Yes</input>
                <input id="rd2" name="radioGroup1" type="radio" value="No"> No</input>
                <br>
                <!-- Second Pair To Disable If No Selected Above -->
                <input id="rd3" name="radioGroup2" type="radio" value="Promotion"> Promotion</input>
                <input id="rd4" name="radioGroup2" type="radio" value="Demotion"> Demotion</input>
                <script>
                    function fn1() {
                        if(rd1.checked==true)
                            // Enable radioGroup2 if Yes selected
                            document.getElementById("rd3").disabled = false;
                        else if(rd2.checked==true)
                            // Disable radioGroup2 if No selected
                    }
                </script>

Js compact an extended json

I have an extended json as seen below, is there a way to compact a json.

Extended:

{
  "attributes": {},
  "children": [
    {
      "attributes": {
        "ignoreBoundsFiltering": "false"
      },
      "children": [
        {
          "attributes": {
            "text": ""
          }
        }
      ]
    }
  ]
}

Compact:

{"attributes":{},"children":[{"attributes":{"ignoreBoundsFiltering":"false"},"children":[{"attributes":{"text":""}}]}]}

How to create dynamic, sequential CSS animations

I am trying to create dynamic, sequential animations that start off where the previous animation left off. The animation is simply to move left 110px but is there any way to start the next animation at 110px then move left 110px relative to that new position and keep doing this “n” times based off of some variable that can be set?

The problem is that the animation starts off with a left of “0px” so even if I retain the end position with something like animation-fill-mode it will eventually just reset the position at the start of the next animation if I use something like animation-iteration-count. I don’t know if this can be done with just HTML/CSS which is perfectly fine I just would like some insight as to how else I can do this.

@keyframes moveleft {
    0% {
        left: 0px;
    }

    100% {
        left: 110px;
    }
}

Nextjs server side permanent redirection rather 404 page

I have a Next.js app with three routes: /home, /about, and /contact.

If a user lands on a route that doesn’t exist, by default, Next.js will direct them to the 404 page.

However, I want to avoid redirecting them to the 404 page. Instead, I’d like to establish a permanent redirection to /home. This means that if someone lands on an unavailable route, they will automatically be redirected to /home.

I need to set this up from the server side in the Next.js config file. The reason for this is that I recently acquired a domain, and users are currently hitting a lot of 404 pages for URLs that used to be live. I want to minimize the number of users encountering 404 errors.

While it’s relatively straightforward to implement this when we know the specific unknown page a user might land on, without knowing the exact routes, we’ll likely need to use a regex pattern. Unfortunately, I’m struggling to figure out how to do this.

Could you please provide guidance on potential solutions or approaches to achieve this?

Capture and edit site url and use value in html django

Want to get the site url and parse the path down to the string input and then validate that string is in a django model table.

What I have done so far works in that it will display the string entered, but do not know how to then use it to compare what is in the customuser model alias_name field. If it is in the table, it should render the from in the template, if not, then it should render Sorry not found.

FYI – I am new to this and have done my due deligence it resarching this.

app/urls.py

path(‘signup/str:alias_name/’, SignUpView.as_view(), name=’accounts/signup.html’),

This allows any string to be put in here and the page renders.

app/views.py

class SignUpView(CreateView):
    form_class = CustomUserCreationForm
    success_url = reverse_lazy("login")
    template_name = "registration/signup.html"
    model = CustomUserCreationForm

app/forms.py

class CustomUserCreationForm(UserCreationForm):

    class Meta:
        model = CustomUser
        fields = (
                "first_name",
                 "last_name",
                 "email", 
                 "cell",
                 "username", 
                 'password1', 
                 'password2', 
                 'alias_name',
                 'org',
                 )

class CustomUserChangeForm(UserChangeForm):

    class Meta:
        model = CustomUser
        fields = (
                "first_name", 
                "last_name", 
                "username", 
                "email", 
                "cell", 
                )

template

<!DOCTYPE html>
<html>
<body>

{% extends "base.html" %}

{% block title %}Sign Up{% endblock %}

{% block content %}
<h2>Sign Up</h2>
  <p  id="alias"></p>

  <script> 
    document.getElementById("alias").innerText = window.location.pathname.toString().replace('/accounts/signup/', '').replace('/', '');
  </script>



  
<h1>Your sponsor is {{alias}} </h1>

  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Sign Up</button>
  </form>
{% endblock %}
</body>
</html>

How do i make div move up as the user scrolls on the page?

I want to do recreate something similar to text where the title of the film “Elimental” moves up as the user scrolls.

this is what i’m working with:

    <div id="teaser">
      <div class="row">
          <div class="col-sm" id="image-container">
              <img src="images/hd.jpg,1600" class="img-fluid">
          </div>
      </div>
  </div>

  <div id ="container" class="describe-movie">
      <div class="row">
          <div class="col-sm">
              <h1>NYUAD STARTER PACK</h1>
              <p>text here</p>
              <a class="readmore" href = "NYUAD-starter-pack.html">read more...</a>
          </div>
      </div>
  </div>

I want the “describe-movie” div to move up the page, essentially covering part of the teaser image.
Can someone please help with that?