Why does the javascript variable name only print once in this html? [duplicate]

When I execute the following code, why does the variable name which is assigned to output only print the first time I use it…not every time I used it?

 <!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script>
window.onload = function(){
    var name = prompt("What's your name?");
    var lengthOfName = name.length

    document.getElementById('output').innerHTML = name;
};
</script>

</body>
</head>
<body>

<h1>My First Heading</h1> <p id="output" </p>
<p>My first paragraph.</p> <p id="output" </p>
<p>My second paragraph.</p>
<p id="output" </p>

</body>
</html>

when i run it…this is the what it looks like

My First Heading dodo bird

My first paragraph.

My second paragraph.

I would expect it to look like this

My First Heading dodo bird

My first paragraph. dodo bird

My second paragraph. dodo bird

creating an object with hours through the user interface

I am having trouble creating the right object. I have a calendar that stores the hours. He wants timeTable to hold such an object, for example

"timeTable":{
    "0": [{"from":"08:00","to":"12:00"}, {"from":"14:00","to":"18:00"}],
    "1": [{"from":"08:00","to":"16:00"}]
  }

How, after clicking the save button, send such an object to:

 timeTable: Map<number, Array<HourScheduleDefinitionModel>>;

interface:

interface HourScheduleDefinitionModel {
  from: string;
  to: string;
}

https://stackblitz.com/edit/angular-ivy-e92ezv?file=src%2Fapp%2Fapp.component.ts

Mongoose cast failed

Does anyone see what might be the problem ?

I feel like I am respecting each entries type, what’s wrong ?

{
  "message": "Product validation failed: subcategory.0: Cast to [string] 
failed for value ... (type string) at path "subcategory.0""
}

data.js

Understand DOM javascript?

I have this piece of code but I dont understand the presence of:” subTotal = subTotalElement.textContent “

function updateSubtotal(product) {
  console.log('Calculating subtotal, yey!');
  // const price
  // const quantity
  const price = product.querySelector('.price span');
  const quantity = product.querySelector('.quantity input');
  const subTotalElement = product.querySelector('.subtotal span'); //HTML element

   

  const subTotal = price.textContent * quantity.value; //input work with  input.value

 subTotal = subTotalElement.textContent ; //to change the HTML
  return subTotal;
}

Tagify – How to add new tags

I am using tagify for including tags but the issue is when I try to add a new tag it is cleared automatically.

I want it to add a new tag if the new value is typed in.

HTML Code

<input name='tags' class='some_class_name' placeholder='write some tags' value='css, html, javascript'>

JS Code

var input = document.querySelector('input[name="tags"]');

var whitelist = ["A# .NET", "A# (Axiom)", "A-0 System", "A+", "A++", "ABAP", "ABC", "ABC ALGOL", "ABSET", "ABSYS", "ACC", "Accent", "Ace DASL", "ACL2", "Avicsoft", "ACT-III", "Action!", "ActionScript", "Ada", "Adenine", "Agda", "Agilent VEE", "Agora", "AIMMS", "Alef", "ALF", "ALGOL 58", "ALGOL 60", "ALGOL 68", "ALGOL W", "Alice", "Alma-0", "AmbientTalk", "Amiga E", "AMOS", "AMPL", "Apex (Salesforce.com)", "APL", "AppleScript", "Arc", "ARexx", "Argus", "AspectJ", "Assembly language", "ATS", "Ateji PX", "AutoHotkey", "Autocoder", "AutoIt", "AutoLISP / Visual LISP", "Averest", "AWK", "Axum", "Active Server Pages", "ASP.NET", "B", "Babbage", "Bash", "BASIC", "bc", "BCPL", "BeanShell", "Batch (Windows/Dos)", "Bertrand", "BETA", "Bigwig", "Bistro", "BitC", "BLISS", "Blockly", "BlooP", "Blue", "Boo", "Boomerang", "Bourne shell (including bash and ksh)", "BREW", "BPEL", "B", "C--", "C++ – ISO/IEC 14882", "C# – ISO/IEC 23270", "C/AL", "Caché ObjectScript", "C Shell", "Caml", "Cayenne", "CDuce", "Cecil", "Cesil", "Céu", "Ceylon", "CFEngine", "CFML", "Cg", "Ch", "Chapel", "Charity", "Charm", "Chef", "CHILL", "CHIP-8", "chomski", "ChucK", "CICS", "Cilk", "Citrine (programming language)", "CL (IBM)", "Claire", "Clarion", "Clean", "Clipper", "CLIPS", "CLIST", "Clojure", "CLU", "CMS-2", "COBOL – ISO/IEC 1989", "CobolScript – COBOL Scripting language", "Cobra", "CODE", "CoffeeScript", "ColdFusion", "COMAL", "Combined Programming Language (CPL)", "COMIT", "Common Intermediate Language (CIL)", "Common Lisp (also known as CL)", "COMPASS", "Component Pascal", "Constraint Handling Rules (CHR)", "COMTRAN", "Converge", "Cool", "Coq", "Coral 66", "Corn", "CorVision", "COWSEL", "CPL", "CPL", "Cryptol", "csh", "Csound", "CSP", "CUDA", "Curl", "Curry", "Cybil", "Cyclone", "Cython", "Java", "Javascript", "M2001", "M4", "M#", "Machine code", "MAD (Michigan Algorithm Decoder)", "MAD/I", "Magik", "Magma", "make", "Maple", "MAPPER now part of BIS", "MARK-IV now VISION:BUILDER", "Mary", "MASM Microsoft Assembly x86", "MATH-MATIC", "Mathematica", "MATLAB", "Maxima (see also Macsyma)", "Max (Max Msp – Graphical Programming Environment)", "Maya (MEL)", "MDL", "Mercury", "Mesa", "Metafont", "Microcode", "MicroScript", "MIIS", "Milk (programming language)", "MIMIC", "Mirah", "Miranda", "MIVA Script", "ML", "Model 204", "Modelica", "Modula", "Modula-2", "Modula-3", "Mohol", "MOO", "Mortran", "Mouse", "MPD", "Mathcad", "MSIL – deprecated name for CIL", "MSL", "MUMPS", "Mystic Programming L"];

var tagify = new Tagify(input, {
      whitelist:whitelist,
      maxTags: 10,
      dropdown: {
        maxItems: 20,          
        classname: "tags-look", 
        enabled: 0,            
        closeOnSelect: false   
      }
    })

Example link -> https://codepen.io/vsync/pen/bGpdVMW

Div with sprite-animation doesn’t change properly during window.resize event

Soo, I am trying to imitate 3d-model rotation with sprite-sheet. I found a perfect example on Codepen, but it was not responsive. What I tried to do is to write div’s, container’s and spritesize (in script) in ‘VW’. And then it is being checked on window.resize event. It does work, but unfortunately not DURING window resize. I put my snippet and three pictures in post — 1) I opened website and everything is perfect 2) I started to change the size of my browser window and as you can see something is wrong 3) Now I tried to “rotate” the “model” with resized window and all is fine again. Sorry, if the question is weird, I am only a beginner 🙁 the first image, the second and the third

var spriteslider = document.createElement('div');
var clientWidth = document.getElementById('spritetarget').clientWidth;

document.body.appendChild(spriteslider);

spriteslider.slider = document.getElementById('spriteslider');
spriteslider.sprite = document.getElementById('spritetarget');
spriteslider.spritesize = clientWidth;
spriteslider.spritecount = 20;
spriteslider.pixelsperincrement = 5;
spriteslider.multiplier = spriteslider.lastmultiplier = 0;

Draggable.create(spriteslider, {
    type: 'x',
  trigger: spriteslider.slider,
  bounds: { minX:0, maxX:0, minY:0, maxY:0 },
      edgeResistance: 0,
  cursor: 'e-resize',
  onDrag: function() {
    if (this.isDragging) {
      var t = this.target;
      t.multiplier = Math.floor(this.x / t.pixelsperincrement) + t.lastmultiplier;
      // TweenLite.set(t.sprite, { backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"});
      TweenLite.set(t.sprite, { backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"});

    }
  },
      onDragEnd: function() {
    var t = this.target;
    t.lastmultiplier = t.multiplier % t.spritecount;
  }
});

window.addEventListener('resize', function(event) {
    var clientWidth = document.getElementById('spritetarget').clientWidth;
    spriteslider.spritesize = clientWidth;
    TweenLite.set(t.sprite, { backgroundPosition: (-t.multiplier * t.spritesize) + "px 0"});
}, true);
body {
  text-align: center;
  font: normal 12px sans-serif;
  background: #000000;
  color: #91E600;
}
.spriteslider {
  margin: 20px auto;
  padding: 60px;
  width: 20vw;
  height: 20vw;
  background: #FCFEFC;
  border-radius: 5px;
}
#spritetarget {
  width: 20vw;
  height: 20vw;
  background-size: cover;
  background-image: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/29123/heart.png); /* horizontal spritesheet - image from http://preloaders.net */
  background-repeat: repeat-x;
}
<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>CodePen - GSAP Draggable 360° sprite slider</title>
  <link rel="stylesheet" href="./style.css">

</head>
<body>
<!-- partial:index.partial.html -->
<div class='spriteslider' id='spriteslider'>
  <div id='spritetarget'></div>
</div>

<p>Drag the box left/right to control the sprite's position.</p>
<!-- partial -->
  <script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/utils/Draggable.min.js'></script><script  src="./script.js"></script>

</body>
</html>

how to make variable accessible in requirejs callback function

I have a piece of code with requirejs

var path = this.formatPath(path);
require([path], function (template) {

//....code here

});

And I’d like to print the path inside the requirejs callback function.

Something like this

var path = this.formatPath(path);
require([path], function (template) {

//console.log(path)

});

However because the callback function is in a different scope, I can’t access it.

How do I pass the path variable in the callback function?

Filter table from database by 2 filed and from 1 table

I learn about the script autodidact and only PHP and Mysql and i don't know how to tell the things about the name part of script or syntrac or anything i just know how to use it and hard to for me find my question from goolge, please understand me, sorry.

There is posible to filter 2 field ‘firstname’ and ‘year’ from 1 database?
Condition 1 : When i type firstname by input only, it work, start from refresh first if not go to condition 3.
Condition 2 : When i select year by select option only, it work, start from refresf first if not go to condition 3.
Condition 3 : When i select year and type by input, it doesn’t work.

What i need is, when i select year 2009 and than when i just type ‘a’ Abdul and Agus selected from database, should only abdul selected from database.
I think the problem is my PHP and MYsql so i focus on them because i just know about them and forget about javascript.
Here my database ‘directory’ :
| firstname | status | year |
|:——— |:——:| :—-:|
| Agus | Alumni | 2008 |
| Abdul | Alumni | 2009 |
| David | Alumni | 2009 |
| Jelita | Student| |

index.php

<html>
<head>
<script>
function sortResult(str)
{
if (str=="")
  {
  document.getElementById("result").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("result").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","results.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="sortby" onchange="sortResult(this.value)">
            <option>Tahun</option>
            <option value="2008">2008</option>
            <option value="2009">2009</option>
</select>
<input name="sortby" onKeyUp="sortResult(this.value)" type="text">
</form>
<br>
<div id="result"><b>Results will be listed here.</b></div>

</body>
</html>

results.php

<?php
$q = $_GET['q'];

$con = mysqli_connect('localhost','root','','school');
if (!$con)
  {
  die('Could not connect: ' . mysqli_error($con));
  }

mysqli_select_db($con,"database"); 
$sql="SELECT * FROM directory where
status='Alumni' and tahun Like '%".$q."%' or
status='Alumni' and firstname Like '%".$q."%'";

$result = mysqli_query($con,$sql);

echo "<table border='1'>
<tr>
<th>ID</th>
<th>Fistname</th>
<th>Title</th>
<th>Graduation</th>
</tr>";

while($row = mysqli_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" .$row['noid']. "</td>";
  echo "<td>" .$row['firstname']. "</td>";
  echo "<td>" .$row['status']. "</td>";
  echo "<td>" .$row['tahun']. "</td>";
  echo "</tr>";
  }
echo "</table>";

mysqli_close($con);
?>

JS FullCalendar Recurring Event not having correct start time

first time posting here. I am using Javascript FullCalendar and I am trying to set up a simple recurring event. The problem is that its start time is not displayed correctly and the event itself is not appearing in the Week/Day View(I am assuming it’s because the start/end times are not being rendered correctly.) The recurring event is the one with title – Mathemathics. As show in the pictures, it displays a time of 12:00:00 which is incorrect as in the code I clearly set it to 16:00. It can be seen in the month view but in week and day it’s not showing up. Any tips and suggestions will be helpful, looked up all over the internet and the FullCalendar docs but couldn’t find anything related to my problem.

document.addEventListener('DOMContentLoaded', function() {
                var calendarEl = document.getElementById('calendar');
                var calendar = new FullCalendar.Calendar(calendarEl, {
                    initialView: 'dayGridMonth',
                    height: "90%",
                    slotMinTime: "06:00:00",
                    slotMaxTime: "20:30:00",
                    firstDay: 1,
                    eventTimeFormat: {
                        hour: '2-digit',
                        minute: '2-digit',
                        second: '2-digit',
                        meridiem: false
                    },
                    slotLabelFormat: {
                        hour: '2-digit',
                        minute: '2-digit',
                        meridiem: false,
                        hour12: false
                    },
                    headerToolbar: {
                        left: 'prev,next today',
                        center: 'title',
                        right: 'dayGridMonth,timeGridWeek,timeGridDay'
                        },
                    events: [{
                        title: 'Mathematics',
                        starTime: '16:00:00',
                        endTime: '17:30:00',
                        daysOfWeek: [1]
                    }, {
                        title: 'C++',
                        start: "2021-12-11T10:00:00",
                        end: "2021-12-11T12:00:00",
                    }]
                    });
                calendar.render();
            });

Month view

Week view

EDIT:
I am using FullCalendar v5.10.1

Bug in my recursive division algorithm (to generate maze randomly)

I’m having trouble generating a random maze. My algorithm creates the initial box where the maze will be. But I cannot seem to generate any walls inside of this box. I’m trying to use the recursive division algorithm. Here is my code:

class Maze {
    constructor(COLS,ROWS) {
        this.width = COLS;
        this.height = ROWS;
        this.COLS = this.width*2+1; // *2 To account for blocks which are replaced by walls, 
        this.ROWS = this.height*2+1; // so the hollow blocks will be half of the total blocks, and there 
        //will be +1 wall (because the border of the maze will be a wall on either side on both x and y axies.)
        this.dimentions = [this.COLS, this.ROWS];
        this.maze = this.initArray([]);

        // This will palce the border walls (the ones on the outside of the maze)
        this.maze.forEach((currentRow, index) => {
            if(index === 0 || index === this.ROWS-1) {
                currentRow.forEach((_, cellIndex) => {
                    this.maze[index][cellIndex] = ["BLACK_WALL"];
                });
            } else {
                this.maze[index][0] = ["BLACK_WALL"];
                this.maze[index][currentRow.length-1] = ["BLACK_WALL"];
            }
        });

        // Now do the "recursive division" method to generate the maze
        const randomWallStart = [[2,2], [this.COLS-3, this.ROWS-3]][this.randInt(0,2)]; // Picks top left or bottom right
        const randomWallEnd = [[this.COLS-3, 2], [2, this.ROWS-3]][this.randInt(0,2)]; // Picks the other corner
        this.recursiveDivision(randomWallStart, randomWallEnd);
    }

    randInt(min, max) { // Used in random generation of maze
        return Math.floor(Math.random()*(max-min))+min;
    }

    initArray(value) {
        return new Array(this.ROWS).fill().map(() => new Array(this.COLS).fill(value));
    }

    recursiveDivision(wallStart, wallEnd, its=0) {
        this.maze[wallStart[1]][wallStart[0]] = ["FLAG1"];
        this.maze[wallEnd[1]][wallEnd[0]] = ["FLAG2"];
        const randXpoint = this.randInt(wallStart[0], wallEnd[0]); // Doesn't matter which way round the max and min are.
        const randYpoint = this.randInt(wallStart[1], wallEnd[1]);

        const directionToBuildWall = wallStart[0] === wallEnd[0] ? 0 : 1; // 0 = x-axis 1 = y-axis

        const newWallStart = [randXpoint, randYpoint];
        let forwardsOrBackwards = 1;
        if(newWallStart[directionToBuildWall] > this.dimentions[directionToBuildWall]/2) {
            forwardsOrBackwards = -1;
        }

        let currentPosition = newWallStart;
        currentPosition[directionToBuildWall] +=  forwardsOrBackwards * 1;

        while(this.maze[currentPosition[1]][currentPosition[0]] != "BLACK_WALL") {
            this.maze[currentPosition[1]][currentPosition[0]] = ["BLACK_WALL"];
            currentPosition[directionToBuildWall] += forwardsOrBackwards*1;
        }

        if(its > Math.min(this.COLS-2)) {
            return;
        }
        const beginningPos = currentPosition.slice();
        beginningPos[directionToBuildWall] = 1; 
        this.recursiveDivision(currentPosition,beginningPos,its+1);

    }

  posToSpace(x) {
    return 2 * (x-1) + 1;
  }

  posToWall(x) {
    return 2 * x;
  }

  inBounds(r, c) {
    if((typeof this.maze[r] == "undefined") || (typeof this.maze[r][c] == "undefined")) {
      return false; // out of bounds
    }
    return true;
  }

  isGap(...cells) {
    return cells.every((array) => {
      let row, col;
      [row, col] = array;
      if(this.maze[row][col].length > 0) {
        if(!this.maze[row][col].includes("door")) {
          return false;
        }
      }
      return true;
    });
  }

  countSteps(array, r, c, val, stop) {

    if(!this.inBounds(r, c)) {
      return false; // out of bounds
    }

    if(array[r][c] <= val) {
      return false; // shorter route already mapped
    }

    if(!this.isGap([r, c])) {
      return false; // not traversable
    }

    array[r][c] = val;

    if(this.maze[r][c].includes(stop)) {
      return true; // reached destination
    }

    this.countSteps(array, r-1, c, val+1, stop);
    this.countSteps(array, r, c+1, val+1, stop);
    this.countSteps(array, r+1, c, val+1, stop);
    this.countSteps(array, r, c-1, val+1, stop);
  }

  display() {
    this.parentDiv = document.getElementById("maze-container");
    while(this.parentDiv.firstChild) {
      this.parentDiv.removeChild(this.parentDiv.firstChild);
    }
    const container = document.createElement("div");
    container.id = "maze";
    container.dataset.steps = this.totalSteps;

    this.maze.forEach((row) => {
      let rowDiv = document.createElement("div");
      row.forEach((cell) => {
        let cellDiv = document.createElement("div");
        if(cell?.join) {
          cellDiv.className = cell.join("");
        }
        rowDiv.appendChild(cellDiv);
      });
      container.appendChild(rowDiv);
    });

    this.parentDiv.appendChild(container);

    return true;
  }
}

const myMaze = new Maze(5,5);
myMaze.display();
body, html {margin: 0;}
#maze-container {
    position: absolute;
    top: 50%; left: 50%;
    transform: translate(-50%, -50%);
}

#maze {
  position: relative;
  background-color: #a7c53f;
  background-size: 8em 8em;
}
#maze div {
  display: flex;
}
#maze div div {
  position: relative;
  width: 1.2rem;
  height: 1.2rem;
}
#maze div div::after {
  position: absolute;
  left: -3px;
  top: -4px;
  text-align: center;
  text-shadow: 0 0 1px black;
  font-size: 1.2em;
  z-index: 10;
}
.FLAG1 {
    background-color: #a00;
}
.FLAG2 {
    background-color: #0a0;
}
#maze div div.BLACK_WALL, #maze div div.nubbin.BLACK_WALL, #maze div div.door.exit {
  background-color: #000;
  background-size: 0.5em 0.5em;
}
#maze div div.nubbin.BLACK_WALL::after {
  content: "";
}
#maze div div:nth-child(odd) {
  width: 1em;
}
#maze div:nth-child(odd) div {
  height: 1em;
}
<div id="maze-container"></div>

As you can see when you run the code, the walls are generated, but in the wrong places. So some touch each other (so you can’t move between them) and I cannot solve this problem.
I cannot get this “recursive division” algorithm to work properly.

show pop-up component when the user refresh the page from browser in Vue.js

I am working on a project. I have a create product page. When user fill out one of input boxes and decide to click another menu i can catch the click event beforeRouteLeave hooks and trigger the “page leaving warning pop up component”.

On the other hand I need to trigger that pop up again when user click browser’s page refresh button. How can I do that?
I have tried so many events such as “beforeonload onunload unload” so far. I can get default warning pop up that comes from browser and I could not override it.

I tried many times but without success. Anyone guide me?