Is possible export just 1 object and not whole page? (Javascript, export/import)

I am trying export and import my objects in js files, but my console throws errors like

  1. Uncaught ReferenceError: Cannot access ‘SetStorage’ before
    initialization.

Here is how my import looks like:

import { SetStorage } from "./databaseInsurence.js"
let data= new SetStorage();

and script tag in my HTML:

<script type= "module" src="editPojisteni.js"></script>

Thank you.

Kind regards Miriam.

I think problem is with loading page, but I am not sure.

Can I make a DNS query directly from the browser?

I would like to build a simple web app that asks the user for a domain, performs an DNS query on it, and returns the results.

It’s fairly simple to achieve this with a server, but I wonder if this is possible without using a server at all – simply making the NS query using JS from the browser.

I’m looking for a full query, not just IP – all the CNAMES and text fields as well.

I’ve found the dns.resolve() API, but it’s only supported in Firefox for some reason.

Is there a globally available API or library to make NS queries from the browser?

Array updating state in react

I have 2 state variable like 

const[ingredients,setIngredient1]=usestate()

const[ingredient2,setIngredient]=usestate()
const[ingredient,setIngredient]=usestate()
I want to make array like 
ingredients['salt','meat'] where  
ingredients1="salt"
ingredients='meat'
And then send ingredients[] to node js back end in form of Formdata().

ingredients['salt','meat'] 

This react js question want to make array with dot notation

Receiving an Uncaught Type Error Cannot Read properties of null (reading ‘addEventListener’)

I have the following code to calculate the shipping costs based on purchase value and on two other variables (through radio buttons):

$(document).ready(function () {
        let fnum = 0, snum = 0;
        $('input[name="fnum"]').on("click", function () {
            fnum = parseFloat($('input[name="fnum"]:checked').val());

        });

        $('input[name="snum"]').on("click", function () {
            snum = parseFloat($('input[name="snum"]:checked').val());
        });

        let purchaseAmount = document.querySelector('#purchaseAmount');
        purchaseAmount.addEventListener('input', function () {
        valAsNumber = parseFloat(purchaseAmount.value);                
        });

        $("button").on('click', function () {
            var boundaryValue1 = 24.99;
            var boundaryValue2 = 49.99;
            var shippingSubCost = 0;

            if (valAsNumber <= boundaryValue1 ){
                shippingSubCost = 5.00;
            }
            else if (valAsNumber > boundaryValue1 && valAsNumber <= boundaryValue2){
                shippingSubCost = 2.50;
            }
            else{
                shippingSubCost = 0.00;
            }
            
            
            var shippingCost = (shippingSubCost * fnum) + (valAsNumber * snum);
    });
        const formatter = new Intl.NumberFormat('en-US', {
            style: 'currency',
            currency: 'USD',});

        var outputShippingCost = formatter.format(shippingCost);

        console.log("Shipping Cost = $" + outputShippingCost);
        console.log("Purchase Amount = $" + purchaseAmount);
        console.log("shippingSubFee = $" + shippingSubFee);
        console.log("preferredCustomer = " + preferredCustomer);
        console.log("trustedTraveler = " + trustedTraveler);

        $("#finalQuote").val(outputShippingCost);
        }
    
    );

The HTML is as follows:

<body data-new-gr-c-s-check-loaded="14.1003.0" data-gr-ext-installed="">
    <nav class="navbar navbar-expand-md navbar-dark bg-dark fixed-top">
        <a class="navbar-brand" href="index.html">Get your Shipping Quote Now!</a>


        <div class="collapse navbar-collapse" id="navbarsExampleDefault">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item">
                    <a class="nav-link" href="index.html">Home</a>
                </li>

            </ul>
        </div>
    </nav>

    <main role="main" class="container" style="padding-top: 5em">
        <h1 style="text-align: center;">Enter Information</h1>

        <form id="addForm" name="addForm">
            <div class="form-group">
                <div class="card" style="">
                    <div class="card-header">
                        <b>Customer Information</b>
                    </div>

                    <div style="padding: 10px">
                        <div class="form-group">
                            <label for="firstName">First Name</label>
                            <input type="text" class="form-control" id="firstName" name="firstName">
                        </div>
                        <div class="form-group">
                            <label for="lastName">Last Name</label>
                            <input type="text" class="form-control" id="lastName" name="lastName">
                        </div>

                        <div class="form-group">
                            <label for="address">Address</label>
                            <input type="text" class="form-control" id="address" name="address">
                        </div>
                        <div class="form-row">
                            <div class="form-group col-md-6">
                                <label for="city">City</label>
                                <input type="text" class="form-control" id="city" name="city">
                            </div>
                            <div class="form-group col-md-4">
                                <label for="province">Province</label>
                                <select id="province" class="form-control" name="province">
                                    <option value="ON" selected>ON</option>
                                    <option value="NL">NL</option>
                                    <option value="PE">PE</option>
                                    <option value="NS">NS</option>
                                    <option value="NB">NB</option>
                                    <option value="QC">QC</option>
                                    <option value="MB">MB</option>
                                    <option value="SK">SK</option>
                                    <option value="AB">AB</option>
                                    <option value="BC">BC</option>
                                    <option value="YT">YT</option>
                                    <option value="NT">NT</option>
                                    <option value="NU">NU</option>
                                </select>
                            </div>
                            <div class="form-group col-md-2">
                                <label for="postalCode">Postal Code</label>
                                <input type="text" class="form-control" id="postalCode" name="postalCode">
                            </div>
                        </div>

                        <div class="form-row">
                            <div class="form-group col-md-4">
                                <label for="phone">Phone Number</label>
                                <input type="text" class="form-control" id="phone" name="phone">
                            </div>

                            <div class="form-group col-md-8">
                                <label for="email">Email address</label>
                                <input type="email" class="form-control" id="email" name="email">
                            </div>
                        </div>
                    </div>

                </div>
                <br>
                <div class="card">
                    <div class="card-header">
                        <b>Customer Purchasing Information</b>
                    </div>
                    <div class="card-body">
                        <div id="optionfood">
                        <div class="form-group">
                            <label for="preferredCustomer">Are you a Preferred Customer?</label>
                            <input type="radio" id="preferredCustomer" name="fnum" value="0">Yes
                            <input type="radio" id="preferredCustomer" name="fnum" value="1">No
                            <br>
                        </div>                        
                        <div class="form-group">
                            <label for="trustedTraveler">Are you a Trusted Traveler?</label>
                            <input type="radio" id="trustedTraveler" name="snum" value="0">Yes
                            <input type="radio" id="trustedTraveler" name="snum" value="0.15">No
                            <br>
                        </div>

                        <div class="form-group">
                            <label for="purchaseAmount">Purchase Amount ($CDN)</label>
                            <input type="number" class="form-control" name="purchaseAmount" id="purchaseAmount" pattern="^$d{1,3}(,d{3})*(.d+)?$" value="" data-type="currency" placeholder="$0.00" min="0.01">
                        </div>
                        </div>

                    </div>
                </div>
            </div>
            <a type="button" class="btn btn-primary" id="btnSubmit" onclick="AddQuote()" style="color: white">Submit</a>
        </form>
    </main>
</body>

When I try to run this code, I receive an Uncaught Type Error Cannot Read properties of null (reading ‘addEventListener’). Any ideas on why this is happening and how to recover from it?

I tried adjusting my HTML code but it didn’t work

Where and how long are values stored by user scripts persisted?

Greasemonkey (and other user script managers) provide functions like GM.getValue and GM.setValue in its API, which allow scripts to store and retrieve arbitrary script-specific values.

Greasemonkey’s documentation on GM.setValue promises that the values stored will persist across page loads and origins. However, it’s pretty scant on other details, namely: how long are those values persisted?

  • Until the tab is closed? (like sessionStorage)
  • Until the browser is closed?
  • Until browser cache is cleared? (like localStorage)
  • Forever? (until the script and/or extension is removed)

Furthermore, with browser features like Firefox containers, should I expect values in user script storage to be available across different containers?

Finally, is there any way a user script can control how long/in which scope user script data is stored?

Trying to understand async/await and Promise

I know a few things about async/ await is that only async functions can use await, await waits for a promise/async-function to return a resolve or reject. I was hence trying to learn it in depth but got confused as why this code wasnt giving expected results

var x = [1]

const add2 = async () => {
    x = [...x, 2]
    return Promise.resolve()
}

const add3 = async () =>  {
    setTimeout(() => {
        x = [...x, 3]
        return Promise.resolve()
    }, 4000)
}

const final = async () => {
    console.log(x)
    await add2()
    console.log(x)
    await add3()
    console.log(x)
}

final()

This would give me output as

[1]
[1, 2]
[1, 2]

Whereas my expected output was

[1]
[1, 2]
[1, 2, 3]

So i tried to make a few changes and i got the output

var x = [1]

const add2 = async () => {
    x = [...x, 2]
    return Promise.resolve()
}

const add3 = (z) => new Promise((resolve, reject) => {
    setTimeout(() => {
        x = [...x, 3]
        console.log(z)
        return resolve()
    }, 4000)
})

const final = async () => {
    console.log(x)
    await add2()
    console.log(x)
    await add3()
    console.log(x)
}

final()

So i am confusion wether i can implement this functionality using just async function and not defining a new promise

What is the difference between .addEventListener and .on() when adding an event in Bootstrap 5?

I’m trying to add a listener to my modal to be able to apply a behavior every time the modal is opened.

According to the Bootstrap 5 documentation, you could use:
https://getbootstrap.com/docs/5.2/components/modal/#events

const myModalEl = document.getElementById('fast-modal')
myModalEl.addEventListener('show.bs.modal', event => {
  // do something...
})

enter image description here

My HTML of the modal is:

<div class="modal fade" id="fast-modal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header"></div>
            <div class="modal-complement" id="fast-result-box"></div>
            <div class="modal-body"></div>
            <div class="modal-footer"></div>
        </div>
    </div>
</div>

Using pure Javascript, it works as expected!


My problem is when I try to do the same event addition using Jquery 3.6, like this:
http://api.jquery.com/on/

$(document).on('show.bs.modal', '#fast-modal', function () {
    alert('hi');
})
        
// or

$('#fast-modal').on('show.bs.modal', function () {
    alert('xx');
})

Why when I use Jquery it doesn’t work? Where is the error in the code?

Getting “Undefined” from model using Nodejs

I am working with Nodejs and using expressjs for API’S,Right now i am trying to use condition (according to model response) but i am getting “undefined” message,Where i am wrong ? Here is my “controller file”(api.controller)

const sendotps = async (req, res) => {
    var phone_number=req.body.phone_number;
    if (!phone_number || !phone_number.trim() || phone_number == null || phone_number < 10)
        return res.status(400).send({ statusCode: 400, statusMessage: 'Bad Request', message: 'Enter valid mobile number', data: null });
    try {
        const result= await User.sendOtp(phone_number);
        console.log('result is '+ result);
        if(result!"notexist")
            {
                    // further code
            }
        else
            {
                    // further code
            }   
    } catch (err) {
        res.status(500).send({
            statusCode: 500,
            statusMessage: 'Internal Server Error',
            message: null,
            data: null,
        });
    }

Here is my “model file”(user.model)

static sendOtp(phone_number) {
        const sql2 = "SELECT * FROM users WHERE phone_number = '${phone_number}' AND is_registered='1'";
                const [rows2, fields2] = await pool.execute(sql2);
               if(rows2>0)
                {
                        return rows2;
                }
                else
                {
                        return "notexist";
                }
    } 

JavaScript anonymous function not working

  <!DOCTYPE html>

<html>

    <head> 
            <title> This is head tag java Script file </title>
            
            <script  type = "text/javascript" src = "helloworld.js" > </script> 
            
            <script>
                    nam();
                    //hello("diplay");
                    
                    
            </script>
            
    </head>
    
    <body> 
            <button id = "btn"> Click me </button>
    </body>
    
</html>

    var nam = function()  
{
    alert("Name : hello world");
};

I make function name “name” but the program not working , I was changed function name “name” to “nam” it’s working why?

Is there any algorithm or pre-existing function to create groups out of custom sorted data for fleuntUI GroupedList? The data is read from csv file

link to fluent ui grouped list : https://developer.microsoft.com/en-us/fluentui#/controls/web/groupedlist

I want groups to be created based on three columns i.e it creates three levels of groups

Any existing algorithm so that we can just mention the column names and it returns groups to pass to fluent ui?

div moves other divs when size expands

i’m trying to build a row of divs where a div will expand when a mouse hovers over it.
It got that so far but i want that the expanding div is not moving the other divs around (changing there size) but to expand over his neigbours, partly covering them.

i hope you get what i mean..

i also would like to keep the js part because there should happen more stuff when hovering over the elements.

here is my code so far:

<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8" />
    <style>
        .wrap{
            font-size: 160px;
            font-weight: bold;
            height: 450px;
            width: 1100px;
            display: flex;
            flex-direction: row;
            align-items: center;
            border-style: solid;
            border-width: 1px;  
        }
        .a{
            width: 220px;
            height: 350px;
            border-style: solid;
            border-width: 1px;
        }
        .b{
            width: 220px;
            height: 350px;
            border-style: solid;
            border-width: 1px;
        }
        .c{
            width: 220px;
            height: 350px;
            border-style: solid;
            border-width: 1px;
        }
        .d{
            width: 220px;
            height: 350px;
            border-style: solid;
            border-width: 1px;
        }
        .e{
            width: 220px;
            height: 350px;
            border-style: solid;
            border-width: 1px;
        }
    </style>
    <script type="application/javascript">
        function enlarge(id){
            /*console.log("enlarge: " + id);*/
            var element = document.getElementById(id);
            element.style.height = "440px";
            element.style.width = "260px";
            element.style.borderWidth = "1px";
            element.style.borderStyle = "solid";
            
        }
        function reduce(id){
            /*console.log("reduce: " + id);*/
            var element = document.getElementById(id);
            element.style.height = "350px";
            element.style.width = "220px";
            element.style.borderWidth = "1px";
            element.style.borderStyle = "solid";
        }
    </script>
</head>
<body>  
    <center>
    
        <div class="wrap">
            <div class="a" id="a" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">A</div>
            <div class="b" id="b" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">B</div>
            <div class="c" id="c" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">C</div>
            <div class="d" id="d" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">D</div>
            <div class="e" id="e" onmouseover="enlarge(this.id)" onmouseout="reduce(this.id)">E</div>
        </div>
    
    </center>
</body>
</html>

also on jsfiddle:
https://jsfiddle.net/fkdvptuz/

How to implement an AI opponent in a basic Tic Tac Toe gameboard?

I am a beginner in programming. I have worked on a basic Tic Tac Toe gameboard, it works successfully. For the second phase of my assignment, I am required to implement an AI opponent however I came across several problems.

As a beginner, I need some help and guidance as to how I can fix and work on my codes of the normal Tic Tac Toe gameboard so that I can have an AI opponent.

I used HTML, CSS, and JS for my basic Tic Tac Toe gameboard. I will list all my codes below:

HTML

`<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Tic Tac Toe</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  <div class="container">
    <h1>Tic Tac Toe</h1>
    <div id="board">
      <div class="square" id="0"></div>
      <div class="square" id="1"></div>
      <div class="square" id="2"></div>
      <div class="square" id="3"></div>
      <div class="square" id="4"></div>
      <div class="square" id="5"></div>
      <div class="square" id="6"></div>
      <div class="square" id="7"></div>
      <div class="square" id="8"></div>
    </div>
    <button id="reset">Reset Game</button>
    <div id="message"></div>
  </div>
  <script src="index.js"></script>
</body>
</html>`

CSS

`.container {
  text-align: center;
}

#board {
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  margin: 0 auto;
}

.square {
  width: 90px;
  height: 90px;
  background-color: black;
  margin: 5px;
  border-radius: 5px;
  font-size: 50px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
}

.square:hover {
  background-color: whitesmoke;
}

.square.X {
  color: #ff5e5e;
}

.square.O {
  color: #0077ff;
}
`

JS

`let board = ["", "", "", "", "", "", "", "", ""];
let currentPlayer = "X";
let gameOver = false;

const winningConditions = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
];

const squares = document.querySelectorAll(".square");
const resetButton = document.querySelector("#reset");

// Add click event listener to each square
squares.forEach(square => {
  square.addEventListener("click", handleClick);
});

// Add click event listener to reset button
resetButton.addEventListener("click", resetGame);

function handleClick(event) {
  const square = event.target;
  const index = square.getAttribute("id");

  // If square is already clicked or game is over, return
  if (board[index] !== "" || gameOver) {
    return;
  }

  // Add X or O to board and update UI
  board[index] = currentPlayer;
  square.classList.add(currentPlayer);
  square.innerHTML = currentPlayer;

  // Check for winner or tie game
  checkForWinner();
  checkForTieGame();

  // Switch current player
  currentPlayer = currentPlayer === "X" ? "O" : "X";
}

function checkForWinner() {
  for (let i = 0; i < winningConditions.length; i++) {
    const [a, b, c] = winningConditions[i];
    if (board[a] === board[b] && board[b] === board[c] && board[a] !== "") {
      gameOver = true;
      highlightWinnerSquares(a, b, c);
      displayWinner(board[a]);
      break;
    }
  }
}

function checkForTieGame() {
  if (!board.includes("") && !gameOver) {
    gameOver = true;
    displayTieGame();
  }
}

function highlightWinnerSquares(a, b, c) {
  document.getElementById(a).classList.add("winner");
  document.getElementById(b).classList.add("winner");
  document.getElementById(c).classList.add("winner");
}

function displayWinner(player) {
  const message = document.getElementById("message");
  message.innerHTML = `${player} wins!`;
}

function displayTieGame() {
  const message = document.getElementById("message");
  message.innerHTML = "It's a tie game!";
}

function resetGame() {
  board = ["", "", "", "", "", "", "", "", ""];
  currentPlayer = "X";
  gameOver = false;

  squares.forEach(square => {
    square.classList.remove("X", "O", "winner");
    square.innerHTML = "";
  });

  const message = document.getElementById("message");
  message.innerHTML = "";
}`

The server runs the spring boot project, and some pages cannot be loaded normally

The springboot project contains a front-end page – FuncPepStatistics. The content of this page is composed of statistical graphs generated by js code written by echarts.js.
After the project is run in idea, the FuncPepStatistics.html page can be run successfully.
However, if the springboot project is packaged, whether it is run on the local cmd or on the cloud server, the page cannot be successfully displayed, and the error that occurs is a 500 type error
The console of the browser gives the following error:
Failed to load resource: the server responded with a status of 500 () Uncaught (in promise) Error: A listener indicated an asynchronous response by returning true, but the message channel closed before a response was received
The server terminal error is as follows:

[THYMELEAF][http-nio-9188-exec-9] Exception processing template "/FuncPepStatistics": Error resolving template [/FuncPepStatistics], template might not exist or might not be accessible by any of the configured Template Resolvers

org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/FuncPepStatistics], template might not exist or might not be accessible by any of the configured Template Resolvers
Servlet.service() for servlet [dispatcherServlet] in context with path [/mfppdb] threw exception [Request processing failed; nested exception is org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/FuncPepStatistics], template might not might exist not be accessible by any of the configured Template Resolvers] with root cause
org.thymeleaf.exceptions.TemplateInputException: Error resolving template [/FuncPepStatistics], template might not exist or might not be accessible by any of the configured Template Resolvers

I have checked that the application.properties file configuration is correct, there is no error in the path, and the view function is also correct.

Selection one “input” with help “radio”

I would like to be able to do only one enabled input type text when selecting for help input type radio.

I can check multiple boxes with a checkbox which works as I want. On this basis, I made a selection using input type radio, which unfortunately does not work properly. Each first selection of radio makes input “always” enabled. And I want only one of the fields that is currently selected to be enabled and the others disabled.

Code with using input type Checkbox(works correctly)

<script>
function disable(checkbox,form){
    if(document.getElementById(checkbox).checked == true){
        document.getElementById(form).disabled = false
    }else{
        document.getElementById(form).disabled = true
    }
}
</script>
<label>Name:<br><input type="checkbox" id="chbx_name" onclick="disable('chbx_name','name')"><input type='text' id="name" name="name" value='<?php echo $row['name'] ?>' disabled></label>
<label>Data:<br><input type="checkbox" id="chbx_data" onclick="disable('chbx_data','data')"><input type='date' id="data" name="data" value='<?php echo $row['data'] ?>' disabled>
</label>
<label>Hour:<br><input type="checkbox" id="chbx_hour" onclick="disable('chbx_hour','hour')"><input type='time' id="hour" name="hour" value='<?php echo $row['hour'] ?>' disabled>
</label>

Code with using input type radio(works incorrectly)

<script>
    function disable(checkbox,form){
        if(document.getElementById(checkbox).checked == true){
                    document.getElementById(form).disabled = false
        }else{
            document.getElementById(form).disabled = true
        }
    }
</script>
<?php
    $result = $mysqli->query("SELECT picture_name FROM film_pictures WHERE IDpicture = ".$id);
    while($row=$result->fetch_array()){
            $i=0;
            $i++;                                           
                ?><label><input type="radio" id="radio_picture_name<?php echo $i ?>" onclick="disable('radio_picture_name<?php echo $i ?>','picture_name<?php echo $i ?>')"><input type="text" id="picture_name<?php echo $i ?>"  name="picture_name" value="<?php echo $row['picture_name'] ?>" style="width:450px" ></label>
<?php } ?>