Why is my code snippet not returning an alert?

Here is code:

document.addEventListener("DOMContentLoaded", () => {
  event.preventDefault();
  document.querySelector("#submit").onsubmit;
  () => {
    if (
      document.querySelector("#input").value === "" ||
      document.querySelector("#input").value === null
    ) {
      alert("Please enter your name.");
      return false;
    }
    let name = document.querySelector("#input").value;
    alert("Hello, " + name + "!");
  };
});
<form>
  <input id="input" placeholder="Name" type="text" autofocus autocapitalize="words" />
  <input id="submit" type="submit" />
</form>

When i run this code snippet it adds a question mark to the end of the url but doesn’t do an alert, any and all help appreciated

i’ve tried using the id called input instead of submit in the onsubmit but that gave the same result

PDF.js Setting a field value?

I hope you’re all doing well. So I’ve been working with PDF.js by Mozilla for a while now. We’re using it to display PDF forms to be filled out on a mobile app. Everything works great, I’m just trying to implement a feature where you can cache the users entries so that they can resume from where they left off. For a few reasons I can’t just download the PDF to save it and then load it back up when they wat to resume.

Essentially I want to store all the user entries and the Field ID for each of them, which I’ve already gotten working, and then when the user wants to resume I want it to load the empty PDF, and then automatically re-populate all the fields with the cached entries.

I know I could set the individual text fields, but when I do that it doesn’t apply to the annotationStorage so when I parse the form, those fields are read as blank.

I’ve tried the following lines of code in an attempt to set a field value with the id “5R”

PDFViewerApplication.pdfDocument.annotationStorage.setValue('5R', "Shirboogle");
PDFViewerApplication.pdfDocument.annotationStorage.getAll()['5R'].value = "Shirboogle";
var objs = await PDFViewerApplication.pdfDocument.getFieldObjects();
objs['Address 1 Text Box'][0].value = "Shirboogle";
// and
objs['Address 1 Text Box'][0].defaultValue = "Shirboogle";
// This will actually set the value of the text field, but when I look for it in annotationStorage OR
// getFieldObjects() the value is still unchanged.
document.getElementById('pdfjs_internal_id_5R').value = 'Shapoopsies';

along with many other attempts. I’ve looked all over and nothing seems to be available, so if you have any ideas please let me know!

D3 Mitch Tree add Filter and Search Functionality

I am building a heirarchy tree that needs to be filterable and searchable. I am using D3 Mitch tree – https://d3-mitch-tree.netlify.app/

Right now I handle he filtering by

    document.getElementById('focusButton').addEventListener('click', function(){
    var value = 'filter1';
    var nodeMatchingText = treePlugin.getNodes().find(function(node){
    return node.data.name == value;    
    });
    treePlugin.focusToNode(nodeMatchingText);  
      
    });```


Then in the data json the name would have to be filter1 to make this match, and then it would open and focus on that node. This works, however I would like it to open all of the children related to that node. 

Search is where I am really struggling, I need it to do a full match or starts with or even partial on the names and then open ALL nodes that have the match in their children and close any that don't .

Currently I have this which will only open and focus on the first if it is an exact match. In the console log statement I can see all of the nodes but I am not sure how to get it to return and open those nodes.

document.getElementById('focusButton-search').addEventListener('click', function(){
var value = document.getElementById('search').value;
var nodeMatchingText = treePlugin.getNodes().find(function(node){
return node.data.name == value;
});
console.log(nodeMatchingText);
treePlugin.focusToNode(nodeMatchingText);

});

Render multiple mapbox maps with svelte leads to strage behaviour (renders but not draggable)

I have this mapboxmap.svelte component (its a public token!):

<script>
  import { onMount } from "svelte";
  import mapbox from "mapbox-gl";
  //   import "mapbox-gl/dist/mapbox-gl.css";

  mapbox.accessToken =
    "pk.eyJ1Ijoicm9iaW5rb2hycyIsImEiOiJjanU5am95bm4xZnZ6NDNrOTRyYTYwdzJzIn0.iMFQgQIlhz36wB3819Xftw";

  // create map
  let map;
  onMount(() => {
    map = new mapbox.Map({
      container: "map", // container id
      style: "mapbox://styles/examples/cjgioozof002u2sr5k7t14dim", // map style URL from Mapbox Studio
    });
  });
</script>

<div id="map" />

<style lang="scss">
  #map {
    width: 400px;
    height: 400px;
  }
</style>

And I want to render it multiple times on the site. So I import the component into my App.svelte-component and “call” the component two times like this:

<script>
  import { onMount } from "svelte";
  import Mapboxmap from "./lib/maps/mapboxmap.svelte";
</script>

<Mapboxmap />
<Mapboxmap />

It does show two maps. Yet only one is working in the sense that it is draggable (this first one)

The strange this is that uncommenting this line, which imports some mapbox css

import "mapbox-gl/dist/mapbox-gl.css";

leads to the disappearing of the second map. What am I getting wrong here?

webpack main.js file size is 6.3 in “webpack –mode production”

I am using webpack to combine django & React js.
but main.js bundle file is too large (6.3 MB)
so the page to much time to load

webpack.config.js

const path = require("path");
const webpack = require("webpack");
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");

module.exports = {
  entry: "./src/index.js",
  output: {
    path: path.resolve(__dirname, "./static/frontend"),
    filename: "[name].js",
  },

  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
        },
      },
      // Additional configuration to handle *.css files
      {
        test: /.css$/i,
        use: ["style-loader", "css-loader"],
      },
      {
        test: /.svg$/,
        use: ["@svgr/webpack"],
        use: [
          {
            loader: "svg-url-loader",
            options: {
              limit: 10000,
            },
          },
        ],
      },
      {
        test: /.(png|jpg)$/,
        type: "asset/resource",
      },
    ],
  },
  optimization: {
    minimize: true,
  },
  performance: {
    hints: false,
    maxEntrypointSize: 512000,
    maxAssetSize: 512000,
  },
  plugins: [
    new NodePolyfillPlugin(),
    new webpack.DefinePlugin({
      "process.env.NODE_ENV": JSON.stringify("production"),
    }),
  ],
};

babel.config.json

{
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "node": "10"
            }
          }
        ],
        "@babel/preset-react"
      ],
      "plugins": ["@babel/plugin-proposal-class-properties"]
    }
  

My pakage.json Installed is

  • “webpack”: “^5.75.0”,
  • “webpack-cli”: “^5.0.0”

I am unable to optimize with minimize = true
Its show error when minimize = true

ERROR in main.js main.js from Terser plugin

Why JavaScript Validation is Not Working For Some Input Fields?

I created a form for Validation But Only the Author Name is getting Validated and rest of other input field is getting submitted without getting validation

I tried giving name to form and retrieving the values from it but it doesn’t seem to work. I created a seperate file for JavaScript and JSP Page

The Below One is HTML Form

<form method="post"  class="form-custom" onsubmit="return validateForm()" action="../AddProducts">
   <div class="row">
      <div class="col">
        <label for="bname">Book Name</label>
        <input type="text" class="form-control" id="bname" placeholder="Enter Book name" name="bname">
         <p class="error" id="error_name"></p>
       </div>
       <div class="col">
         <label for="authorname">Author Name</label>
         <input type="text" class="form-control" id="author" name="author" placeholder="Enter Author name">
         <p class="error" id="error_author"></p>
       </div>
   </div>
   <div class="row">
      <div class="col">
        <label for="bname">Price</label>
        <input type="text" class="form-control" id="price" name="price" placeholder="Enter Price" >
        <p class="error" id="error_price"></p>
       </div>
       <div class="col">
         <label for="authorname">Quantity</label>
         <input type="text" class="form-control" id="qty" name="qty" placeholder="Enter Qty" >
         <p class="error" id="error_qty"></p>
        </div>
        <div class="col">
          <label for="authorname">Select Category</label>
          <select class="custom-select" id="inputGroupSelect01">
             <option selected value="-1">Choose...</option>
             <c:forEach var="r" items="${rs.rows}">
                <option value="${r.category}">${r.category}</option>
             </c:forEach>
          </select>
          <p class="error" id="error_select"></p>  
       </div>
       <div class="col">
         <label>Choose Book Image</label>
         <div class="custom-file">
            <input type="file" class="custom-file-input" id="inputGroupFile01">
            <label class="custom-file-label" for="inputGroupFile01" id="custom-label">Choose file</label>
            <p class="error" id="error_file"></p>
         </div>
       </div>
   </div>
   <div class="row">
      <div class="col">
         <div class="form-group">
            <label for="desc">Description</label>
            <textarea class="form-control customtxt" id="desc" rows="4"></textarea>
                        
          </div>
      </div>
   </div>
   <div class="row">
      <div class="col d-flex justify-content-center">
            <input type="submit" value="Save" class="btn custombtn m-2"/>
            <input type="reset" value="Clear" class="btn custombtn m-2"/>
      </div>
   </div>
                 
</form>

Below is the JavaScript Validation Function()

function validateForm()
{

    var author=document.getElementById('author').value;
    var price=document.getElementById('price').value;
    var qty=document.getElementById('qty').value;
    var bname=document.getElementById("bname");
    var c=document.getElementById('inputGroupSelect01');
    var cat=c.options[c.selectedIndex].value;
    var filepath=document.getElementById("inputGroupFile01").value;
    var allowedExtension=/(.jpg|.jpeg|.png|.gif)$/i;


    if(!author.match(/[A-z]+$/))
    {
        document.getElementById('error_author').innerHTML="*Please Enter Valid Author Name!";
        document.getElementById('author').focus();
        return false;
    }
    else if(!bname.match(/[A-z]+$/))
    {
        document.getElementById('error_name').innerHTML="*Please Enter Valid Book Name";
        document.getElementById('bname').focus();
        return false;
    }
    else if(!price.match(/^d+(?:[.,]d+)*$/))
    {
        document.getElementById('error_price').innerHTML="*Please Enter Valid Price!";
        document.getElementById('price').focus();
        return false;
    }
    else if(!qty.match(/^[0-9]+$/))
    {
        document.getElementById('error_qty').innerHTML="*Please Enter Valid Quantity!";
        document.getElementById('qty').focus();
        return false;
    }
    else if(cat===-1)
    {
        document.getElementById('error_select').innerHTML="*Please Select a Category!";
        return false;
    }
    else if(filepath==="")
    {
        document.getElementById('error_file').innerHTML="*Please Upload Image!";
        filepath.value="";
        return false;
    }
    //exec -> search for the particular word is there or not
    else if(!allowedExtension.exec(filepath))
    {
        document.getElementById('error_file').innerHTML="*Please Upload Valid Image!";
        filepath.value="";
        return false;

    }
    else
    {
        return true;
    }
}

My browser Google Chrome doesn´t run Promises nor Async await. What can I do?

The following code doesn´t run on my Google Chrome:

const urls = [
  "https://jsonplaceholder.typicode.com/posts",
  "https://jsonplaceholder.typicode.com/users",
  "https://jsonplaceholder.typicode.com/albums",
];

Promise.all(urls.map((url) => fetch(url).then((resp) => resp.json())))
    .then((array) => {
    console.log("posts", array[0]);
    console.log("users", array[1]);
    console.log("albums", array[2]);
})
.catch("oops");

const getData = async function () {
const [users, posts, albums] = await Promise.all(
urls.map((url) => fetch(url).then((resp) => resp.json()))
);
console.log("posts", posts);
console.log("users", users);
console.log("albums", albums);
};

getData();

enter image description here
This is my expectacion

MongoRuntimeError: Unable to parse localhost:127.0.0.1:27017 with URL

Guys I have been taking this Udemy online course “The Complete Web Development Bootcamp” for a while https://www.udemy.com/course/the-complete-web-development-bootcamp. In Section 32, 378th video a simple website is created to explain Authentication and security. So basically when I enter the sample email and password it should take me to a secrets page. But instead I’m getting this mongo runtime error in my terminal after pressing the register button in the register page.

MongoRuntimeError

And I got some error when i ran mongod in my terminal:
msg: Deleted expired documents using index,
attr: namespace:config.system.sessions

Instead of just showing Waiting for connections, attr:{port:27017,ssl:off}

mongod error

My source code from app.js:

app.js
app.js

I already tried sudo rm /var/lib/mongodb/mongod.lock command, but hyper terminal in my pc doesn’t support sudo command. I have also checked my services tab in task manager and the mongoDB server was running perfectly. And someone suggested to download homebrew but that is for MacOS. Can anyone suggest a solution for this in Windows 11 OS?

JavaScript/AngularJS: When reading excel row turns string with date, into date only value

I am using AngularJS to read and display the contents of an excel file.
When the excel file contains a row with a value such as:
Finance Committee will need to meet prior to the board meeting on February 16

The value gets converted into a date 2/16/01

After this piece of code gets executed (ProcessExcel)

$scope.DisplayFile = function () {
    var regex = /^[a-z0-9][-a-z0-9x20_!().:,]*.xlsx?$/i;
    if (regex.test($scope.SelectedFile.name)) {
        if (typeof (FileReader) !== "undefined") {
            var reader = new FileReader();
            //For Browsers other than IE.
            if (reader.readAsBinaryString) {
                reader.onload = function (e) {
                    $scope.ProcessExcel(e.target.result);
                };
                reader.readAsBinaryString($scope.SelectedFile);
            } else {
                //For IE Browser.
                reader.onload = function (e) {
                    var data = "";
                    var bytes = new Uint8Array(e.target.result);
                    for (var i = 0; i < bytes.byteLength; i++) {
                        data += String.fromCharCode(bytes[i]);
                    }
                    *$scope.ProcessExcel(data)*; --I think the issue comes from this function, I might be incorrect

    $scope.ProcessExcel = function (data) {

        //file data
        var workbook = XLSX.read(data, {
            type: 'binary'
        });

        //fetch first sheet
        var firstSheet = workbook.SheetNames[0];

        //put sheet into array excelRows
        *excelRows = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[firstSheet]);* -- By the time this assignment occurs, the value of the excel array for that row, is already 2/16/01

Can someone please help me understand how can this be avoided, and corrected?

Thank you,
Erasmo.

Invalid Hook Call on Adding React Router DOM and Navbar in Latest React Version

I am creating a Todo List application with Navigation bar and React Router DOM. Everything was working fine before I added Navigation bar and React Router DOM. Now, I’m getting this error:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app
    See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

I have imported all the latest components as well as aligned the version of React and React Router DOM.

The code for each file is given below:

App.js

import logo from './logo.svg';
import './App.css';
import Navibar from './components/Navibar';
import { useState } from 'react';
import TodoTask from './components/TodoTask';
import { Route, Routes, BrowserRouter } from 'react-router-dom';
import Footer from './components/Footer';
import AboutUs from './components/AboutUs';
import ContactUs from './components/ContactUs'

function App() {
  return (
    <BrowserRouter>
      <div>
        <Navibar />
        <Routes>
          <Route exact path="/" element={<TodoTask/>}/>
          <Route path="/aboutus" element={<AboutUs />} />
          <Route path="/contactus" element={<ContactUs />} />
        </Routes>
        <Footer />
      </div>
    </BrowserRouter>
  );
}

export default App;

AboutUs.js

import React from 'react';
const AboutUs = () => {
    return (
        <div>
            This is footer
        </div>
    )
}

export default AboutUs;

ContactUs.js

import React from 'react';
const ContactUs = () => {
    return (
        <div>
            This is footer
        </div>
    )
}

export default ContactUs;

Navibar.js

import React from 'react';
import {Link} from "react-router-dom";
const Navibar = () => {
    console.log("Load navigation bar")
    return (
        <div>
             <nav className="navbar navbar-expand-lg bg-light">
                <div className="container-fluid">
                    <Link className="navbar-brand" to="#">navbar</Link>
                    <button className="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                        <span className="navbar-toggler-icon"></span>
                    </button>
                    <div className="collapse navbar-collapse" id="navbarSupportedContent">
                        <ul className="navbar-nav me-auto mb-2 mb-lg-0">
                        <li className="nav-item">
                                <Link exact className="nav-link active" aria-current="page" to="/">Welcome</Link>
                            </li>
                            <li className="nav-item">
                                <Link className="nav-link active" aria-current="page" to="/aboutus">About Us</Link>
                            </li>
                            <li className="nav-item">
                                <Link className="nav-link" to="/contactus">Contact Us</Link>
                            </li>        
                        </ul>
                        
                    </div>
                </div>
            </nav> 
        </div>
    )
}

export default Navibar;

Package.json

{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.5",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-icons": "^4.7.1",
    "react-scripts": "5.0.1",
    "router-dom": "^2.2.10",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Can someone suggest what I should do to get rid of this error?
Thanks!~

How to add extra property in object

I’m trying to update the object with this field included: [{ name: 'Euler', age: 27, location: 'remote' }]
at the moment the str is: [{ name: 'Euler', age: 27 }] so the location fields needs to be added.

I’ve done this so far:

function updateRemoteStudents (str) {
  
str["Location"] = "remote";

 console.log (str);
 
  // Your code here
}

result i get is: [{ name: 'Euler', age: 27 }, Location: 'remote' ].

How can i change the function to reflect what i want (sorry new to coding)

[{ name: 'Euler', age: 27, location: 'remote' }]

how to sort 100 million and 1 billion element of array

I am trying to sort 100 million and 1 billion elements of an array but my code is crashed which sorting best for 1 billion element
So which sorting algorithms is the best for 1billion elements

let arr = new Array(1000000000).fill().map(() => Math.round(Math.random() * 1000000000))
const merge = (leftarr, rightarr) => {
  const output = []
  let left_arrindex = 0
  let right_arrindex = 0
  while (left_arrindex < leftarr.length && right_arrindex < rightarr.length) {
    const left_arrel = leftarr[left_arrindex]
    const right_arrele = rightarr[right_arrindex]
    if (left_arrel > right_arrele) {
      output.push(left_arrel)
      left_arrindex++
    } else {
      output.push(right_arrele)
      right_arrindex++
    }

  }
  return [...output, ...leftarr.slice(left_arrindex), ...rightarr.slice(right_arrindex)]
}
// console.log(merge([3, 6],[2,4]));

const mergesort = (arr, N) => {
  if (arr.length <= 1) {
    return arr
  }
  const midllindex = Math.floor(arr.length / 2)
  const leftarr = arr.slice(0, midllindex)
  const rightarr = arr.slice(midllindex)
  return merge(
    mergesort(leftarr),
    mergesort(rightarr)
  )
}
console.log(mergesort(arr));

How can I format received data using Object.keys?

I have this data:

const langs = {
    en: ['One', 'description'],
    pl: ['Jeden', 'opis'],
};

And I’m trying to parse it into this format:

const formattedData = {
    name: {
        en: "One",
        pl: "Jeden",
    },
    description: {
        en: "description",
        pl: "opis",
    }
};

I tried to do something like this:

const langs = {
  en: ['One', 'description'],
  pl: ['Jeden', 'opis'],
};

const val = Object.keys(langs).map(item => ({
  [item]: langs[item][0]
}))

console.log(val);