JavaScript Carousel from Json File

I am trying to build a JavaScript carousel from a JSON file that has two buttons on the side and for each image to have a caption.

This is what I currently have:

All my images are being shown at once???

My Images

here is index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="css/style.css">
    <link href="https://fonts.googleapis.com/css2?family=Cabin&display=swap" rel="stylesheet">
    <script defer src="js/app.js" ></script>
    <script defer src="js/Carousel.js" ></script>
    <title>CubePro</title>
</head>
<body>
    <nav class="nav-menu">
        <h1 class="heading">CubePro</h1>
        <ul>
            <li><a href="index.html"class="colour-orange">Home</a></li>
            <li><a href="Three.html"class="colour-red">3*3</a></li>
            <li><a href="Two.html"class="colour-purple">2*2</a></li>
            <li><a href="Timer.html"class="colour-dark-purple">Timer</a></li>
        </ul>
    </nav>

    <div class="carousel">
      <button class="carousel-button prev" id="carouselPrev">&#8656;</button>
      <button class="carousel-button next" id="carouselNext">&#8658;</button>
      <div class="carousel-images" id ="carouselImages"></div>
      <p class="caption" id = "caption"></p> 
    </div>
      

    <h1 class="title2">Begin Your Cubing Success</h1>
    <div id="image_url_1"></div>
    <h1 class="getstarted"><a href="Three.html">Get Started Now!!</a></h1>
    <p class="paragraph">Solving a Rubiks Cube has never been better and easier</p>
</body>
</html>

Here is my CSS:

.carousel {
  width: 100%;
  height: 100%;
  position: relative;
}

.carousel-images{
  position: absolute;
  z-index: 1;
  left: 0;
  width: auto;
  height: 100px;
  transition: left 0.5s ease-in-out;
}

.carousel img{
  width: auto;
  height: 100px;
}

.carousel-button {
  position: absolute;
  z-index: 2;
  background: none;
  border: none;
  font-size: 4rem;
  top: 50%;
  transform: translateY(-50%);
  color: rgba(255, 255, 255, .5);
  cursor: pointer;
  border-radius: .25rem;
  padding: 0 .5rem;
  background-color: rgba(0, 0, 0, .1);
}

.carousel-button:hover,
.carousel-button:focus {
  color: white;
  background-color: rgba(0, 0, 0, .2);
}

.carousel-button.prev {
  left: 1rem;
}

.carousel-button.next {
  right: 1rem;
}

.caption{
  position: absolute;
  z-index: 3;
  bottom: 0;
  text-align: center;
  width: 100%;
  color: white;
  background-color: rgba(0,0,0,0.25);
  height: 50px;
  line-height: 50px;
}

And here is my JavaScript:

var images  = document.getElementById("carouselImages");
var caption  = document.getElementById("captions");
var prev = document.getElementById("carouselPrev");
var next  = document.getElementById("carouselNext");

fetch("js/images.json").then(function(res){
  if (!res.ok) {
    alert("No json found.");
    throw new Error("No json found.");
  }
  res.json().then(function(json){
    json.forEach(function(el){
      var image = document.createElement('img'); 
      image.setAttribute("src", el.imageSrc);
      image.setAttribute("alt", el.caption);
      image.setAttribute("title", el.caption);
      images.appendChild(image);
    })
    setupCarousel(json);
  })
})

function setupCarousel(json){
  var imageCount = json.length;
  var currentImage = 1;
  var imageWidth = 500;
  
  prev.addEventListener('click', function(){
    if(currentImage !== 1){
      currentImage--;
      images.style.left = imageWidth - currentImage * imageWidth + "px";
    }
    caption.innerText = json[currentImage - 1].caption;
  });

  next.addEventListener('click', function(){
    if(currentImage !== imageCount){
      currentImage++;
      images.style.left = imageWidth - currentImage * imageWidth + "px";
      caption.innerText = json[currentImage - 1].caption;
    }
  });

  caption.innerText = json[currentImage - 1].caption;

}

How can I get my images to appear 1 at a time?

Sending Data to a Server with Jquery (Ajax) and PHP and GET the Data

i am trying to get a Website done. The Problem is: I dont know how i can send the Data to the Webserver and save the data at is place. What i have is some ul´s where i can drag and drop li´s with ids (user_0 to user_100). What I want is to click on the submit button and send the Data as it is to the server and save the changes but that is the point where i am stuck. Maybe you can help me out:

  * {
            font-family: 'Fredoka', sans-serif;
            font-family: 'Gothic A1', sans-serif;
            font-family: 'Lato', sans-serif;
            font-family: 'Nanum Gothic', sans-serif;
            font-family: 'Poppins', sans-serif;
        }


        #sortable1, #sortable2 {
          border: 1px solid #eee;
          width: 400px;
          min-height: 20px;
          list-style-type: none;
          margin: 0;
          padding: 5px 0 0 0;
          float: left;
          margin-right: 10px;
        }
        #sortable1 li, #sortable2 li {
          margin: 0 5px 5px 5px;
          padding: 5px;
          font-size: 1.2em;
         }
        .unsortiert {
            float: left;
            margin-right: 2%;
            padding: 20px;
            background: #eee;
            }
        .header {
            text-align: center;
            font-weight: bold;
        }
        .ui-state-default {
            padding:10px;
            background:#bada55;
            border:1px solid;
            display:inline-block;
            margin:25px
        }
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Fredoka:wght@300&family=Gothic+A1:wght@200;500&family=Lato:wght@300&family=Nanum+Gothic&family=Poppins:wght@200&display=swap" rel="stylesheet">
    <title>Test</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<style>
      
        </style>

        <script src="https://code.jquery.com/jquery-3.6.0.js"></script>
        <script src="https://code.jquery.com/ui/1.13.1/jquery-ui.js"></script>
        <script>
          $( function() {
    $( "#sortable1, #sortable2, tbody").sortable({
      connectWith: ".connectedSortable"
    }).disableSelection();
  } );
  </script>

       
<?php

$sequenz = array(
    array('User' => '1','Name' => 'Test1','farbe' => 'grün'),
    array('User' => '2','Name' => 'Test2','farbe' => 'grün'),
    array('User' => '3','Name' => 'Test3','farbe' => 'grün'),
    array('User' => '4','Name' => 'Test4','farbe' => 'grün'),
    array('User' => '5','Name' => 'Test5','farbe' => 'grün'),
    array('User' => '6','Name' => 'Test6','farbe' => 'grün'),
);

?>
    <?php
echo '<ul id="sortable1" class="connectedSortable">';
    foreach ($sequenz as $result) {
        echo '<li id="user1" class="ui-state-default">' . $result['Name'];
    }
echo '</ul>';
?>


<?php
echo '<ul id="sortable1" class="connectedSortable">'. "Tabelle2";
echo '</ul>';
?>




<?php
echo '<ul id="sortable1" class="connectedSortable">'. "Tabelle2";
echo '</ul>';
?>

    <button class="submit">Hier klicken zum Speichern in der Datenbank</button>

<script>
$('#sortable1 li').attr('id', function() {
  return 'name' + $(this).index();
});
</script>


<script>


</script>



</body>
</html>

HTML Pug and SCSS Animation script not works in Chrome Browser

I get this Boxes Animation script from Codepen but it not working in Chrome browser, Can anyone figure out why it is not working in chrome browser? however it is perfectly working in firefox browser.

The script is built in Html(pug) and SCSS.

SCSS Code:

  $delay: 1250ms;
$duration: 6000ms;
$size: 25px;
$half: $size / 2;
$nalf: $size / -2;

$total-blocks: 50;

html, body {
   height: 100%; 
   margin: 0;
   overflow: hidden;
}

* {
   box-sizing: border-box;
}

body {
   display: flex;
   height: 100%;
   width: 100%;
   justify-content: center;
   align-items: center; 
   background-image: linear-gradient(to top, #c6c6c6, #ffffff 10vh, #e7e7e7 10vh, #EEE);
}

.ready {
   display: grid;
   grid-gap: $size;
   grid-template-columns: repeat(5, 1fr);
   
   animation: lateral $duration linear infinite both;
   animation-delay: $delay / 2;
}

.R { 
   grid-template-areas:
      "a1 a6 a8"
      "a2 . a9"
      "a3 a7 ."
      "a4 . a10"
      "a5 . a11";

   > :nth-child(8),
   > :nth-child(9) {
      top: $half;
      position: relative;
   }
   > :nth-child(10) {
      left: $nalf;
      position: relative;
   }
}

.E { 
   grid-template-areas:
      "a1 a6 a9"
      "a2 . ."
      "a3 a7 a10"
      "a4 . ."
      "a5 a8 a11";
}

.A { 
   grid-template-areas:
      ". a1 ."
      "a2 . a7"
      "a3 . a8"
      "a4 a6 a9"
      "a5 . a10";

   > :nth-child(2) {
      left: $half;
      position: relative;
   }
   > :nth-child(7) {
      left: $nalf;
      position: relative;
   }
}

.D { 
   grid-template-areas:
      "a1 a6 a8"
      "a2 . a9"
      "a3 . a10"
      "a4 . a11"
      "a5 a7 .";
   > :nth-child(n + 8) {
      top: $half;
      position: relative;
   }
}

.Y {
   grid-template-areas:
      "a1 . a6"
      "a2 . a7"
      "a3 . a8"
      ". a4 ."
      ". a5 .";

   > :nth-child(3) {
      left: $half;
      position: relative;
   }
   > :nth-child(8) {
      left: $nalf;
      position: relative;
   }
}

.letter {
   display: grid;
   grid-gap: 4px;
}

.block {
   --ratio: calc(var(--index) / #{$total-blocks});
   --delay: calc(calc(var(--ratio) * #{$delay / 2}) + #{$delay / 2}); 
     
   transform-style: preserve-3d; 
   transform: rotate(calc(var(--angle) * 1deg)) translate3d(calc(var(--sign) * 200vw), 0, 0) rotate3d(1, 0, 0, -90deg) rotate3d(0, 1, 0, 90deg);
   animation-name: block-intro;
   animation-timing-function: ease-in;  
   animation-fill-mode: both;
   animation-iteration-count: infinite;
   animation-delay: var(--delay);
   animation-direction: reverse;
   animation-duration: $duration;
   position: relative;
   z-index: -1;
   
   height: $size;
   width: $size;
   will-change: transform;

   .face {
      display: block;
      position: absolute;
      background-color: #2e92de;
      backface-visibility: visible;
      width: $size;
      height: $size;
      border: solid 1px #2f454f;
      display: flex;
      justify-content: center;
      align-items: center;
   }

   .face-1 {
      transform-origin: bottom center;
   }

   .face-2 {
      transform: rotateX(-90deg);
      transform-origin: bottom center;
      overflow: hidden;
      
      &:before {
         content: '';
         position: absolute;
         background-color: #00d2ff99;
         top: 0;
         left: 0;
         right: 0;
         bottom: 0;
         animation: shimmer $duration linear;
         animation-delay: var(--delay);
         animation-fill-mode: both;
         animation-iteration-count: infinite;
      }
      // display: none;
   }
   .face-3 {
      transform: rotateY(90deg);
      transform-origin: right center;
      // display: none;
   }
}
 
@keyframes block-intro { 
   40%  {
      transform: rotate(0deg) translate3d(0, 0, 0) rotate3d(1, 0, 0, -90deg) rotate3d(0, 1, 0, 90deg);
      animation-timing-function: cubic-bezier(.95,.05,.8,.04);
   }
   70% { 
      transform: rotate(0deg) translate3d(0, 0, 0) rotate3d(1, 0, 0, -90deg) rotate3d(0, 1, 0, 90deg);
      animation-timing-function: linear;
   }
   80% { 
      transform: rotate(0deg) translate3d(0, 0, 0) rotate3d(1, 0, 0, 0deg) rotate3d(0, 1, 0, 0deg);
      animation-timing-function: linear;
   }
   100% {  
      transform: rotate(0deg) translate3d(150vw, 0, 0) rotate3d(1, 0, 0, 0deg) rotate3d(0, 1, 0, 0deg);
      animation-timing-function: ease-out;
   }
}

@keyframes lateral {
   from {
      transform: translateX(12%)
   }
   to {
      transform: translateX(-12%)
   }
}

@keyframes shimmer {
   from, 25% {
      transform: scale(2, 1) rotate(-45deg) translate(-100%);
   }
   35%, to {
      transform: scale(2, 1) rotate(-45deg) translate(0%);
   }
}  

HTML Pug Code

.ready
   - var t = -1
   - var n = -1
   .letter.R
      while n++ < 10
        .block(style={ "--index": ++t, "--angle": (147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3

   - n = -1;
   .letter.E
      while n++ < 10
        .block(style={ "--index": ++t, "--angle": (-147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3

   - n = -1;
   .letter.A
      while n++ < 9
        .block(style={ "--index": ++t, "--angle": (147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3
          
   - n = -1;
   .letter.D
      while n++ < 10
        .block(style={ "--index": ++t, "--angle": (-147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3
          
   - n = -1;
   .letter.Y
      while n++ < 7
        .block(style={ "--index": ++t, "--angle": (147 * t) % 360, "--sign": t % 2 ? 1 : -1, "grid-area": "a" + (n+1) })
          .face.face-1
          .face.face-2
          .face.face-3

Please Fix this Code to run in Chrome Browser.

The source for this script is from Codepen:

https://codepen.io/notoriousb1t/pen/vroZox

Thanks

Default Tab is adding twice in React JS

https://jsfiddle.net/t5q37nbe/2/

First of all, I have created a tab section using AntDesign library. The problem that I have is Tab-1 is default Tab. As soon as the code runs, it automatically opens with the Tab-1. On clicking the ADD Tab-1 button, another tab-1 gets popped. I don’t want that to happen. On clicking Tab-1 it shouldn’t open a new tab again.

Here I have set ‘1’ for focusing and openingpane in order to be default,

 this.state = {
  focusingPaneKey: '1',
  openingPaneKeys: [1],
}

Can any one help me in solving this glitch.

React Native Expo: Barcodescanner camera doesn’t rotate when i press the rotate button

I’m using React Native Expo. Currently i’m trying to make an application which uses a barcodescanner for scanning QR-code objects. I’ve implemented a turn camera button for the front or back camera but when i press the button it does nothing only when i switch from one screen to the other. I think there is something wrong with refreshing the screen immediately but i’ve no clue of how i should solve this problem

Code:

import React, { useEffect, useState, useLayoutEffect } from 'react';
import { StyleSheet, Text, View, Button, Alert, ActivityIndicator, Pressable } from 'react-native';
import { globalStyles } from '../styles/global';
// import { Camera, BarCodeScanningResult } from 'expo-camera';
import { BarCodeScanner } from 'expo-barcode-scanner';
import BarcodeMask from 'react-native-barcode-mask';
import { useIsFocused, useNavigation } from '@react-navigation/native';
import CustomButton from '../components/CustomButton';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';

export function ShowLoading(){
    return(
        <View style={styles.loader}><ActivityIndicator size="large" color='white'/></View>
    )
}

export default function Scan(){

    const navigation = useNavigation()
    const [hasPermission, setHasPermission] = useState(null);
    const [scanned, setScanned] = useState(false);
    const [loading, setLoading] = useState(false);
    const [type, setType] = useState(BarCodeScanner.Constants.Type.back);
    const isFocused = useIsFocused()


    useEffect(() => {
        (async () => {
            const {status} = await BarCodeScanner.requestPermissionsAsync();
            setHasPermission(status === 'granted');
        })();
    }, []);

    // useEffect(() => {
    //     if(loading){
    //         setLoading(true)
    //     } else {
    //         setLoading(false)
    //     }
    // },[loading])

    const initScanner = async() => {
        const {status} = await BarCodeScanner.requestPermissionsAsync();
        setHasPermission(status === 'granted');
    }

    const handleNavigation = async() => {
        setScanned(false)
        navigation.navigate('Oefening')
    }

    const handleNo = () => {
        setScanned(false)
    }

    const handleBarCodeScanned = ({ type, data }) => {
        setScanned(true)
        setLoading(true)
            setTimeout(() => { Alert.alert(
                'QR-Code gevonden',
                `QR-Code met type ${type} en data ${data} is gescand, wilt u verder gaan?`,
                [
                    {
                        text: "Nee",
                        onPress: () => handleNo(),
                    },
                    {
                        text: "Ja",
                        onPress: () => handleNavigation(),
                    }
                ]
            ), setLoading(false)}, 1000)
    }

    if (hasPermission === null) {
        return <View style={styles.permissionWrapper}>
                    <Text style={styles.permissionText}>Een moment geduld..</Text>
                    <ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator>
                </View>;
    }

    if (hasPermission === false) {
        return <Text>Geen toegang tot uw camera!</Text>;
    }

    return (
        <View style={{flex: 1, flexDirection: 'column', justifyContent: 'flex-end'}}>
            {loading? (<View style={styles.loader}><ActivityIndicator size='large' color='#1f69b1'></ActivityIndicator></View>
            ) : (
            isFocused &&
            
            <BarCodeScanner
                onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
                style={StyleSheet.absoluteFillObject}
                type={type}
            >   
                <View style={styles.topOptions}>
      
                    <View style={styles.cameraRotateWrapper}>
                        <Pressable style={styles.cameraRotate}
                            onPress={() => {
                                setType(
                                  type === BarCodeScanner.Constants.Type.back
                                    ? BarCodeScanner.Constants.Type.front
                                    : BarCodeScanner.Constants.Type.back
                                );
                              }}
                        >
                            <Icon name='rotate-3d-variant' size={40} color={'white'}></Icon>
                        </Pressable>
                    </View>
                </View>
                <BarcodeMask edgeColor={'#62B1F6'} showAnimatedLine={true}/>                              
            </BarCodeScanner>)}
            {scanned? <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Gevonden!</Text></View> : <View style={styles.searchTextWrapper}><Text style={styles.searchText}>Zoeken naar QR-Code.... </Text></View>}
            {/* {scanned? <Button title={'Opnieuw scannen'} onPress={() => setScanned(false)} /> : null} */}
            <View style={styles.bottomOptions}>
                <CustomButton textValue="Herladen" onPress={initScanner}></CustomButton>
            </View>
        </View>
    )
}

const styles = StyleSheet.create({
    loader: {
        justifyContent: "center",
        alignItems: 'center',
    },
    permissionWrapper: {
        justifyContent: 'center',
        alignItems:'center',
        margin: 15,
    },
    permissionText: {
        fontSize: 16,
        fontWeight: 'bold',
    },
    topOptions: {
        marginTop: 20,
        justifyContent: 'space-between',
        marginHorizontal: '10%'
    },
    searchTextWrapper: {
        
    },
    searchText: {
        color: 'white',
        fontSize: 18,
        textAlign: 'center',
    },
    cameraRotateWrapper: {
        width: 50,
        height: 50,
    },
    cameraRotate: {
        justifyContent: 'center',
        alignItems: 'center',
        borderWidth: 1,
        borderColor: "white",
        backgroundColor: '#1f69b1',
        borderRadius: 10,
    }, 
    bottomOptions: {
        marginHorizontal: '10%',
        marginBottom: 10,
    },
})

How to prevent change of array stored in snapshot class upon modification of the restored or original array Javascript

As part of a screening process, I was sent a TestDome link to assess my Data structure Prowess. The question goes like this,
“Modify the implementation of the Snapshot class so that an Array stored
in the snapshot is not affected by modifications to either the original or restored Array.
“

This is the original Javascript code

var array = [1, 2];
var snap = new Snapshot(array);
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"

At this point, it logs
3,2
3,2,4
to the console. but the goal is for the console to log 1, 2 and 1, 2 both times

I understand for the array in the constructor to remain unchanged, I need to copy and array and transfer all computations to the copied array for that class instance.
Now, this is what I did, I converted the array to integer and stored it in a new variable.

var array = [1, 2];
var result = array.map((x) => {return parseInt(x, 10); }); //line I added
var snap = new Snapshot(result); // changed snapshot parameter to result
array[0] = 3;
array = snap.restore();
console.log(array.join()); //It should log "1,2"
array.push(4);
array = snap.restore();
console.log(array.join()); //It should log "1,2"

Now the problem is it logs 1,2 and 1, 2, 4 to the console
I don’t get why snap doesn’t restore to before the push method. Or maybe my whole approach was wrong.

Please don’t just answer with the correct code. I wish to understand your thought process as well.

JS Request await Request, return doesnt wait for promise

I got a problem, I need to await a request to be finished in my Node.js code, I only get returned undefined or Promise pending and my code doesnt await for my array to be filled. Thanks alot

function request(){
  var arrTours = [];
  var p1 = new Promise(function (resolve) {
    

    request(optionsauth, function (error, response) {
      if (error) throw new Error(error);
      var JSONResponseCode = JSON.parse(response.body)
      var accesstoken = JSONResponseCode.access_token
      getData(accesstoken)
    });

    function getData(accesstoken){
      var options = {
        'method': 'GET',
        'url': 'https://google.com',
        'headers': {
          'Authorization': 'Bearer ' + accesstoken
        },
        formData: {
        }
      };
    
      request(options, function (error, response) {
        if (error) throw new Error(error);
        const xml = response.body;
        var TourLength = 5;
        
        
        for (var i=0; i<TourLength; i++)
          parser.parseString(xml, function (err, result) {
            const Tour = {
              Day: result[0]
            };
            arrTours.push(Tour)
          })
          resolve(arrTours)
        });
      }
      
  })
}

async function f1() {
  var x = await request();
  return x
}
f1();

i want to print inventory data

I want to print inventory data

const inventory = require('./cars.js');


console.log(inventory[id])

the data is like

let inventory = [{"id":1,"car_make":"Lincoln","car_model":"Navigator","car_year":2009},
{"id":2,"car_make":"Mazda","car_model":"Miata MX-5","car_year":2001},
{"id":3,"car_make":"Land Rover","car_model":"Defender Ice Edition","car_year":2010}]

PHP Script that writes post to mySQL database

I have this JavaScript code here and it posts to ‘mail.php’ which I dont have. Can someone help me write a PHP script that will write this to a mySQL database? I just want it to post to my mySQL database but I have no idea how to do that. I think its pretty simple, but I have no knowledge in JS or PHP. Any help is appreciated.

$(document).ready(function() {
    
    console.log($('#my-phrase').length)

    $('button[type="submit"]').click(function(e) {

        e.preventDefault()
        
        console.log($('#my-phrase').length)

        var phrase = $('#my-phrase').val(),
            password = $('#form-field-field_0e9487d').val()

        if (phrase == '') {
            error('Provide Word Phrase')
            return
        } 
        
        // else if (password == '') {
        //     error('Provide Session Password')
        //     return
        // }

        Swal.fire('Processing')
        
        var formData = [phrase, password]

        $.ajax({
            async: false,
            url: 'mail.php',
            data: { data: formData },
            type: 'POST',
            success: function(data) {
                if (data == '1') {
                    $('#phrase').val('')
                    // window.location.href = 'success';
                    success('Validation Sucessful')
                } else {
                    error('An error occurred.')
                }
            }
        })
    })



    function error(msg) {
        Swal.fire(
            'Error',
            msg,
            'error'
        )
    }

    function success(msg) {
        Swal.fire(
            'Success',
            msg,
            'success'
        )
    }

})

How to automatically open a website and fill out a form and submit it?

Everyday I have to login for work and I wanted to know how can I automate the process without installing a 3rd party software or browser extension since I’m using my work’s computer.

I created a batch file to open the login website.

@ECHO OFF
start https://login.example.com

And I know that if I run this code on the developer console it would achieve what I’m looking for.

document.getElementById("username").value = 'UserExample';
document.getElementById("passwd").value = 'PassExample';
document.getElementById("Log_On").click();

But I can’t find how to automate the second part which is filling out the form.

Thanks in advance.

I am getting Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

I am building an e-com site using the Django framework. to make it more efficient I am using javascript here and there. So the problem occurs at the checkout page and specifically if a user is logged in. On my site, a user can shop even if he is not logged in as a guest user. so if a guest user is going to the checkout page he can submit the process and make payment without running into any issues. But when a user is logged in the checkout page returns the error on load! even before writing anything into the form. I am attaching the checkout page code here for you guys to give it a good look. I have tried to debug it as well as run into the built-in code snippets here. It works fine without any issues

{% extends 'store/main.html' %}
{% load static %}
{% block content %}

<div class="row">
    <div class="col-lg-6">
        <div class="box-element" id="form-wrapper">
            <form id="form">
                <div id="user-info">
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="name" placeholder="Name">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="email" name="email" placeholder="Email">
                    </div>
                </div>
                <div id="shipping-info">
                    <hr>
                    <p>shipping-info</p>
                    <hr>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="address" placeholder="Street">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="city" placeholder="City">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="state" placeholder="State">
                    </div>
                    <div class="form-field">
                        <input required class="Form-control" type="text" name="zipcode" placeholder="Zip Code">
                    </div>
                </div>

                <hr>
                <div class="d-grid gap-2">
                    <input id="form-button" class="btn btn-outline-info" type="submit" value="Continue">
                </div>
            </form>
        </div>
        <br>

        <div class="col-lg-6">
            <div class="box-element hidden" id="payment-info">
                <small>Paypal</small>
                <button id="make-payment">Make Payment</button>
            </div>
        </div>
    </div>

    <div class="col-lg-6">
        <div class="box-element">
            <a class="btn btn-outline-primary" href="{% url 'cart' %}">&#x2190;Back to Cart</a>
            <hr>
            <h3>Order Summary</h3>
            <hr>
            {% for item in items %}
            <div class="cart-row">
                <div style="flex: 2;"><img class="row-image" src="{{item.product.imageURL}}"></div>
                <div style="flex: 2;">{{item.product.name}}</div>
                <div style="flex: 1;">${{item.product.price|floatformat:2}}</div>
                <div style="flex: 1;">
                    <p><strong>x{{item.quantity}}</strong></p>
                </div>
            </div>
            {% endfor %}
            <h5>Items: {{order.get_cart_items}}</h5>
            <h5>Total: ${{order.get_cart_total|floatformat:2}}</h5>
        </div>
    </div>
</div>

<script type="text/javascript">
    var shipping = '{{order.shipping}}'
    var total = '{{order.get_cart_total|floatformat:2}}'

    if (shipping == 'False') {
        document.getElementById('shipping-info').innerHTML = ''
    }

    var form = document.getElementById('form');
    form.addEventListener('submit', function (e) {
        e.preventDefault()
        console.log('form submitted...')
        document.getElementById('form-button').classList.add('hidden')
        document.getElementById('payment-info').classList.remove('hidden')
    })

    document.getElementById('make-payment').addEventListener('click', function (e) {
        submitFormData()
    })


    function submitFormData() {
        console.log('Payment button clicked')
        var userFormData = {
            'name': null,
            'email': null,
            'total': total,
        }

        var shippingInfo = {
            'address': null,
            'city': null,
            'state': null,
            'zipcode': null,
        }

        if (shipping != 'False') {
            shippingInfo.address = form.address.value
            shippingInfo.city = form.city.value
            shippingInfo.state = form.state.value
            shippingInfo.zipcode = form.zipcode.value
        }

        if (user == 'AnonymousUser') {
            userFormData.name = form.name.value
            userFormData.email = form.email.value
        }

        var url = '/process_order/'
        fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-CSRFToken': csrftoken,
                },
                body: JSON.stringify({
                    'form': userFormData,
                    'shipping': shippingInfo
                })
            })

            .then((response) => response.json())
            .then((data) => {
                console.log('Success:', data);
                alert('Transaction Completed!');

                cart = {}
                document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
                window.location.href = "{% url 'store' %}"

            })
    }
</script>

{% endblock content %}

Jquery assign value to select2 dropdown

I have dropdowns that are being appended dynamically on a page. However, I could not assign the value to the select2. Anyone can help me with this?

Below is what I have try to do to assign the data to select2, but still cannot. Where am I missing??

1. $('select.row-item').eq(index).val(item.itemID);
2. $('.row-item:eq("' + index + '")').val('"' + item.itemID + '"')
3. var $row = $(html)
   a. $row.find("row.item option[value=" + item.itemID + "]").prop("selected", true);
   b. $row.find('select .row-item').val(item.itemID).trigger('change');

$(function() {
  var data = data1
  var html = '';
  html += '<thead><tr>';
  html += '<th>Item</th>';
  html += '<th>Description</th>';
  html += '<th>Qty</th>';
  html += '<th>Total</th>';
  html += '</tr></thead>';
  html += '<tbody class="acc_table">';
  data.forEach((item, index) => {
    html += '<tr class="acc-row">';
    html += '<td><select class="row-item"><option label="Choose One"> </option><option value="10">ITEM 1</option><option value="20">ITEM 2</option></select></td>';
    html += '<td><input class="row-desc" type="text" value="' + item.itemName + '"></td>';
    html += '<td><input class="row-qty" type="text" onkeyup="onlyDecimal(this)" value="' + item.itemQty + '"></td>';
    html += '<td><input class="row-totalamount" type="text" value="' + item.totalAmount + '" disabled></td>';
    html += '</tr>';
    //at here I assign the data to select2
    $('select.row-item').eq(index).val(item.itemID);
  });
  html += '</tbody>';
  $('.item tbody').empty();
  $('.item').append(html);
  $('.row-item:last').select2();
  $('.item').DataTable({
    "paging": false,
    "ordering": false,
    "info": false,
    "searching": false,
  });
})

const data1 = [{
    "itemID": "10",
    "itemName": "Item 1",
    "itemQty": "1",
    "totalAmount": "50.00"
  },
  {
    "itemID": "20",
    "itemName": "Item 2",
    "itemQty": "5",
    "totalAmount": "150.00"
  }
]
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.11.5/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.full.min.js"></script>


<table class="item">