Css-Doodle svg update with angular

Context : I am in typical and classic Angular project and trying to import the css doodle library.

I am currently looking to use the css-doodle library in an angular project. There is not much documentation mixing the Angular framework with the CSS-Doodle library. Fortunately, it is possible and can be done as I found in this example:
https://stackblitz.com/edit/angular-rvf8rg?file=src%2Fapp%2Fapp.component.html

However, there are a lot of others examples that use CSS-Doodle WITHOUT Angular. My problem is that I would like to use this next effect that I found but that is not IN Angular:
https://codepen.io/yune/pen/ZEGbypB.

In the JS there is the use of the Id doodle but in my Angular project I can’t get the update() function even though I tried to use a #doodle selector that I added on the element like that :

<css-doodle #doodle use="var(--rule)" id="doodle" click-to-update></css-doodle>

and in my ts I try something like that :

export class AppComponent implements OnInit {
  title = 'sandbox';
  @ViewChild('doodle') doodle: any;

  ngOnInit(): void {
    setInterval(() => {this.doodle.update()}, 4000)
  }
}

But I get an error like this.doodle.update is not a function. Does anyone have a clue to help me or has anyone already used update from CSS-Doodle in Angular or uses a derivative way to do it?

Uncaught (in promise) TypeError: Failed to fetch in signup page

It’s my first time asking a question here and so I may sound “green” on matters tech.

So, I’ve been developing a MERN-stack e-commerce project and while setting up the signup page, this is the error that I have experienced as shown in the title.See screenshot attached for the error display on Inspect Console

Here is the code for the signup page:

import React, { useState } from "react";
import loginSignupImage from "../assets/login-animation.gif";
import { BiShow, BiHide } from "react-icons/bi";
import { Link, useNavigate } from "react-router-dom";
import { BsEmojiSmileUpsideDown } from "react-icons/bs";
import { ImagetoBase64 } from "../utility/ImagetoBase64";
import { toast } from "react-hot-toast";

function Signup() {
  const navigate = useNavigate();
  const [showPassword, setShowPassword] = useState(false);
  const [showConfirmPassword, setShowConfirmPassword] = useState(false);
  const [data, setData] = useState({
    firstName: "",
    lastName: "",
    email: "",
    password: "",
    confirmPassword: "",
    image : ""
  });
  console.log(data);
  const handleShowPassword = () => {
    setShowPassword((preve) => !preve);
  };
  const handleShowConfirmPassword = () => {
    setShowConfirmPassword((preve) => !preve);
  };

  const handleOnChange = (e) => {
    const { name, value } = e.target;
    setData((preve) => {
      return {
        ...preve,
        [name]: value,
      };
    });
  };

  const handleUploadProfileImage = async(e)=>{
      const data = await ImagetoBase64(e.target.files[0])
      console.log(data)

      setData((preve)=>{
          return{
            ...preve,
            image : data
          }
      })

  }
console.log(process.env.REACT_APP_SERVER_DOMAIN)
  const handleSubmit = async(e) => {
    e.preventDefault();
    const { firstName, email, password, confirmPassword } = data;
    if (firstName && email && password && confirmPassword) {
      if (password === confirmPassword) {
          console.log(data)
          const fetchData = await fetch(`${process.env.REACT_APP_SERVER_DOMAIN}/signup`,{
            method : "POST",
            headers : {
              "content-type" : "application/json"
            },
            body : JSON.stringify(data)
          })

          const dataRes = await fetchData.json()
          console.log(dataRes)

        alert(dataRes.message);
        toast(dataRes.message)
        if(dataRes.alert){
          navigate("/login");
        }
       
      } else {
        alert("password and confirm password not equal");
      }
    } else {
      alert("Please enter required fields");
    }
  };

  return (
    <div className="p-3 md:p-4">
      <div className="w-full max-w-sm bg-white m-auto flex  flex-col p-4">
        {/* <h1 className='text-center text-2xl font-bold'>Sign up</h1> */}
        <div className="w-20 h-20 overflow-hidden rounded-full drop-shadow-md shadow-md m-auto relative ">
          <img src={data.image ? data.image :  loginSignupImage} className="w-full h-full" />

          <label htmlFor="profileImage">
            <div className="absolute bottom-0 h-1/3  bg-slate-500 bg-opacity-50 w-full text-center cursor-pointer">
              <p className="text-sm p-1 text-white">Upload</p>
            </div>
            <input type={"file"} id="profileImage" accept="image/*" className="hidden" onChange={handleUploadProfileImage}/>
          </label>
        </div>

        <form className="w-full py-3 flex flex-col" onSubmit={handleSubmit}>
          <label htmlFor="firstName">First Name</label>
          <input
            type={"text"}
            id="firstName"
            name="firstName"
            className="mt-1 mb-2 w-full bg-slate-200 px-2 py-1 rounded focus-within:outline-blue-300"
            value={data.firstName}
            onChange={handleOnChange}
          />

          <label htmlFor="lastName">Last Name</label>
          <input
            type={"text"}
            id="lastName"
            name="lastName"
            className="mt-1 mb-2 w-full bg-slate-200 px-2 py-1 rounded focus-within:outline-blue-300"
            value={data.lastName}
            onChange={handleOnChange}
          />

          <label htmlFor="email">Email</label>
          <input
            type={"email"}
            id="email"
            name="email"
            className="mt-1 mb-2 w-full bg-slate-200 px-2 py-1 rounded focus-within:outline-blue-300"
            value={data.email}
            onChange={handleOnChange}
          />

          <label htmlFor="password">Password</label>
          <div className="flex px-2 py-1 bg-slate-200 rounded mt-1 mb-2 focus-within:outline focus-within:outline-blue-300">
            <input
              type={showPassword ? "text" : "password"}
              id="password"
              name="password"
              className=" w-full bg-slate-200 border-none outline-none "
              value={data.password}
              onChange={handleOnChange}
            />
            <span
              className="flex text-xl cursor-pointer"
              onClick={handleShowPassword}
            >
              {showPassword ? <BiShow /> : <BiHide />}
            </span>
          </div>

          <label htmlFor="confirmpassword">Confirm Password</label>
          <div className="flex px-2 py-1 bg-slate-200 rounded mt-1 mb-2  focus-within:outline focus-within:outline-blue-300">
            <input
              type={showConfirmPassword ? "text" : "password"}
              id="confirmpassword"
              name="confirmPassword"
              className=" w-full bg-slate-200 border-none outline-none "
              value={data.confirmPassword}
              onChange={handleOnChange}
            />
            <span
              className="flex text-xl cursor-pointer"
              onClick={handleShowConfirmPassword}
            >
              {showConfirmPassword ? <BiShow /> : <BiHide />}
            </span>
          </div>

          <button className="w-full max-w-[150px] m-auto  bg-green-500 hover:bg-green-600 cursor-pointer  text-white text-xl font-medium text-center py-1 rounded-full mt-4">
            Sign up
          </button>
        </form>
        <p className="text-left text-sm mt-2">
          Already have account ?{" "}
          <Link to={"/login"} className="text-red-500 underline">
            Login
          </Link>
        </p>
      </div>
    </div>
  );
}

export default Signup;

The error is in line 58: const fetchData = await fetch(${process.env.REACT_APP_SERVER_DOMAIN}/signup,{

Further error description details are as attached in the screenshot below:
Details from Network tab on Inspect Console

Any leads would be highly appreciated.
Regards.

Initially, I had thought the failure to include

“proxy”: “http://localhost:8080” in the frontend’s package.json file was the issue and so included it after

“scripts”: {
“start”: “react-scripts start”,
“build”: “react-scripts build”,
“test”: “react-scripts test”,
“eject”: “react-scripts eject”
},

but it did not turn out as expected.

Any assistance accorded and counsel offered would be highly appreciated.

Add / remove class from array of elements at once, adding and removing active class to menu items without Jquery

I’m working on a one-pager ([https://rnp.mijnbaron.be/]) and I’m trying to add / remove an active class to the menu items if clicked. I already got 1 part working (adding), but I’m struggling with how to remove the active class from the element, if another menu item is clicked.
And preferably without use of jquery.

Here’s what I’ve got so far:

"use strict";

// Select all scrollable links

const scrollEls = document.querySelectorAll(".scroll a");

// For each scrollEL add eventlistener and function if clicked

for (let i = 0; i < scrollEls.length; i++) {
  scrollEls[i].addEventListener("click", function () {

    if (!scrollEls[i].classList.contains("active")) {
      scrollEls[i].classList.add("active");
    } else {

      scrollEls[i].classList.remove("active");
    }
  });
}

I have tried resetting all active items (removing active class) after the click event by using every, but this does not work. Maybe my thought process is wrong 🙂

In rsuitejs, how to make the ‘active’ tag inside Nav.Item conditional?

Consider the following:

<Sidenav defaultOpenKeys={['2']}>
                <Sidenav.Header>
                    <div style={headerStyles}>Custom Sidenav</div>
                </Sidenav.Header>
                <Sidenav.Body>
                    <Nav>
                    <Nav.Item eventKey="1" active icon={<DashboardIcon />} href="/dashboard">{t('Dashboard')}</Nav.Item>
                    <Nav.Menu eventKey="2" title={t("Statistic Data")} icon={<MagicIcon />}>
                        <Nav.Item eventKey="2-2" href="/newplayerstatistic/level">{t('New Player Level Statistic')}</Nav.Item>
                        <Nav.Item eventKey="2-3" href="/newplayerstatistic/chapter">{t('New Player Chapter Statistic')}</Nav.Item>
                        <Nav.Item eventKey="2-4" href="/currentplayerstatistic/level">{t('Current Player Level Statistic')}</Nav.Item>
                        <Nav.Item eventKey="2-4" href="/currentplayerstatistic/chapter">{t('Current Player Chapter Statistic')}</Nav.Item>
                    </Nav.Menu>
                    </Nav>
                </Sidenav.Body>
            </Sidenav>

In eventKey=”1″, what is the active tag called? And how do I make it condiional such that it only active when its true, ie {condition ? ‘active’: ”}. Apperently it is not a string and I cannot set active=true/false.

Node.js Sequelize: Cannot delete property ‘meta’ of [object Array]

I’m learning the Sequelize.js framework and it’s pretty awesome. But when I try to remove a column from my test tables in in my migration file, I get this error:

ERROR: Cannot delete property 'meta' of [object Array]

This error occurs when I use the removeColumn function from the query interface but I don’t have an idea why …

My migration file:

'use strict';

const {DataTypes} = require("sequelize");
/** @type {import('sequelize-cli').Migration} */
module.exports = {
  async up (queryInterface, Sequelize) {
    return queryInterface.sequelize.transaction(t => {
      return Promise.all([
        queryInterface.removeColumn('Students', 'bloodStatus', {transaction: t}),
      ]);
    });
  },

  async down (queryInterface, Sequelize) {
    return queryInterface.sequelize.transaction(t => {
      return Promise.all([
        queryInterface.addColumn('Students', 'bloodStatus', {
          type: DataTypes.STRING,
          allowNull: false
        }, {transaction: t}),
      ]);
    });
  }
};

I used the migration file above but I get the error

ERROR: Cannot delete property 'meta' of [object Array]

I read the documentation and tried to find a solution, but unfortunately I can’t find one.

How to add in a node.js existing project the “jwt token” fonctionnality?

I am a junior dev on JavaScript in Nodejs. I am currently working on an internal api project in my company but the security problem is becoming important. I’m currently hesitating between two modes of operation to set up security via “jwt token”:

-The first would be to simply redo the code of my api and integrate this functionality into it, but that would take a lot of time I guess I have about 13 calls currently operational on the api.

-The second option would be to use a “boilerplate” to have a clean and functional architecture but to start the project from scratch.
**
What is the best solution?**

Currently I have not tried anything, I am only informing myself. I already found a git-hub directory I could use: https://github.com/hagopj13/node-express-boilerplate

.map() to ignore values in array

How to make .map() ignore values in array. In script below values in column B and C of dstSheet are erased when running script. I want to keep it. How to modify this script?

function dorozliczenia() {
  
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const srcSheet = ss.getSheetByName("arkusz 1");
  const dstSS = SpreadsheetApp.openById("1bjqauqiyEzUkECaxqswRmOQPYWydpSAvLf97t5ovbXQ");
  const dstSheet = dstSS.getSheetByName("arkusz 1");

  const obj = Object.fromEntries(srcSheet.getRange("A2:C" + srcSheet.getLastRow()).getValues().map(([a, , c]) => [c, a]));
  const dstRange = dstSheet.getRange("A2:D" + dstSheet.getLastRow());
  const values = dstRange.getValues().map(([, , , a]) => [obj[a] ? true : false,null ,null , a]);
  dstRange.setValues(values);
}

Here are the spreadsheets:

https://docs.google.com/spreadsheets/d/1bjqauqiyEzUkECaxqswRmOQPYWydpSAvLf97t5ovbXQ/ https://docs.google.com/spreadsheets/d/11ZVtFJ5Ul5nUu3PLxUu_xBlfS0bbeAWRj8-ZKwKUTG8/

Is it possible to get current charset of OS in broswer for JavaScript?

Rencently I’m using lingala/zip4j lib to handle .zip files uploaded by users.
It seems that UTF-8 would be the default charset for reading inside file structure.
This will cause exceptions if a .zip file is compressed in a OS not running UTF-8 as default charset.

Seems that CharsetDetector of Apache Tika cannot detect correct charset of filename String of FileHeader instances too.

So is it possible to detect default charset of user OS (not the charset of loaded HTML) for JavaScript running in browser?

MUI TextField select value not updating in React component

I am building a form in a React component that allows users to edit student information. I am using Material-UI’s TextField and Select components to create a dropdown menu for selecting a student’s gender.

The issue I’m facing is that the selectedOption state variable, which is used to keep track of the currently selected gender option, is not being updated properly. When logging the value of selectedOption, it always appears to be empty.

Here is my code:

const EditStudentForm = () => {
    // Use
    const [currentStudent, setCurrentStudent] = useState<Student>({
        id: -1,
        name: '',
        email: '',
        gender: ''
    });

    const studentById = useRecoilValue(studentByIdState);
    const formState = useRecoilValue(editStudentFormState);

    // Gender Select
    const [selectedOption, setSelectedOption] = useState<string>('');

    useEffect(() => {
        if (formState) {
            setCurrentStudent(studentById);
            setSelectedOption(currentStudent.gender);
        }
    }, [studentById, currentStudent]);



    const handleOptionChange = (event: React.ChangeEvent<{ value: unknown }>) => {
        setSelectedOption(event.target.value as string);
    }

    const selectProps: SelectProps = {
        MenuProps: {
            anchorOrigin: {
                vertical: "bottom",
                horizontal: "left"
            },
            transformOrigin: {
                vertical: "top",
                horizontal: "left"
            }
        }
    };


    return (
        <>
            <CssBaseline />
            <Box
                sx={{ width: 320 }}
                role="user-form"
            >
                <Typography variant="h4" color="initial" sx={{ mt: 3, textAlign: 'center' }}>Edit student</Typography>
                <form>
                    <Stack sx={{ m: 2 }} spacing={2}>
                        <TextField
                            id="studentName"
                            label="Student name"
                            value={currentStudent.name}
                            variant='outlined'
                            focused={true}
                        //   onChange={}
                        />
                        <TextField
                            id="studentEmail"
                            label="Student email"
                            value={currentStudent.email}
                            variant='outlined'
                        //   onChange={}
                        />
                        <TextField
                            id="studentGender"
                            label="Student Gender"
                            defaultValue={''} // to avoid MUI: You have provided an out-of-range value
                            value={selectedOption}
                            onChange={handleOptionChange}
                            select
                            SelectProps={selectProps}
                            variant='outlined'
                        >
                            <MenuItem key={1} value={'male'}>
                                Male
                            </MenuItem>
                            <MenuItem key={2} value={'female'}>
                                Female
                            </MenuItem>
                            <MenuItem key={3} value={'other'}>
                                Other
                            </MenuItem>
                        </TextField>
                        <Stack direction="row" spacing={2} sx={{ justifyContent: 'end' }}>
                            <Button variant="outlined" color="primary">
                                Reset
                            </Button>
                            <Button variant="contained" color="primary">
                                Add
                            </Button>
                        </Stack>
                    </Stack>
                </form>
            </Box>
        </>
    )
}

export default EditStudentForm;

with code provided above I get from as:

form image showing TextField Select as empty

I have tried many solutions from SO, but none has worked.
What am I doing wrong? Any help would be appreciated. Thanks!

Calculate and plot Ellipses on scatter plot. Working but right?

I’m working on a react app with a scatter plot from react-chartjs-2. I’ve created some helper functions to calculate and draw 95% confidence interval ellipses on the chart. So far, so good.

It is mostly working well (at least from a visual point of view), but at times, I get some odd results – take the blue item below. The rotation seems off as you could fit all the blue items in a slightly smaller, but rotated, ellipse.

I’ve put the code below and happy to provide more info if anyone can help either:

  1. explain why this result makes sense or
  2. help me figure out how to adjust my approach to get better results.

Thanks!

Ellipses on Scatter Plot

const calculateEllipse = (points, xAxis, yAxis) => {
  const n = points.length;
  const xMean = points.reduce((sum, p) => sum + p.x, 0) / n;
  const yMean = points.reduce((sum, p) => sum + p.y, 0) / n;

  let a = 0;
  let b = 0;
  let c = 0;
  points.forEach((p) => {
    const xPixel = xAxis.getPixelForValue(p.x) - xAxis.getPixelForValue(xMean);
    const yPixel = yAxis.getPixelForValue(p.y) - yAxis.getPixelForValue(yMean);
    a += xPixel * xPixel;
    b += xPixel * yPixel;
    c += yPixel * yPixel;
  });

  a /= n;
  b /= n;
  c /= n;

  const d = Math.sqrt((a - c) * (a - c) + 4 * b * b);
  const e1 = (a + c + d) / 2;
  const e2 = (a + c - d) / 2;

  const angle = (a > c ? Math.atan2(b, a - e1) : Math.atan2(c - e1, b)) / 2;

  const scaleFactor = 2.4477; // Scaling factor for a 95% confidence ellipse

  return {
    x: xAxis.getPixelForValue(xMean),
    y: yAxis.getPixelForValue(yMean),
    a: Math.sqrt(e1) * scaleFactor,
    b: Math.sqrt(e2) * scaleFactor,
    angle,
  };
};


const ellipsePlugin = {
  id: "ellipse",
  afterDatasetsDraw: function (chart, args, options) {
    const ctx = chart.ctx;
    const show = chart.options.plugins.ellipse.show;
    const chartArea = chart.chartArea; // get the chart area

    const xAxis = chart.scales.x;
    const yAxis = chart.scales.y;
    if (show) {
      chart.data.datasets.forEach((dataset, index) => {
        if (chart.isDatasetVisible(index)) {
          const ellipseData = calculateEllipse(dataset.data, xAxis, yAxis);
          ctx.save();

          // check if any part of the ellipse is outside the chart area
          if (
            ellipseData.x - ellipseData.a <= chartArea.right &&
            ellipseData.x + ellipseData.a >= chartArea.left &&
            ellipseData.y - ellipseData.b <= chartArea.bottom &&
            ellipseData.y + ellipseData.b >= chartArea.top
          ) {
            // draw only if the ellipse is completely inside the chart area
            ctx.beginPath();
            ctx.translate(ellipseData.x, ellipseData.y);
            ctx.rotate(ellipseData.angle);
            ctx.scale(ellipseData.a, ellipseData.b);
            ctx.arc(0, 0, 1, 0, 2 * Math.PI);
            ctx.restore();

            ctx.strokeStyle = dataset.borderColor;
            ctx.lineWidth = 2;
            ctx.stroke();
          }
        }
      });
    }
  },
};

How to prevent dropdown mini-cart(cart-preview.html) after clicking on cart icon in bigcommerce cornerstone theme?

If i try to click inside the dropdown div it is closing automatically. I am trying to close the dropdown div when it is clicked outside the div. How to prevent it when click clicking inside the dropdown div? I need to prevent the dropdown because i am going to implement product quantity update implementation.

Where is the code that toggles the mini-cart? Demo link https://cornerstone-light-demo.mybigcommerce.com/

I have tried preventDefault() on clicking the dropdown container. But it was not working.

Material UI Navbar Dropdown List

I am currently trying to add an icon on my navbar that on click would drop down a list of notifications. I have found multiple code examples for drop-down menus but I haven’t been able to use those to assist me or found any list-specific examples. Here is my current code with the menu application:

 const [auth, setAuth] = React.useState(true);
  const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setAuth(event.target.checked);
  };

  const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };


<div
        className="nav-links"
      >
        <IconButton
          size="large"
          aria-label="account of current user"
          aria-controls="menu-appbar"
          aria-haspopup="true"
          onClick={handleMenu}
          color="inherit"
        >
          {/* <NotificationsIcon /> */}
          <Avatar sx={{ bgcolor: deepOrange[500] }}>{user.displayName[0].charAt(0).toUpperCase()}</Avatar>
        </IconButton>
        <Menu
          id="menu-appbar"
          anchorEl={anchorEl}
          anchorOrigin={{
            vertical: 'center',
            horizontal: 'center',
          }}
          keepMounted
          transformOrigin={{
            vertical: 'center',
            horizontal: 'center',
          }}
          open={Boolean(anchorEl)}
          onClose={handleClose}
        >
          <MenuItem onClick={handleClose}>Profile</MenuItem>
          <MenuItem onClick={handleClose}>My account</MenuItem>
        </Menu>
      </div>

Navbar with icon

Navbar with icon clicked

I would like a list (elements not clickable) to dropdown once the icon is clicked.

Thank you!

I got a ‘SyntaxError: Unexpected token “<", "<!DOCTYPE"'

I use react and try to post.
The error I receive is SyntaxError: Unexpected token ‘<‘, “<!DOCTYPE ” it’s happening then I put this line of code : const json = await response.json();
From that I understood it’s the response sending me a HTML instead of JSON(not sure).

If I delete that line of code this time I get a 500 internal server error
Response {type: ‘cors’, url: ‘http://localhost:3000/api/post/’, redirected: false, status: 500, ok: false, 
}
body
:
ReadableStream
bodyUsed
:
false
headers
:
Headers {}
ok
:
false
redirected
:
false
status
:
500
statusText
:
“Internal Server Error”
type
:
“cors”
url
:
“http://localhost:3000/api/post/”
[[Prototype]]
:
Response

My body is in ReadableStream the error could be here but when I check my code I stringify before sending. So I’m confused.

 const handleSubmit = async (e) => {
    e.preventDefault();
    // Récupérer les données du formulaire
    const title = e.target.title.value;
    const description = e.target.description.value;
    const data = { title, description };

    try {
      // Envoyer les données au backend avec la méthode POST
      const url = "http://localhost:3000/api/post/";
      const response = await fetch(url, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: "Bearer " + localStorage.getItem("token"),
          // authorization doit ettre ds headers
        },
        body: JSON.stringify(data),
        // Authorization: `Bearer ${authCtx.token}`
      });

      const json = await response.json();
      // VĂ©rifier si la requĂȘte a Ă©tĂ© traitĂ©e avec succĂšs
      if (response.ok) {
        // Fermer la fenĂȘtre modale
        console.log(json);
        console.log("response ok");
        handleCloseModal();
        // Actualiser la page pour afficher le nouveau post
        window.location.reload();
      } else {
        console.log(response);
      }
    } catch (error) {
      console.log(error);
      if (error.response && error.response.status === 401) {
        console.log("Erreur 401 : authentification requise");
      }
    }
  };

  return (
    <div>
      <Button onClickProps={handleOpenModal}>Creer un post</Button>
      <Modal isOpen={modalIsOpen} onRequestClose={handleCloseModal}>
        <form className="form-post" onSubmit={handleSubmit}>
          <h2>Ajouter un nouveau post</h2>
          <div>
            <label htmlFor="title">Titre</label>
            <input type="text" id="title" onChange={(e) => console.log(e)} />
          </div>
          <div>
            <label htmlFor="description">Description</label>
            <textarea id="description"></textarea>
          </div>
          <button type="submit">Ajouter</button>
        </form>
      </Modal>
    </div>
  );
};

How to beautify JSON in text area?

I’m trying to beautify JSON in text area but I’m unable to do it.

<textarea id="myTextArea" name="w3review" rows="6" cols="" style="width:100%"> 
                                                       
${data}

</textarea>

<button onclick="prettyPrint()">Pretty Print</button> 

And, this is the script which I’m using to beautify the JSON in text area.


function prettyPrint() {
var ugly = document.getElementById('myTextArea').value;
var obj = JSON.parse(ugly);
var pretty = JSON.stringify(obj, undefined, 4);
document.getElementById('myTextArea').innerHTML = pretty;
}

I think the JSON.stringify is not working or I don’t know what is wrong in my code.

Please help me out. thanks in advance