Get text label of parent option group

This is my html:

<select id="categoryg">
<optgroup label="Main" value="binding">
<optgroup label="Sub" value="binding">
                        <option value="46">Test</option>
                        <option value="47">Test2</option>
                        <option value="48">Test3</option>
</optgroup>
</select>

Whenever I change the selection I want to get the label text of the parent option group “Main”.

At the moment my code just gets the label text of the sub parent option group “Sub”.

This is my code (JSFiddle):

$('select').change(function () {

   var opt = $(this).find(':selected');
   var sel = opt.text();
   var og = opt.closest('optgroup').attr('label');
   
   console.log(og) // Sub, should get Main;

});

Binding list value by id in javascript

I have list as shown in the below figure. Grouping is already done based on ID. Now i need to add Select All to the list for all the groups and then need to change the label name of INCLUDE ALL STUDENTS to REMOVE ALL STUDENTS if all items in group are selected and from REMOVE ALL STUDENTS to INCLUDE ALL STUDENTS .

How can i do this

List Data

Tried with

for(i=0;i<res.length;i++){

}
grd.load(List);

How to prevent two filters from overwriting each other on my website using JavaScript

Desperately need help with my js code

So basically I have been trying to resolve this problem for more than 15! hours. I know that it shouldn’t be that hard, but still here I am. I tried to do it a lot of ways but failed. If you help me correct my code i would be forever grateful because im starting to lose my sanity.
So basically I have 2 filters on website. First filter – buttons where i can select genders Second – job Type

  typeOfGender.forEach((li) => {
    li.addEventListener("click", () => {
      li.classList.toggle("filter-header-selected");
      removeJob2();
    });
  });
  typeOfWork.forEach((li) => {
    li.addEventListener("click", () => {
      li.classList.toggle("filter-footer-selected");
      removeJob();
    });
  });

So i toggle class there to know what is selected. Nothing wrong so far.

  function removeJob() {
    let CheckedJobs = [];
    let difference = [];
    //type of work
    document.querySelectorAll(".filter-footer-selected p").forEach((pHtml) => {
      arrayOfClickableJobs.forEach((job) => {
        if (pHtml.innerHTML == job[1]) CheckedJobs.push(job);
      });
      difference = arrayOfClickableJobs.filter(
        (element) => !CheckedJobs.includes(element)
      );
    });
    //
    CheckedJobs.forEach((x) => {
      x[0].setVisible(true);
    });
    difference.forEach((x) => {
      x[0].setVisible(false);
    });
    if (difference.length === 0) {
      arrayOfClickableJobs.forEach((x) => {
        x[0].setVisible(true);
      });
    }
  }
  function removeJob2() {
    let CheckedJobs = [];
    let difference = [];
    //type of work
    document.querySelectorAll(".filter-header-selected").forEach((pHtml) => {
      arrayOfClickableJobs.forEach((job) => {
        if (job[2].includes(pHtml.innerHTML.match(/[А-Яа-я]/)[0].toLowerCase()))
          CheckedJobs.push(job);
      });
      difference = arrayOfClickableJobs.filter(
        (element) => !CheckedJobs.includes(element)
      );
    });

    //
    CheckedJobs.forEach((x) => {
      x[0].setVisible(true);
    });
    difference.forEach((x) => {
      x[0].setVisible(false);
    });
    if (difference.length === 0) {
      arrayOfClickableJobs.forEach((x) => {
        x[0].setVisible(true);
      });
    }
  }

arrayOfClickableJobs – is array of all jobs on website. This 2 functions basically the same. I create array of selected buttons Than I iterate through them and iterate through all the jobs to find a match and push matched jobs in CheckedJobs array.
difference – is opposite of CheckedJobs, it has all the job that is not the match. Than as you can see i show all the jobs i selected and hide other. If I use only one filter – this code works perfectly fine, but if I use two it breaks. If i want to find Women – it will show every women and hide everything. But if select Women and than select in another filter teacher – it will show all teachers regardless of gender – second filter that i use overwrite first. I would be very grateful If someone helped me with this. I wasted a lot of time on this code but cant figure out how to connect this two filters…

Is there something better than useContext for passing general props?

I’m trying to re build an app that I started working with React, but now using Next JS. The way I passed props between components was by prop drilling in react. Now, with Next JS app directory I’m able to create a general layout for the page. The problem here is that what i want as general layout, a header and a left sidebar, need to be able to create elements in a main component, which is nested inside the layout.
To make what I’m trying to do in Next I need to pass props from the left sidebar to the main container. According to the Next JS 13 documentation, it is not possible to pass props from the layout to children components. I read and made a little investigation, and I came to the conclusion that using contexts would be the best approach, but I’m new with this, so is this the best way to go?

Extras (in case you need to know):
-Language: Typescript (TS, TSX)

How to mark checkboxes in a list backward, numerically descending?

I am generating a list from a database using PHP. Each line is numbered in ascending order and contains a checkbox. If you select one, all checkboxes above it, numerically descending, should also be selected.

I have already tried various things, but it does not work.
Here is the code in a shortened form:

<table id="mySEARCH" class="shoppinglist-content">
<!-- ******************************************************************************** shopping list beginn-->
    <!-- script test start -->
    <?php
        if(isset($_COOKIE['shoppinglist'])){
            $list = $_COOKIE['shoppinglist'];
            $stmt = $pdo->prepare("SELECT * FROM `$list`");
            $stmt->execute();
            $x = 0;
            foreach($stmt as $item)
            { $x++;?>
                <tr id="line<?php echo $x;?>" style="opacity: 1.0;">
                <td class="split-list"><input type="checkbox" id="split-list-<?php echo $x;?>" name="split-list" onchange="markAbove<?php echo $x;?>()" value="<?php echo $x;?>"></td>
                </tr>
                <script>
                    function markAbove<?php echo $x;?>(){
                        var choosedLine = document.querySelectorAll("input[type=checkbox]");
                        for(var i = <?php echo $x;?>; i > choosedLine.value; i--){
                            choosedLine.setAttribute("checked", "");
                        }
                        console.log(i);
                    }
                </script>
            <?php
            }
        }else {
/******************************************************************************** shopping list end****/
            ?><tr><td></td><td></td><td>Keine Items vorhanden</td><td></td><td></td><td></td><td></td></tr><?php
        }
    ?>
<!-- script test end -->
</table>

enter image description here

Does anyone have a tip on how this can work?

Several separate promises with linked then(s)

I don’t understand the order in which tasks are sent to the microtasks queue.
I expected this output: 1, 11, 111, 2, 3, 12, 122
But received: 1, 11, 111, 2, 12, 122, 3
Does compiler register the whole chain or it can see only the next then?
How does it work?

Promise.resolve()
  .then(() => console.log(1))
  .then(() => console.log(2))
  .then(() => console.log(3));

Promise.resolve()
  .then(() => console.log(11))
  .then(() => console.log(12));

Promise.resolve()
  .then(() => console.log(111))
  .then(() => console.log(122));

Adding 20 works but subtracting 20 doesn’t – how can I fix my Javascript code for an Ecommerce website?

I’m trying to build an Ecommerce website. When you click/check a varietion it adds 20 on the total price 100. But when you uncheck the varietion it doesn’t minus on the total price. Please help me I’ve been trying this for months and it just won’t work.

Here’s my code:

<div id="total">500</div>
    
    <input onclick="addTwenty()" id="checkbox1" type="checkbox">R20</input>

    <script>

        let total = document.getElementById("total");
        let twenty = document.getElementById("checkbox1");

        function addTwenty(){
            total = 500;
            twenty = 20;
            if (twenty.checked = true){
                document.getElementById("total").innerHTML = total + twenty;
            } else{
                document.getElementById("total").innerHTML = total - twenty;
            }
        }
        
    </script>

I used If statements. When true, it adds value of 20 on 500, which is 520. But when unchecked it doesn’t minus 20. I want it to minus the same value it added when it’s now unchecked.

Cypress.config.js file is invalid

I have detailed test cases for automation using Cypress. When I run command npx cypress open I can see error which says Your ConfigFile is invalid.

I have retried to run npm init -y command and reinstalled the Puppeeteer API as well but still showing same error.

form input array to php

I am trying to insert child names and child birthdays depending how many child does the user have. However, I am having trouble passing the array of child names and its birthdays.

form:

<label for="child_name[]">Name of Children: (Fullname) Child 1:</label>
<input  type="text" name="child_name[]">
<label for="child_birthday[]">Birthday:</label>
<input type="date" name="child_birthday[]">
<button type="button" onclick="addTextbox()"> Add Child</button>
<button type="button" onclick="removeTextbox()">
Remove Child</button>

Script:

<script>
    var counter = 1;
    function addTextbox() {
        counter++;
        var newTextbox = document.createElement('div');
        newTextbox.innerHTML = '<div class="form-row"><div class="form-group col-md-6"><label for="child_name[]' + counter + '">Child ' + counter + ':</label>' + '<input class="form-control" type="text" id="child_name[]' + counter + '" name="child_name[]" ></div>' + '<div class="form-group col-md-6"><label for="child_birthday[]' + counter + '">Birthday:</label>' + '<input class="form-control" type="date" id="child_birthday[]' + counter + '" name="child_birthday[]" ></div></div>';
        document.getElementById('textboxContainer').appendChild(newTextbox);
    }

    function removeTextbox() {
        if (counter > 1) {
            document.getElementById('textboxContainer').removeChild(document.getElementById('textboxContainer').lastChild);
            counter--;
        }
    }
</script>

Php:

$totalChildren = count($childNames);


$sql3 = "INSERT INTO children (employeeid, child_name, child_birthday) VALUES (?, ?, ?)";
$stmt = $conn->prepare($sql3);
$stmt->bind_param("iss", $employeeid, $childName, $childBirthday);

for ($i = 0; $i < $totalChildren; $i++) {
  $childName =  $childNames[$i];
  $childBirthday = $childBirthdays[$i];


  $stmt->execute();
}
$stmt->close();
print_r($_POST['child_name']);

sample:input values
result: result

Expecting to pass and upload the values of childnames and its birthdays.

HTML file with Javascript – Python

I really need help with this. I have to read thousands of HTML files to extract values to a dataset but the HTM file has javascrip and pandas is getting me the name of the variable instead of the value.The code I have used is very simple, use pandas to read it and then look for the tables it found.
I will share a link for the HML file, and the code and an image of the value I am trying to get.
Thank you.

url = "https://raw.githubusercontent.com/OperationsMD/powermill/main/Project_Summary.html"
import pandas as pd

df_mill = pd.read_html(url)
print(df_mill[2])

And I get: 0 verificar tempo when I should get: Tempo Total: 03:09:09 that I show in the image.

enter image description here

Trouble Sending to CWOP over TCP Sockets via Cloudflare Workers

Cloudflare Workers now have the ability to connect directly over TCP sockets. I want to use this feature to send an APRS packet to CWOP.

I have the following function in my code:

export async function sendPacket(packet, server, port) {

  console.log('Opening connection to ' + server + ':' + port);

  const socket = connect({ "hostname": server, "port": port });
  const writer = socket.writable.getWriter();
  const reader = socket.readable.getReader();
  const encoder = new TextEncoder();
  
  // Wait for server's initial message - http://www.wxqa.com/faq.html
  let initialMessage = await reader.read();
  console.log('Received from server: ', new TextDecoder().decode(initialMessage.value));

  // Send login line
  const id = packet.split('>')[0];
  const loginLine = 'user ' + id + ' pass -1 vers cwop.rest 0.1rn';
  console.log('Sending to server: ', loginLine);
  let encoded = encoder.encode(loginLine);
  await writer.write(encoded);

  // Wait for server's acknowledgement
  let { value, done } = await reader.read();
  console.log('Received from server: ', new TextDecoder().decode(value));

  // Send packet
  console.log('Sending to server: ', packet);
  encoded = encoder.encode(packet + 'rn');
  await writer.write(encoded);

  writer.close();
  reader.releaseLock();
  
  let serverResponse = new TextDecoder().decode(value);
  console.log('Received from server: ', serverResponse);

  console.log('Closing connection to ' + server + ':' + port);
  
  return new Response(serverResponse, { "headers": { "Content-Type": "text/plain" } });
  
}

The log shows the following:

Opening connection to rotate.aprs.net:14580
worker.js:15 Received from server:  # aprsc 2.1.5-g8af3cdc
worker.js:20 Sending to server:  user K9ZOG pass -1 vers cwop.rest 0.1
worker.js:26 Received from server:  # logresp K9ZOG unverified, server NINTH
worker.js:29 Sending to server:  K9ZOG>APRS,TCPIP*:@181242z4246.58N/0866.22W_119/001g001t048r000p000h64b09968L162appsscriptforwarder
worker.js:37 Received from server:  # logresp K9ZOG unverified, server NINTH
worker.js:39 Closing connection to rotate.aprs.net:14580

This has been running every five minutes for over a day now, but my data is still not showing up on findu, aprs.fi, cwopviewer.com, etc. Any ideas what might be going wrong?

Why does .splice(i*2+1,1) break my code in a for loop, but .splice(i*2,1), doesn’t, while also failing?

var kept = [0,0,1,1,2,2];
for (i = 0; i<kept.length/2; i) {
    kept.splice(i*2+1,1);
    console.log(kept);
}

I expect this code to return [0,1,2], but instead, my page freezes. I’ve tested it on multiple sites, and it seems to not freeze when I use kept.splice(i*2,1), but when I use that, the splice weirdly removes 2 values at a time instead of the indicated 1, returning an empty array… please help!

React Hook Form value not set for one of the fields

I am using React-Hook-Form to render multiple fields (via child components)
I also have defaultValues defined for all the fields

My Form is as below;

<Form 
    defaultValues={props.defaultValues}
    validationSchema={mySchema}
    ref={formRef}
>

I instantiate the individual fields as below;

<Field key={firstNameFieldOutside.id} field={firstNameFieldOutside} />

My field config passed to the generic Field component is as below;

{
    "id": "first-name-field-outside",
    "mandatory": true,
    "visible": true,
    "maxLength": 20,
    "items": {},
    "value": "FName Outside",
    "disabled": false,
    "hidden": false,
    "fieldLabel": "Test Field Outside",
    "regex": "^[a-zA-Z0-9]+[a-zA-Z0-9\s]{0,50}$|^$",
    "editable": true
}

In my generic Field component, I have

return (
        <>
            <Input 
                label={labelText} 
                name={field.id}
                inputProps={{
                    maxLength: field.maxLength
                }}
                disabled={field.disabled}
                required={field.mandatory}
                autoComplete="off"
            />
        </>
);

Now, I can see all the input fields rendered in the DOM.

But for some reason, for one of the fields firstNameFieldOutside, I cannot see “value” being set. Other attributes like maxlength are applied for this field.

Other difference I observed while debugging for this field specifically while using React Dev Tools (Components tab), when I select InputBase,
I see Ref as false (under hooks)

The Ref is true for all the other fields.

Please help me why I am not seeing “value” set only for this field.

Importing HTML file into a JS file on Localhost

I am currently making an extension for Scratch. For that, I have to run it on the localhost. Now, The main file of the extension is index.js, in that file when I try to import other js files it works fine but the problem arises when I try to import an HTML file. MY version of the code snippet is this:

div = document.createElement('div');
var btn = document.createElement('button');
btn.textContent = 'Close';
btn.onclick = function(){
    div.remove();
}
btn.style.margin = '10px';
var content = document.createElement('div');
content.style.width = '100%';
content.style.height = '100%';
content.style.backgroundColor = 'white';
var iframe = document.createElement('iframe');
// iframe.src = './node_modules/scratch-vm/src/extensions/scratch3_tsp/new.htm';

const path = require('path');
const filePath = path.join(__dirname, 'node_modules', 'scratch-vm', 'src', 'extensions', 'scratch3_tsp', 'new.htm');
iframe.src = filePath;

content.appendChild(iframe);
div.id = 'tsp_viz';
div.style.position = 'absolute';
div.style.width = '500px';
div.style.height = '500px';
div.style.zIndex = '1000';
div.style.backgroundColor = 'red';
div.style.top = '10%';
div.style.left = '30%';
div.style.borderRadius = '10px';
div.appendChild(btn);
div.appendChild(content);

The directory to the file is: “C:UsersUbaid ul AkbarDesktopResearchDevelopmentscratch-guinode_modulesscratch-vmsrcextensionsscratch3_tspnew.htm”. The file only contains some dummy text, nothing special.
And I am running the Node Js in the “scratch-gui” directory. And I tried renaming the file to new.html and new.htm, is there something I am missing?