How can I add a class to each option?

how can i add a class to each option? this is the PHP code, see screenshot in the description, can you help me modify this code, thanks

            <?php 
                if($params->get('cat_select_type','0')==1){
                    $cat_sel = '<select  class="inputbox" id="se'.$module->id.'_cat_0" name="se_cats[]" onchange="se'.$module->id.'_getFields(this.value);"><option value="">'.JText::_('PLEASE_SELECT_CATEGORY').'</option>';
                    foreach($categories as $cat){ 
                        $c_name = str_ireplace("'", "&apos;", $cat->name);
                        for($lev=0;$lev<$cat->level;$lev++){
                            $c_name ="- ".$c_name;
                        }                       
                        $cat_sel .= '<option value="'.$cat->id.'">'.$c_name.'</option>';
                    }
                    $cat_sel .= '</select>';
                    echo $cat_sel;
                }else{
                    $cat_sel = '<select  class="inputbox" id="se'.$module->id.'_cat_0" name="se_cats[]" onchange="se'.$module->id.'_new_cat(0,this.value,new Array());se'.$module->id.'_getFields(this.value);"><option value="">'.JText::_('PLEASE_SELECT_CATEGORY').'</option>';
                    foreach($categories[0] as $cat){
                        $cat_sel .= '<option value="'.$cat->id.'">'.str_ireplace("'", "&apos;", $cat->name).'</option>';
                    }   
                    $cat_sel .= '</select>';
                    echo $cat_sel;
                }                   
                ?>

screenshot

New component for every column in Supabase database React

I have a Supabase database called threads with 5 entries, I am trying to make a new React component for every column in the database but I am running into some issues.

The issue that it’s giving me is that it’s stopping the program to prevent an infinite loop, I’d assume this is because in my code I am updating my useState every time I render my Component which I am aware of, but I’m not sure how I would get around this problem.

Component.js:

import {useState} from "react";
import {supabase} from "../../utils/supabaseClient";

export default function Sidebar() {
    const [newThreads, setNewThreads] = useState([]);

    // this is where I am kinda stuck
    const threadList = [];
    (async () => {
        let {data: threads, error} = await supabase
            .from('threads')
            .select('thread_title');
        threadList.push(threads); // how do I get the current index of the loop (and limit it to only get 5 entries?)
        threadList.forEach(function (value) {
            console.log(value)
        })
    })();
    setNewThreads(threadList);

    return (
        <div className="sidebar">
            <div className="sidebar-widget">
                <span className="widget-title">New Threads</span>
            </div>
            <div className="sidebar-widget">
                <span className="widget-title">New Members</span>
                {(Object.entries(newThreads) || []).map(([key, value]) => {
                    return (
                        <div className="widget-cell">
                            <div className={"widget-cell-image"}/>
                            <div className="widget-cell-content">
                                <span className={"widget-cell-title"}>{value}</span>
                                <div className="widget-cell-values">
                                    <span className={"widget-cell-by-user"}>by harley_swift,</span>
                                    <span className={"widget-cell-time"}>22:02</span>
                                </div>
                            </div>
                        </div>
                    );
                })}

            </div>
        </div>
    )
}

Any help with an explanation would be greatly appreciated!

Does typescript have syntactic sugar around returning a value or throwing an exception if that value is undefined?

I find myself wanting to do something like this a lot (pseudocode):

const something = somethingElse || throw an error

This would throw an error if somethingElse were falsy. Here’s another example, written in real typescript:

const accessToken = process.env.ACCESS_TOKEN ?? throw new Error("The environment variable ACCESS_TOKEN was undefined or null");

This doesn’t compile because the right-hand side needs to be an expression. Is there a way to write code functionally equivalent to the above while being comparable in terseness?

I can do the following, but I find it obnoxious to type and it uses up a lot of vertical space:

  const accessToken = process.env.PATREON_CREATORS_ACCESS_TOKEN;
  if (accessToken === undefined) {
    throw new Error("The environment variable PATREON_CREATORS_ACCESS_TOKEN was undefined");
  }

I could also create some utility function where you pass in something potentially falsy, and if it is falsy, throw an error. But I’m wondering if typescript/javascript provides some clever syntax to pull this off so I don’t have to create such a function.

Can you set “t” tab to always be the same size in a textarea?

I have a textarea, which I am trying to insert tabs of the same size into.

As you can see in the example, the only difference in each line of the testString is the position of the t.

However, in the resulting textarea, the size of the tabs are different, seemingly dependent on how many characters are in front of it. This causes text after the tab to not be aligned properly.

In my perfect world, all of the 5s in the textarea would be aligned vertically, since each line is technically the same (five characters + one tab)

I am aware of the CSS property tab-size, and though this indeed changes the size of tabs, the resulting tab size in the textarea is still based on how many characters are in front of it.

I don’t want to insert spaces rather than tabs, because I want a single backspace/delete to remove the entire tab, but if someone enters multiple spaces in succession, I would like backspace/delete to only clear single spaces as per usual.

Is there something that I am missing? Are there any workarounds to achieve this? My research has returned no helpful results, so I am now reaching out here.

Thanks for your help.

testString = '1t2345' + 'n' + '12t345' + 'n' + '123t45' + 'n' + '1234t5'
document.getElementById('text').value = testString
<textarea cols="10" rows="4" id="text"></textarea>

Store json data into separate variables depending on category React [duplicate]

So i have this random api that generates random json data. Is there a way i can store them as variables separately based on category?
For ex:

const data = [
  { color: "red", category: "shoes", quantity: 10 },
  { color: "blue", category: "shoes", quantity: 20 },
  { color: "black", category: "jacket", quantity: 10 },
  { color: "white", category: "jacket", quantity: 20 },
  { color: "green", category: "hat", quantity: 10 },
];

I would like to have var jacket to have the data { color: "black", category: "jacket", quantity: 10 }, { color: "white", category: "jacket", quantity: 20 } then var shoes to have all the data with the category shoes and var hat to have all the hats. Note: the data is random so the color, category and quantity fields always change. Any help would be greatly appreciated.

Format post URL with multiple of the same input types

I have a form with multiple of the same input fields with the same names like this:

<form method="post" enctype="multipart/form-data">
    <input type="number" step="1" min="1" max="" name="quantity" value="1" title="Quantity" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric">
    <input type="hidden" name="add-to-cart" value="<?php echo get_the_ID(); ?>">

    <input type="number" step="1" min="1" max="" name="quantity" value="1" title="Quantity" class="input-text qty text" size="4" pattern="[0-9]*" inputmode="numeric">
    <input type="hidden" name="add-to-cart" value="<?php echo get_the_ID(); ?>">
</form>

I need my post-url to look something like this: “example.com?add-to-cart=5555,6666&quantity=5,6”.
5555 and 6666 is the data from the input field “add-to-cart”
5 and 6 is the data from the input field “quantity”.

What’s the easiest way to do this?

JavaScript – specific queried from two databases

I need help with a JavaScript task.
How do I get something specific queried from two databases?

Task:
View the index.js file
Implement the gradeOverview() function, which gets the variables students and
grades and creates a grade overview for each student. Thereby
each element in the students array should be projected to an object in the following format:
{ student: (students[i]), grades: [(grades[j], grades[j+k], …)] }

This is my function which accesses both databases and should retrieve and display a value from one database at a time based on the “student number”.

    function gradeOverview(students, grades) {
      const result = students.map((student) => [
        {
          student: student,
          grade: grades.reduce((grades, grade) => {
            const student number = grade.studentnumber;
            if (grades[matriculationnumber] == null) grades[matriculationnumber] = [];
            grades[matriculationnumber].push(grade);
            return grades;
          }),
        },
      ]);

  console.log(result);

  return result;

  // TODO: implement me
}

How to search for items in array properties? [duplicate]

I am trying to make a simple website(without CSS3) to search for items in an array. My way of accomplishing this goal is to search in the ‘title’ or ‘desc’ properties of an item in the array. My expected result is to get titleOfItem + ‘ fizz’ in the console if the title includes the keyword from the input. Instead, I get the following error:
console image & error
EDIT: I fixed this by adding a condition instead of a number in the for loop.

Here is my HTML5 code:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
    <input id="keywordText" type="text">
    <button id="submit" onclick="search()">Search</button>
    <script src="script.js"></script>
  </body>
</html>

and Here is my JS code:

const items = {
  john:{title:'john', desc:"doe", elem:document.getElementById('john')},
  jane:{title:'jane', desc:"doe", elem:document.getElementById('jane')}
}

let allItems = []
for (var key in items) {
  allItems.push(items[key])
}



function search() {
  let keyword = document.getElementById('keywordText').value;
  for (let count = 0; allItems.length; count++) {
    let titleOfItem = allItems[count].title
    if (titleOfItem.includes(keyword)) {
      console.log(titleOfItem + ' fizz')
    } else {
      console.log(titleOfItem + ' buzz')
    }
  }
}

Is there something that I am doing wrong in this code? Also, for organization purposes, is there some way to get this information straight from the first array?

Thank you for your help!

My coupon checking codewars program has an unexplained error

function checkCoupon(enteredCode, correctCode, currentDate, expirationDate) {
  const months = 'January February March April May June July August September October November December'.split(' ');
  if (enteredCode != correctCode) return false;
  
  if (Number(currentDate.split(' ')[2]) > Number(expirationDate.split(' ')[2])) return false;
  
  else if (Number(currentDate.split(' ')[2]) == Number(expirationDate.split(' ')[2])) {
    for (let x = 0; x < months.length; x++) {
      if (months[x] == currentDate.split(' ')[0]) {
        for (let y = 0; y < months.length; y++) {
          if (months[y] == expirationDate.split(' ')[0]) {
            if (x > y) return false;
            else if (x == y) {
              if (Number(currentDate.split(' ')[1].replace(',', '')) > Number(expirationDate.split(' ')[1].replace(',', ''))) return false;
              else return true;
            }
            else return true;
          }
        }
      }
    }
  }
  
  else return true;
}

I’m doing a 7 kyu codewars kata called “The coupon code” and the program I’ve made completes all of the tests except three. All 3 of them say they expected false and instead got true. I’ve tried to see the problem in my code for over 45 minutes, but haven’t made any progress because codewars doesn’t allow users to see the conditions of the tests, only the outputs. I’m aware that there is a Date object within JavaScript that I could use to remedy this problem. I intentionally opted against using this for the sake of developing problem solving skills. Does anyone have advice that could help nudge me in the right direction?

CSS transitions not visible when screen-recording using Puppeteer

I have a page where lots of large images are being resized and moved around and I am using CSS transitions for all of these actions.

When I run the page on the browser everything is working fine.

The transitions are sometimes a bit bumpy but it’s understandable given the size of the images and the large quantity so I can live with that.

However, I’m now trying to use puppeteer (headless) combined with the puppeteer-screen-recorder module and when I look at the resulting video, there are no transitions.

import puppeteer from 'puppeteer'
import { PuppeteerScreenRecorder } from 'puppeteer-screen-recorder'

const defaultViewport = {
  width: 1440,
  height: 764
}

;(() => {

  const browser = await puppeteer.launch({ defaultViewport })
  const page = await browser.newPage()
  const recorder = new PuppeteerScreenRecorder(page, {
    videoFrame: defaultViewport,
    aspectRatio: '360:191'
  })

  async function stop() {
    await recorder.stop()
    await browser.close()
    process.exit(1) 
  }

  await page.setDefaultNavigationTimeout(0)

  await page.exposeFunction('onAnimationsDone', async () => {
    stop()
  })

  await page.exposeFunction('onAnimationsStarted', () => {
    recorder.start('./client/db/test.mp4')
  })

  await page.goto('http://localhost:8000/')

})()

Is this an unavoidable limitation of using headless puppeteer or am I doing something wrong ?

Replace User Text Input In Chrome Extension

I currently have this code that will replace specific cases user input with other characters and it works in browser. However, when I try to do this in a google chrome extension, the text does not get replaced. Is there a way to make it work for chrome extensions?

$('body').on('input', 'input[name=address1]', function() {
  $(this).val($(this).val().replace('/', ' m. '));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="text" name="address1" id="address1" value=""/>

React Native route.params is undefined

I’ve been trying to pass data from my home.js screen to my merchant.js screen by using navigation.navigate(‘Merchant’, store ) but when I try to actually use route.params I get undefined.

Here’s my home.js

export default function Home( { navigation }) {
...
{storeData.map(store => {
    return (
     <View>
      <TouchableOpacity>
        <Text style={styles.categoryName}
          onPress={() => {navigation.navigate('Merchant', store)}}>
         {store.name}
        </Text>
      </TouchableOpacity>

Merchant.js

function Merchant({ navigation, route }) {
    console.log(route);
...
}

Output:

{“key”: “Merchant-86K9u5ytF32VGMRcO9s2g”, “name”: “Merchant”, “params”: undefined}

Again I have no idea what is going on. I’ve tried navigation.push(), I’ve tried using navigate(‘Merchant’, {name: store.name}) but I still get undefined.

If you would like to paste more code with my stack navigation I can.