CMAKE running Javascript utility

I’m working on a project in C/C++ buildable with cmake…
During build process I’ve to build configurations (headers and sources) based on some configuration file written in json format.

I reached the prefixed result adopting a script file in javascript and in the cmake I placed this command:

add_custom_target( BuildStructure ALL node ${CMAKE_CURRENT_SOURCE_DIR}/util/buildProjectStructCfg.js ...)

Ok, it is working fine but…

Is a portable solution ?

Is it possible to try better solutions ?

I adopted javascript because to handle json files for me is the best…

Thank you

How to access nested json object inside array in react js

I want to access nested JSON object values by iterating. This is the data I get from my query:

{"_id":"654d4224fb04863b8eb89200","firms":[{"_id":["65423d5c240388c1594e7b7b"],"name":["Camaro Coiled Tubing"]}]}
{"_id":"654d4224fb04863b8eb8920d","firms":[{"_id":["65423d5c240388c1594e7b82"],"name":["DANCO Coiled Tubing"]}]}
{"_id":"654d4224fb04863b8eb8921b","firms":[{"_id":["65423d5c240388c1594e7b7d"],"name":["San Joaquin Bit"]}]}

I would like to create a second array with only the firm and name and have tried the following:

      vendorList.forEach(function (d) {
        vendorArray.push({
          id: d.firms._id,
          name: d.firms.name,
        });
      });

My output looks like this:

Vendor List:  [{}, {}, {}, {}]

An empty array.

How can I position a div fixed relative to the body, when it’s inside a fixed parent div?

I’m currently working on a CSS layout where I have a fixed parent div containing another div. I want the inner div to be fixed relative to the body, not its parent.

Code (Tailwind):

<div class="h-screen bg-red-100">
  <div class="fixed left-1/2 top-1/2 h-80 w-80 -translate-x-1/2 -translate-y-1/2 bg-red-300">
    <div class="fixed top-10 h-40 w-40 bg-red-600">I want to make this div fixed relative to body</div>
  </div>
</div>

Tailwind Playground

Is there a way to achieve this without JavaScript? If not, how can I accomplish it using JavaScript?

I’ve also researched extensively and searched on Stack Overflow, but I couldn’t find a solution that fits my exact requirements.

Thank you!

+1(909) 233-7696 / How to withdraw, transfer, or sending from Coinbase Bank Account?

In today’s digital age, cryptocurrencies have become a popular investment option for many. Coinbase, one of the leading cryptocurrency exchange platforms, offers users a secure and straightforward way to manage their crypto assets. One common question that arises among Coinbase users is how to withdraw money from their Coinbase account to their bank account. This article provides a comprehensive guide on the process, including information on fees and other important considerations.

Step-by-Step Guide to Withdrawing Money from Coinbase / Call Now: +1(909) 233-7696

• Log in to Your Coinbase Account: Start by logging into your Coinbase account on the website or mobile app.
• Navigate to the Portfolio Page: Once logged in, go to the “Portfolio” page to view your assets.
• Select the Asset to Withdraw: Choose the cryptocurrency you want to cash out. If it’s not in a fiat currency like USD, you’ll need to convert it to a fiat currency first.
• Click on ‘Withdraw’: Find the “Withdraw” button next to the selected asset and click on it.
• Enter the Withdrawal Amount: Type in the amount you wish to withdraw. Make sure you have enough funds to cover any withdrawal fees.
• Choose Your Bank Account: Select the bank account you want to transfer the funds to. If you haven’t linked a bank account yet, you’ll need to do so at this stage.
• Review and Confirm: Double-check the withdrawal details, including the amount and destination bank account. Confirm the transaction to initiate the withdrawal process.
• Wait for Processing: Withdrawals can take several business days to process. The exact time frame depends on your bank and the payment method used.

How to Cash Out Crypto from Coinbase / Call Now: +1(909) 233-7696

To cash out cryptocurrency from Coinbase, follow these steps:
• Log In: Sign in to your Coinbase account.
• Portfolio: Go to your “Portfolio” page.
• Select Crypto: Find the cryptocurrency you want to cash out and click on it.
• Sell: Click on the “Sell” button.
• Enter Amount: Enter the amount of cryptocurrency you want to sell.
• Preview Sell: Review the details of your transaction, then click “Preview Sell.”
• Confirm: If everything looks correct, confirm the sale.
• Withdraw: After selling your cryptocurrency, the cash will be available in your Coinbase fiat currency wallet. You can then withdraw it to your linked bank account.

How to Transfer Money from Coinbase / Call Now: +1(909) 233-7696

To transfer money from your Coinbase wallet to another wallet or exchange, follow these steps:
• Log In: Sign in to your Coinbase account.
• Portfolio: Go to your “Portfolio” page.
• Select Asset: Choose the cryptocurrency you want to transfer.
• Send: Click on the “Send” button.
• Recipient Address: Enter the recipient’s wallet address or scan their QR code. Make sure the address is correct to avoid losing funds.
• Amount: Enter the amount you want to send.
• Continue: Click “Continue” to review the details of your transfer.
• Confirm: After reviewing, confirm the transaction. You may need to complete a two-factor authentication process.

How to Send Money from Coinbase to Bank Account / Call Now: +1(909) 233-7696

To send money from your Coinbase account to your bank account, follow these steps:
• Log In: Sign in to your Coinbase account.
• Portfolio: Go to your “Portfolio” page.
• USD Wallet: Click on your USD Wallet (or the fiat currency wallet you used to sell your crypto).
• Withdraw: Click on the “Withdraw” button.
• Enter Amount: Enter the amount of money you want to withdraw.
• Select Bank Account: Choose the bank account you want to withdraw to. If you haven’t linked a bank account yet, you’ll need to do so.
• Withdraw: Review the details and confirm the withdrawal.

Understanding Fees and Limits

When withdrawing money from Coinbase, it’s important to be aware of the fees and limits that apply. Coinbase charges a fee for each withdrawal, which varies depending on the payment method and the amount being transferred. Additionally, there are daily and weekly withdrawal limits that restrict the amount of money you can move out of your account within a certain period. These limits can vary based on factors such as your account level and verification status.

Frequently Asked Questions (FAQs)

How long does it take to withdraw money from Coinbase to a bank account?
Withdrawal times can vary, but it typically takes 1-3 business days for the funds to appear in your bank account.

Are there any fees for withdrawing money from Coinbase?
Yes, Coinbase charges a fee for withdrawals. The fee amount depends on the payment method and the currency being withdrawn.

Can I withdraw money from Coinbase to any bank account?
You can withdraw money to any bank account that is linked to your Coinbase account and supports the currency you are withdrawing.

Is there a minimum amount for withdrawing money from Coinbase?
Yes, there is a minimum withdrawal amount, which varies depending on the currency and payment method.

What should I do if my withdrawal from Coinbase is delayed?
If your withdrawal is taking longer than expected, check the status of the transaction in your Coinbase account. If the status is ‘Pending,’ the transaction is still being processed. If it’s been several days and the status hasn’t changed, contact Coinbase support for assistance.

Conclusion
Withdrawing money from Coinbase to your bank account is a straightforward process, but it’s important to be mindful of the fees, limits, and processing times involved. By following the steps outlined in this guide and understanding the associated costs, you can smoothly transfer your funds from Coinbase to your bank account.

How to overcome Right Click is Not allowed by website using puppeteer?

I have a website i want to crawl data using puppeteer where the right click is disabled for the website.

Here i have included the code, which submits the form to open in new page.But when the puppeteer click it is showing “Right Click is Not allowed”

How do i overcome this problem.

Its a submit form not a href so i cant do page.goto(url).

 await Promise.all([
          page.waitForNavigation({ timeout: 0 }),
          await page.keyboard.down('Control'),
          // Wait for the new page to load
          await page.click('input[type="submit"][name="formsearch"]', {
            button: 'right',
          }), // Click the button with id "id24"
          await page.keyboard.up('Control'),
        ])

I tried using the page.keyboard.down

How to get a JavaScript script to stay within its designated element?

Pretty much what it says on the tin.

I have a JS script that isn’t staying within the div element it is designated to on my page, it “sits” in the footer section instead.
Page design with the JS script result “sitting” in the footer

<header>

    <div>icon</div>
    <div>header</div>
    <div style="padding:5px;">
    script is supposed to go here
        <script src="JS/SpinningBaton.js"></script>
    </div>
  
</header>

That’s how I currently have the HTML block written in an attempt to resolve the issue. Unfortunately, nothing has changed. What am I doing to wrong?

For context, the div element is 165px in size while the JS script is 155px, so it should fit without overflow.

I have tried putting the script within different elements within the div and resizing the div element. But the script defiantly stays in the footer area regardless of what I have tried so far.

Import a module in a dynamically created module (node, browsers)

I am successfully importing a dynamically created module using this construct:

const binString = Array.from(new TextEncoder().encode(moduleText), (byte) => String.fromCodePoint(byte)).join("");
const url = 'data:text/javascript;base64,' + btoa(binString);
var mod2 = await import(/* webpackIgnore: true */ url);

Works both in Node and in Chrome.

However, if I import some static module in that dynamic module, node says:

node:internal/errors:496
    ErrorCaptureStackTrace(err);
    ^

TypeError [ERR_INVALID_URL]: Invalid URL
    at new NodeError (node:internal/errors:405:5)
    at new URL (node:internal/url:778:13)
    at getPackageScopeConfig (node:internal/modules/esm/package_config:14:24)
    at packageResolve (node:internal/modules/esm/resolve:736:25)
    at moduleResolve (node:internal/modules/esm/resolve:831:20)
    at defaultResolve (node:internal/modules/esm/resolve:1036:11)
    at DefaultModuleLoader.resolve (node:internal/modules/esm/loader:251:12)
    at DefaultModuleLoader.getModuleJob (node:internal/modules/esm/loader:140:32)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:76:33)
    at link (node:internal/modules/esm/module_job:75:36) {
  input: './package.json',
  code: 'ERR_INVALID_URL'
}

How it can be fixed?

Modal won’t hide

The modal is designed to appear when there is an empty filled that has no value except some input fields. It shows up, yes, but after clicking OK, It won’t hide.

I did some troubleshoot but nothing really happened. Any advise or help would be appreciated.

                <!--Required Fields modal -->
      <div id="requiredFieldsModal" class="hidden fixed flex top-0 left-0 w-full h-full items-center justify-center bg-black bg-opacity-50">
          <div class="bg-white p-5 rounded-lg text-center">
              <h2 class="mb-4">Please fill in all required fields.</h2>
              <button id="confirmFill" class="mr-2 px-4 py-2 bg-yellow-400 hover:bg-yellow-500 text-white rounded">OK</button>
          </div>
      </div>

      <script>
        document.addEventListener('DOMContentLoaded', () => {
          const form = document.querySelector('form');
          const inputs = form.querySelectorAll('input');
          const requiredFieldsModal = document.querySelector('#requiredFieldsModal');
          const confirmFill = document.querySelector('#confirmFill');

          form.addEventListener('submit', (event) => {
            console.log('Form submitted'); // Add this line to check if the code is being triggered

            let hasEmptyField = false;

            inputs.forEach((input) => {
              if (input.value.trim() === '' && input.name !== 'email' && input.name !== 'contactNumber' && input.name !== 'endOfEmployment') {
                hasEmptyField = true;
              }
            });

            if (hasEmptyField) {
              event.preventDefault();
              requiredFieldsModal.classList.remove('hidden');
            }
          });

          confirmFill.addEventListener('click', () => {
            requiredFieldsModal.classList.add('hidden');
          });
        });
      </script>

how to find sum of input value in javascript

Can anyone help me to find sum of input values using JavaScript. The HTML and JavaScript is given below. Thanks in advance

let inputs=document.getElementsByTagName('input');
let button=document.querySelector('button');

button.addEventListener('click',function(){
let sum='';
for(let i=0;i<inputs.length;i++){
sum+=parseInt(inputs[i].value);
}
console.log(sum);
})
<input type="text">
<input type="text">
<button>Find Sum</button>

React deploying as blank screen, in locally works fine

my react app git repo link = “https://github.com/MuhdSHiBiLi/employee-front.git”
this is my host llink = “https://muhdshibili.github.io/employee-front/” it only gives a blank screen as output

how to solve this issue. am also added the home pages and deploy scripts on package.jsom. doesnt work
am tried to resolve by removing browser rote from app.js and add hash route, but no change still same blank screen in this

Yarn patches keep coming back even though I removed them?

I tried using Yarn 2+’s native patches, but they had a lot of problems, so I removed the native patches and switched back to patch-package. I deleted all the resolutions from my package.json, removed all the “patch:” packages, and deleted the .yarn/patches folder. I thought this would remove all the native patches.

However, every time I run yarn install, I get:

➤ YN0000: ┌ Fetch step
➤ YN0066: │ typescript@patch:typescript@npm%3A5.4.3#optional!builtin<compat/typescript>::version=5.4.3&hash=e012d7: Cannot apply hunk #8
➤ YN0000: │       /*preferSymlinks*/
➤ YN0000: │       true,
➤ YN0000: │       (path, isRedirect) => {
➤ YN0028: │ -       const isInNodeModules = pathContainsNodeModules(path);
➤ YN0028: │ +       let isInNodeModules = pathContainsNodeModules(path);
➤ YN0028: │ +       const pnpapi = getPnpApi(path);
➤ YN0028: │ +       if (!isInNodeModules && pnpapi) {
➤ YN0028: │ +         const fromLocator = pnpapi.findPackageLocator(importingFileName);
➤ YN0028: │ +         const toLocator = pnpapi.findPackageLocator(path);
➤ YN0028: │ +         if (fromLocator && toLocator && fromLocator !== toLocator) {
➤ YN0028: │ +           isInNodeModules = true;
➤ YN0028: │ +         }
➤ YN0028: │ +       }
➤ YN0000: │         allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect, isInNodeModules });
➤ YN0000: │         importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
➤ YN0000: │       }

It looks like it’s trying to apply native Yarn patches. I’m not referencing typescript@patch:typescript@npm%3A5.4.3#optional!builtin<compat/typescript>::version=5.4.3&hash=e012d7 anywhere in my project. I’m patching Typescript using patch-package, whereas this string looks like it came from Yarn 2+’s native patch. I tried removing yarn.lock and re-generating it, but it appears in yarn.lock again:

"typescript@patch:typescript@npm%3A^5.4.2#optional!builtin<compat/typescript>":
  version: 5.4.3
  resolution: "typescript@patch:typescript@npm%3A5.4.3#optional!builtin<compat/typescript>::version=5.4.3&hash=e012d7"
  bin:
    tsc: bin/tsc
    tsserver: bin/tsserver
  checksum: 1b50712759f1e4bf4bf6fe7e662235358b716972dec8aa9ca117dee531dbd7b417f5fe28f74d347b4447eec09a200c0372fe9cf1aad2e15a2bcf4a1a99db0820
  languageName: node
  linkType: hard

I also tried yarn cache clean and removing node_modules, but it keeps coming back.

What’s going on here? Is this my old patch from yarn patch and I didn’t fully remove it? Or was it possibly added by a package?

How to get OAuth2 Access token from Postman

I have some requests to an API using OAuth2 so I config like the picture below.

Here I configured the authentication to be OAuth 2.0 in the collection and all the requests will be able to access the API properly. This works well

enter image description here

Now I need to decode the access token to get some user’s information so that I can customize the request. But I don’t know how to receive the access token from OAuth2

I found pm.request.auth but seem it doesn’t work because the Authentication of the request is inherited from the parent (collection). Same, I see the access token is set in the header but the header is generated by Postman so I can’t get it here

enter image description here

Can someone help me on this?

Thanks.

Recreating the schedule in the image using HTML, CSS, or Javascript

The schedule I wanna recreate

I need help on how can I recreate this schedule with CSS, HTML, and Javascript all three combined. I’m having a hard time on how can I fit or split three blank table cells into one part of the table data. For example, the 7:00 – 8:00 time period has three table data cells all aligned and fitted with the other cells in the following days, Tuesday, Wednesday, Thursday, and Friday. Thanks in advance! 🙂

This is my code here, apologies for the very shit, and disorganized code. I am planning on cleaning it once I understand how I recreate the table.

    <style>

th {
    border: none;
    color: black; /* Text color */
    padding: 8px;
    text-align: center;
  }

  .cell1 {
    background-color: #006400; /* Green */
  }

  .cell1wd1 {
  height: 2px;
  width: 20px;
  padding: 2px 4px; /* Adjust top and bottom padding */
  font-size: 10px; /* Adjust font size if needed */
  white-space: nowrap; /* Prevent text wrapping */
}

  .cell2 {
    background-color: #FFBEC8; /* Green */
  }

  .cell3 {
    background-color: #808080; /* Green */
  }

    </style>
  <table cellspacing="1">

<tr>   
     
    <thead>
        <th>
        Time
        </th>

        
        
        <th class="cell1">
            Monday
            <tr>
                <tbody>
                    <td>
                        7:00 - 8:00
                            <th class="cell1">
                            </th>
                        </tr>
                    </td>
                </tbody>    
                <td>
                <th class="cell1">
                </th>
                </td>
            </tr>
            <tr>
                <td>
                <th class="cell1">
                </th>
                </td>
            </tr>
            
        </th>   
</tr>




    <th>
    <td>
    <th class="cell2">
        Tuesday
    </th>
    </td>
</th>

    <th class="cell3">
        Wednesday
    </th>

    <th class="cell1">
        Thursday
    </th>

    <th class="cell2">
        Friday
    </th>

</tr>

<tr>
    <td>
        7:00 - 8:00<br>

        <td>
        <th class="cell2">
        </th>
        </td>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>


<tr>
    <td>
        8:00 - 9:00<br>
        
        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        9:00 - 10:00<br>

        <th class="cell1">
            CMSC 132
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        10:00 - 11:00<br>

        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        11:00 - 12:00<br>

        <th class="cell1" class="cell1wd1">
            a
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        12:00 - 1:00<br>
        
        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        1:00 - 2:00<br>

        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        2:00 - 3:00<br>

        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        3:00 - 4:00<br>

        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        4:00 - 5:00<br>

        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>

<tr>
    <td>
        5:00 - 6:00<br>

        <th class="cell1">
        </th>

        <th class="cell2">
        </th>

        <th class="cell3">
        </th>

        <th class="cell1">
        </th>
    </td>

    <th class="cell2">
    </th>
</tr>
    
</table>

</table>
</body>

Unhandled Runtime Error TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

I am making a multiselect component in Next.js and I am using states and setting states. But this error occurs: enter image description here Whenever I click this: enter image description here

Below is the code of MultiSelect.tsx:



import { useState } from "react";

import {
  Command,
  CommandDialog,
  CommandEmpty,
  CommandGroup,
  CommandInput,
  CommandItem,
  CommandList,
  CommandSeparator,
  CommandShortcut,
} from "@/components/ui/command";

interface MultiSelectProps {
  placeholder: string
  collections: CollectionType[]
  value: string[]
  onChange: (value: string) => void
  onRemove: (value: string) => void
}

const MultiSelect: React.FC<MultiSelectProps> = ({
  placeholder,
  collections,
  value,
  onChange,
  onRemove,
}) => {
  const [inputValue, setInputValue] = useState("");
  const [open, setOpen] = useState(false);

  return (
    <Command className="overflow-visible bg-white">
      <CommandInput
        placeholder={placeholder}
        value={inputValue}
        onValueChange={setInputValue}
        onBlur={() => setOpen(false)}
        onFocus={() => setOpen(true)}
      />
      <div className="relative mt-2">
        {open && (
          <CommandGroup className="absolute w-full z-10 top-0 overflow-auto border rounded-md shadow-md">
            {collections.map((collection) => (
              <CommandItem key={collection._id}>{collection.title}</CommandItem>
            ))}
          </CommandGroup>
        )}
      </div>
    </Command>
  );
};

export default MultiSelect;

Also, pasting here the code from the ProductForm.tsx:

"use client";

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { Separator } from "../ui/separator";
import { z } from "zod";
import { Button } from "@/components/ui/button";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Textarea } from "../ui/textarea";
import ImageUpload from "../custom ui/ImageUpload";
import { useParams, useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import toast from "react-hot-toast";
import Delete from "../custom ui/Delete";
import MultiText from "../custom ui/MultiText";
import MultiSelect from "../custom ui/MultiSelect";

const formSchema = z.object({
  title: z.string().min(2).max(20),
  description: z.string().min(2).max(500).trim(),
  media: z.array(z.string()),
  category: z.string(),
  collections: z.array(z.string()),
  tags: z.array(z.string()),
  size: z.array(z.string()),
  colors: z.array(z.string()),
  price: z.coerce.number().min(0.1),
  expense: z.coerce.number().min(0.1),
});

interface ProductFormProps {
  initialData?: ProductType | null; // Must have ? to make it optional
}

const ProductForm: React.FC<ProductFormProps> = ({ initialData }) => {
  const router = useRouter();
  //const params = useParams();

  const [loading, setLoading] = useState(false);
  const [collections, setCollections] = useState<CollectionType[]>([]);

  const getCollections = async () => {
    try{
      setLoading(true)
      const res = await fetch("/api/collections", {
        method: "GET",
      })
      const data = await res.json()
      setCollections(data)
      setLoading(false)
    }catch(err) {
      console.log("[collections_GET]", err)
      toast.error("Something went wrong. Please try again.")
    }
  }

  useEffect(() => {
    getCollections()
  }, [])

  // 1. Define your form.
  const form = useForm<z.infer<typeof formSchema>>({
    resolver: zodResolver(formSchema),
    defaultValues: initialData
      ? initialData
      : {
          title: "",
          description: "",
          media: [],
          category: "",
          collections: [],
          tags: [],
          sizes: [],
          colors: [],
          price: 0.1,
          expense: 0.1,
        },
  });

  const handleKeyPress = (
    e:
      | React.KeyboardEvent<HTMLInputElement>
      | React.KeyboardEvent<HTMLTextAreaElement>
  ) => {
    if (e.key === "Enter") {
      e.preventDefault();
    }
  };

  // 2. Define a submit handler.
  const onSubmit = async (values: z.infer<typeof formSchema>) => {
    // Do something with the form values.
    // ✅ This will be type-safe and validated.
    //console.log(values)
    try {
      setLoading(true);
      const url = initialData
        ? `/api/products/${initialData._id}`
        : "/api/products";
      const res = await fetch(url, {
        method: "POST",
        body: JSON.stringify(values),
      });
      if (res.ok) {
        setLoading(false);
        toast.success(`Product ${initialData ? "updated" : "created"}.`);
        window.location.href = "/products";
        router.push("/products");
      }
    } catch (err) {
      console.log("[products_POST]", err);
      toast.error("Something went wrong. Please try again.");
    }
  };

  return (
    <div className="p-10">
      {initialData ? (
        <div className="flex items-center justify-between">
          <p className="text-heading2-bold">Edit Product</p>
          <Delete id={initialData._id} />
        </div>
      ) : (
        <p className="text-heading2-bold">Create Product</p>
      )}
      <Separator className="bg-grey-1 my-4 mb-7" />
      <Form {...form}>
        <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
          <FormField
            control={form.control}
            name="title"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Title</FormLabel>
                <FormControl>
                  <Input
                    placeholder="Title"
                    {...field}
                    onKeyDown={handleKeyPress}
                  />
                </FormControl>
                <FormDescription>The title of the product.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="description"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Description</FormLabel>
                <FormControl>
                  <Textarea
                    placeholder="Description"
                    {...field}
                    rows={5}
                    onKeyDown={handleKeyPress}
                  />
                </FormControl>
                <FormDescription>
                  The description of the product.
                </FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <FormField
            control={form.control}
            name="media"
            render={({ field }) => (
              <FormItem>
                <FormLabel>Image</FormLabel>
                <FormControl>
                  <ImageUpload
                    value={field.value}
                    onChange={(url) => field.onChange([...field.value, url])}
                    onRemove={(url) =>
                      field.onChange([
                        ...field.value.filter((image) => image !== url),
                      ])
                    }
                  />
                </FormControl>
                <FormDescription>The image of the product.</FormDescription>
                <FormMessage />
              </FormItem>
            )}
          />
          <div className="md: grid md:grid-cols-3 md:gap-8">
            <FormField
              control={form.control}
              name="price"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Price ($)</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      placeholder="Price"
                      {...field}
                      onKeyDown={handleKeyPress}
                    />
                  </FormControl>
                  <FormDescription>The price of the product.</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="expense"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Expense ($)</FormLabel>
                  <FormControl>
                    <Input
                      type="number"
                      placeholder="Expense"
                      {...field}
                      onKeyDown={handleKeyPress}
                    />
                  </FormControl>
                  <FormDescription>The expense of the product.</FormDescription>
                  <FormMessage />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="category"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Category</FormLabel>
                  <FormControl>
                    <Input
                      placeholder="Category"
                      {...field}
                      onKeyDown={handleKeyPress}
                    />
                  </FormControl>
                  <FormMessage className="text-red-1" />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="tags"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Tags</FormLabel>
                  <FormControl>
                    <MultiText
                      placeholder="Tags"
                      value={field.value}
                      onChange={(tag) => field.onChange([...field.value, tag])}
                      onRemove={(tagToRemove) =>
                        field.onChange([
                          ...field.value.filter((tag) => tag !== tagToRemove),
                        ])
                      }
                    />
                  </FormControl>
                  <FormMessage className="text-red-1" />
                </FormItem>
              )}
            />
            <FormField
              control={form.control}
              name="collections"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>Collections</FormLabel>
                  <FormControl>
                    <MultiSelect
                      placeholder="Collections"
                      collections={collections}
                      value={field.value}
                      onChange={(_id) => field.onChange([...field.value, _id])}
                      onRemove={(idToRemove) =>
                        field.onChange([
                          ...field.value.filter((collectionId) => collectionId !== idToRemove),
                        ])
                      }
                    />
                  </FormControl>
                  <FormMessage className="text-red-1" />
                </FormItem>
              )}
            />
          </div>
          <div className="flex gap-10">
            <Button type="submit" className="bg-blue-1 text-white">
              Submit
            </Button>
            <Button
              type="button"
              onClick={() => router.push("/collections")}
              className="bg-blue-1 text-white"
            >
              Discard
            </Button>
          </div>
        </form>
      </Form>
    </div>
  );
};

export default ProductForm;

When clicking the multiselect component it should show the current collection list.

Print The Receipt Only Using PHP or JS

So I am just learning php and creating a OPG Clinic Management System as my first project. I am not watching any tutorials or reading books I am learning on the go. For example I didn’t know what CRUD is until I needed to implement that in the System.

Right Now I am facing an issue where I am unable to print only the receipt section and not the page like I don’t want the even the top parts of the page where they show the title of page number btw I don’t have receipt printer to test in yet.

So I want to print only section within this border. but some how I keep seeing a entire page on the print window and it’s probably going to print the entire thing.

Now I don’t wanna using some PHP framework to it for me, I want to keep the whole vanilla.

I tried a few answers on StackOverFlow where they were using JS but they are still showing the whole page, I even removed the headers and footer from the page, but I see the page title and number on the print window. I don’t want all this white space titles and other description.