How to save the name of object in array object?

I have an array containing 7 objects named is NewClass.

enter image description here

When I make some changes to the objects, the object has lost its original NewClass name.

Like that:

enter image description here

In arrray[6] lost NewClass name.

So is there any way I can keep the NewClass name for that object?

Here is my function to handle this array:

useEffect(() => {
console.log(layers);
if (selectedLayerIndex && layers.length > 0) {

  console.log(
    'x',
    layers.map((x) => {
      if (x.feature.properties.editLayerId === selectedLayerIndex) {
        console.log(x);

        return (x = {
          ...x,
          options: { ...x.options, color: 'cyan', fillColor: 'cyan' },
        });
      }
      return x;
    })
  );
  
}

}, [selectedLayerIndex]);

Thank you so much!

The Submit button is not working as expected

I have a form Data in the html like the below,

Blade file:

<form method="post" action="someURL" id="register">
<input type="text" name="name" id="name" />
<div class="error">{{ $errors->first('name') }}</div>
<input type="email" name="email" id="email"/>
<div class="error">{{ $errors->first('email') }}</div>
<textarea name="body" id="message"> Enter your message here</textarea>
<div class="error">{{ $errors->first('message') }}</div>
<input type="submit" id="btnSubmit" disabled />
</form>


<script>
const button = document.querySelector("#btnSubmit");
const buttonExpirationDataKey = 'button-disabled-expiration';

let startButtonStateCheck = () => {
  button.dataset.interval = setInterval(updateButtonState, 1000);
}

let updateButtonState = () => {
  let expirationDate = new Date(button.dataset.enabledAt);
  
  if (expirationDate < new Date()) {
    button.disabled = false;
    clearInterval(button.dataset.interval);
  } else {
    button.disabled = true;
  }
}

let buttonDisableExpiration = localStorage.getItem(buttonExpirationDataKey);
if (!buttonDisableExpiration) {
  // no button state in localStorage, enable button
  button.disabled = false;
} else {
  // button state held in localStorage, check every 1s for expiration to enable the button again
  button.dataset.enabledAt = buttonDisableExpiration;
    updateButtonState();
  startButtonStateCheck();
}

button.addEventListener("click", () => {
 var form = document.getElementById("register");
  var fields = ["name", "email", "body"];
   var i, l = fields.length;
    var fieldname;
     for (i = 0; i < l; i++) {
      fieldname = fields[i];
       if (form[fieldname].value === "") {
          button.disabled = false;
          }
          else{
           button.disabled = true;
           let now = new Date();
           let expirationTime = 1000 * 10; 
           let expirationDate = new Date(now.getTime() + expirationTime);
           localStorage.setItem(buttonExpirationDataKey, expirationDate);
            button.dataset.enabledAt = expirationDate;
            startButtonStateCheck();
          }
       }
 });

</script>

In controller::

 $data = request()->validate([
         'name' => 'required',
         'email'   => 'required|email',
         'body' =>  'required',
        
      ]);

I have validated the fields in the controller.

The Submit button on click should check whether all the Input Values were given, If either one of the values is missing, the Submit button should be Enabled, even on click. I have given the validation in the controller

In my code, the submit button is disabled every time, when it is clicked even without the input values. But, it shows the error as This field is required near the input fields, when we click the submit button.

I need the submit button to be Disabled on click, when all the input values were given and then storing the button Enabled and Disabled in the Local storage.

When a user submits the form, without entering the form input, the button should be Enabled.

But, the submit button is not working as expected. It gets disabled, even without the form inputs

How could I do this? Could anyone please help?

Discordjs cooldown database with sequalize unique id error

I have made a cooldowns database with sequalize and sqlite3 for my discord bot. This is to add individual cooldowns for certain commands however I am getting an error that says “id must be unique” even when I turn off the unique: true to unique: false or even make a new database storage for the other command. Below is the full error.

node:internal/process/promises:246
          triggerUncaughtException(err, true /* fromPromise */);
          ^

Error
    at Database.<anonymous> (C:UsersbradeDesktopBear battlesnode_modulessequelizelibdialectssqlitequery.js:179:27)
    at C:UsersbradeDesktopBear battlesnode_modulessequelizelibdialectssqlitequery.js:177:50
    at new Promise (<anonymous>)
    at Query.run (C:UsersbradeDesktopBear battlesnode_modulessequelizelibdialectssqlitequery.js:177:12)
    at C:UsersbradeDesktopBear battlesnode_modulessequelizelibsequelize.js:311:28
    at async SQLiteQueryInterface.insert (C:UsersbradeDesktopBear battlesnode_modulessequelizelibdialectsabstractquery-interface.js:308:21)
    at async model.save (C:UsersbradeDesktopBear battlesnode_modulessequelizelibmodel.js:2432:35)
    at async Function.create (C:UsersbradeDesktopBear battlesnode_modulessequelizelibmodel.js:1344:12) {
  name: 'SequelizeUniqueConstraintError',
  errors: [
    ValidationErrorItem {
      message: 'id must be unique',
      type: 'unique violation',
      path: 'id',
      value: '250412979835764738',
      origin: 'DB',
      instance: cooldown {
        dataValues: {
          id: '250412979835764738',
          expiry: 1655869677206,
          command: 'hunt',
          updatedAt: 2022-06-22T03:42:57.207Z,
          createdAt: 2022-06-22T03:42:57.207Z
        },
        _previousDataValues: { id: undefined, expiry: undefined, command: undefined },
        uniqno: 1,
        _changed: Set(3) { 'id', 'expiry', 'command' },
        _options: {
          isNewRecord: true,
          _schema: null,
          _schemaDelimiter: '',
          attributes: undefined,
          include: undefined,
          raw: undefined,
          silent: undefined
        },
        isNewRecord: true
      },
      validatorKey: 'not_unique',
      validatorName: null,
      validatorArgs: []
    }
  ],
  parent: [Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: cooldown.id] {
    errno: 19,
    code: 'SQLITE_CONSTRAINT',
    sql: 'INSERT INTO `cooldown` (`id`,`expiry`,`command`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5);'
  },
  original: [Error: SQLITE_CONSTRAINT: UNIQUE constraint failed: cooldown.id] {
    errno: 19,
    code: 'SQLITE_CONSTRAINT',
    sql: 'INSERT INTO `cooldown` (`id`,`expiry`,`command`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5);'
  },
  fields: [ 'id' ],
  sql: 'INSERT INTO `cooldown` (`id`,`expiry`,`command`,`createdAt`,`updatedAt`) VALUES ($1,$2,$3,$4,$5);'
}

Here is the code for my daily command.

const { SlashCommandBuilder } = require('@discordjs/builders')
const ms = require('ms')
const { defaultColor } = require('../../command-imports')

module.exports = {
    data: new SlashCommandBuilder()
    .setName('daily')
    .setDescription('Claim your daily reward.'),

    async execute (interaction, Cooldowns) {
        let getCooldown = await Cooldowns.findOne({where: {id: interaction.user.id}}) // Finds if user has cooldown
        let cooldownTime = getCooldown?.expiry

        if(getCooldown && cooldownTime > new Date().getTime()) { // If cooldown is active run this
            return interaction.reply({content: `You are still under cooldown! Please wait **${ms(cooldownTime - new Date().getTime(), {long: true})}**`})
        } else if (getCooldown) { // If cooldown is expired remove from db and run rest of code
            Cooldowns.destroy({where: {id: interaction.user.id, command: 'daily'}})
        }

        const claimedDaily = {
            color: defaultColor,
            description: "You have recieved N/A from your daily reward"
        }
        interaction.reply({embeds: [claimedDaily]})
        Cooldowns.create({ // Creates 5 minute cooldown for hunt command
            id: interaction.user.id,
            expiry: new Date().getTime() + (60000 * 5),
            command: 'daily'
        })
    }
}

Here is my hunt command.

const { SlashCommandBuilder } = require('@discordjs/builders')
const { errorColor, defaultColor } = require('../../command-imports')
const ms = require('ms')

module.exports = {
    data: new SlashCommandBuilder()
    .setName('hunt')
    .setDescription('Hunt for a chance at finding a bear.'),

    async execute(interaction, Cooldowns, Economy) {

        let getCooldown = await Cooldowns.findOne({where: {id: interaction.user.id, command: 'hunt'}}) // Finds if user has cooldown
        let getUser = await Economy.findOne({where: {id: interaction.user.id}})
        if(!getUser) {
            getUser = await Economy.create({id: interaction.user.id, coins: 0})
        }
        let cooldownTime = getCooldown?.expiry

        if(getCooldown && cooldownTime > new Date().getTime()) { // If cooldown is active run this
            return interaction.reply({content: `You are still under cooldown! Please wait **${ms(cooldownTime - new Date().getTime(), {long: true})}**`})
        } else if (getCooldown) { // If cooldown is expired remove from db and run rest of code
            Cooldowns.destroy({where: {id: interaction.user.id, command: 'hunt'}})
        }


        let whichExecute = Math.floor(Math.random() * 8) + 1 // 7/8 Chance for coins 1/8 Chance for bears

        if(whichExecute <= 7) { 
            let coinsFound = Math.floor(Math.random() * 10) + 1 // Picks random coin amount between 1 - 10
            const nothingFound = {
                color: errorColor,
                description: `No bear was found however you found ${coinsFound} :coin: n You have ${getUser.coins} :coin:` // Displays coins earned and total coins
            }
            interaction.reply({embeds: [nothingFound]}) 
            await Economy.update({coins: getUser.coins + coinsFound}, {where: {id: interaction.user.id}}) // Updates user in db
            Cooldowns.create({ // Creates 5 minute cooldown for hunt command
                id: interaction.user.id,
                expiry: new Date().getTime() + (60000 * 5),
                command: 'hunt'
            })
        }
        else if(whichExecute === 8) {
            const bearFound = { // Displays bear found
                color: defaultColor,
                description: "You found placeholder_beartype :bear:;;"
            }
            interaction.reply({embeds: [bearFound]})
            Cooldowns.create({ // Creates 5 minute cooldown for hunt command
                id: interaction.user.id,
                expiry: new Date().getTime() + (60000 * 5),
                command: 'hunt'
            })
        }
    }
}

I still get the error for unique id even though it should be stored with the same id but under a different command name. This error doesn’t appear until I run both commands (doesn’t matter the order) for example I do /hunt and then do /daily later on. Any help fixing this would be great if you have any questions or stuff I can clarify let me know.

Unable to access value through SQLite storage in react-native

I’m trying to access some data input on one page by adding it to sqlite database and then displaying it on another page from the created sqlite database.

The value is not being printed, how can I check if the data is being added to the database in the first place?

I am creating a database and a table, and taking an input value on the home page and passing that to the database.

Next, I navigate to another page and display the data that was previously input from the database.

I don’t know how many more details I can add.

import React, {useEffect, useState} from 'react';
import {StyleSheet, View, Text, Pressable, Alert} from 'react-native';
import {NavigationContainer} from '@react-navigation/native';
import {createStackNavigator} from '@react-navigation/stack';
import CustomButton from './utils/CustomButton';
import sqlite from 'react-native-sqlite-storage';
import {TextInput} from 'react-native-gesture-handler';

const Stack = createStackNavigator();

const db = sqlite.openDatabase(
  {
    name: 'MainDB',
    location: 'default',
  },
  () => {},
  error => {
    console.log(error);
  },
);

function ScreenA({navigation}) {
  const [info, setInfo] = useState('');

  useEffect(() => {
    createTable();
    getData();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const onPressHandler = () => {
    navigation.navigate('ScreenB');
  };

  const createTable = () => {
    db.transaction(tx => {
      tx.executeSql(
        'CREATE TABLE IF NOT EXISTS ' +
          'Data ' +
          '(ID INTEGER PRIMARY KEY AUTOINCREMENT, Info TEXT);',
      );
    });
  };

  const getData = () => {
    try {
      db.transaction(tx => {
        tx.executeSql('SELECT Info FROM Data', [], (_tx, results) => {
          var len = results.rows.length;
          if (len > 0) {
            navigation.navigate('ScreenB');
          }
        });
      });
    } catch (error) {
      console.log(error);
    }
  };

  const setData = async () => {
    if (info.length === 0) {
      Alert.alert('warning', 'please enter data');
    } else {
      try {
        await db.transaction(async tx => {
          await tx.executeSql('INSERT INTO Data (Info) VALUE (?)', [info]);
        });
        navigation.navigate('ScreenB');
      } catch (error) {
        console.log(error);
      }
    }
  };

  return (
    <View style={styles.body}>
      <Text style={styles.text}>hello</Text>
      <TextInput
        style={styles.input}
        placeholer="enter your data"
        onChangeText={value => setInfo(value)}
      />
      <CustomButton
        title="go to data"
        color="#1eb900"
        onPressFunction={setData}
      />
    </View>
  );
}

function ScreenB({navigation, route}) {
  const [info, setInfo] = useState('');

  const onPressHandler = () => {
    navigation.navigate('ScreenA');
  };

  useEffect(() => {
    getData();
  }, []);

  const getData = () => {
    try {
      db.transaction(tx => {
        tx.executeSql('SELECT Info FROM Data'),
          [],
          (_tx, results) => {
            let len = results.rows.length;
            if (len > 0) {
              let userInfo = results.rows.item(0);
              setInfo(userInfo);
            }
          };
      });
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <View style={styles.body}>
      {/* <Text style={styles.text}>Screen B</Text> */}
      <Text style={styles.text}>Welcome {info} </Text>
      <Pressable
        onPress={onPressHandler}
        style={({pressed}) => ({backgroundColor: pressed ? '#ddd' : '#0f0'})}>
        {/* <Text style={styles.text}>Go Back to Screen A</Text> */}
      </Pressable>
    </View>
  );
}

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen name="ScreenA" component={ScreenA} />
        <Stack.Screen name="ScreenB" component={ScreenB} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

const styles = StyleSheet.create({
  body: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  text: {
    fontSize: 40,
    fontWeight: 'bold',
    margin: 10,
  },
  input: {
    width: 300,
    borderWidth: 1,
    borderColor: '#555',
    borderRadius: 10,
    backgroundColor: '#ffffff',
    textAlign: 'center',
    fontSize: 20,
    marginBottom: 10,
  },
});

export default App;

Is this the best way to call multiple functions with onclick in JavaScript?


Is this an acceptable/helpful way to use multiple functions with onclick? I know it works, but I just want to format correctly.


<button type="button" onclick="validateForm()">Submit</button>
<script>
function validateForm () {
    let x = document.forms["myForm"]["myInput"].value;
    if (x == "") {
        document.getElementById("noName").innerHTML = "Please Enter Name";
        return false;
    } else {
        getInputValue(), getHoliday(), hello();
    }
}
</script>

Why this code only outputs the first function and not the other? [closed]

I wanna display the output of both functions, my code is

function DecimalGenerate() { var min = 1.03, max = 5.99, NumberResult = Math.random() * (max - min) + min; document.write(parseFloat(NumberResult).toFixed( 2 )); }; DecimalGenerate();
function main() {
var loc = localStorage.getItem('test');
if (loc == undefined ) {
localStorage.setItem('test', 10);
var loc = localStorage.getItem('test'); document.write("<strong>Your Install Bonus  Is: "+ loc+" $</strong>");
} else { //DecimalGenerate(); document.write(l);
var l = parseFloat(NumberResult).toFixed(2)
var lo = localStorage.getItem('test');
document.write(l);
var lod = +lo + +l;
//document.write(lod);
localStorage.setItem('test',lod)
var load = lod.toFixed(2);
document.write("Your Balance Is: "+ load +" $"); } };
main();

Everything Was working fine until i added the first function.
How can i solve this?

Get data from SVGLoader in three js

I’m importing svg files in three.js by using SVGLoader. So I have a method loadSVG and a function inside of it that makes some actions when svg is loaded. I want to return the result of it in method loadSVG. I guess I have to use promises or async await but have no idea how to do that

loadSVG( url ) {

  const loader = new SVGLoader();
  loader.load( url, function ( data ) {

    ...
    //here I can get the result

  } );

  //I want to return here the result from above

} 

Fixing a Sorting Word Count Code in Javascript

I am a student taking part of a Javascript Coding Certification Course. This website was a resource given in case I needed any help with my work out of camp hours. I was hoping that someone in this community will be able help me with my code.

This code takes a long string, which is given already in the code, and prints the three most common words found within the string. It uses concepts like Callback Functions, objects, arrays, .split, and .sort to execute this code. Here is the code below.

window.onload = () => {
  let result = countWords();
  console.log(result);
};

function countWords() {
  let text =
    "Some of the biggest and most expensive transportation projects in the world have involved building bridges. Bridges are crucial links that carry cars, trucks and trains across bodies of water, mountain gorges or other roads. As a result, they are one of the most important aspects of civil engineering and are subject to intense scrutiny, especially when they collapse. Bridge collapses can be tragic events, leading to loss of life and serious property damage. That is why bridge engineers, designers and builders must always take their jobs very seriously. The best way for them to prevent these accidents is to understand why bridges collapse in the first place. Understanding bridge collapses can lead to major changes in the design, construction and safety of future building projects. The following are main reasons why bridges fall.";

  text.toLocaleLowerCase;
  let newString = "";
  for(let i = 0; i < text.length; i++) {
    if (text[i] !== "." && text[i] !== ",") {
      newString += text[i];
    }
  }
  let arrayOfWords = newString.split(" ")


  let object = {
  }

  for(let i = 0; i < arrayOfWords.length; i++) {
    let word = arrayOfWords[i];
    
    if (object[word] == undefined) {
      object[word] = 1;
    }
    else {
      object[word] += 1;
    }
  }

let myArray = Object.entries(countWords);
  // now sort the arrays based on the count number
bArray = myArray.sort((a,b) => {
  return b[1] - a[1];
}).slice(0,3);
  // print out first three most commone words.
  return bArray;
}

The current output just says: Array[]

I have tried changing around where I enter the bArray variable, but that hasn’t seem to work. I think it has something to do with the for loop, but I don’t know if that is it either!

I would love it if someone could give me feedback so this code prints the three most common words in the text. I will continue to try and fix the code myself. Thank you so much!

GSAP – Range Slider to Responsively Move Through Spritesheet onChange

I’m trying to use GSAP to dynamically move through a spritesheet with five frames. The sheet is 2405px x 145px making each frame 481px in width and 145px in height. I’m running into trouble controlling which frame appears as the slider advances.

The point of this project is to use a controller (the range slider) to “grow/shrink” the size of the head. If the slider advances automatically, the user can’t control what position it stops at. In my code, I want to use the value of the slider to move left or right through each frame of the sprite. When the slider moves right, the head should grow. When the slider moves left, the head should shrink. If the user drags the slider to position four, Frame 4 (position -1924px or -4 * 481px) should show.

The HTML:

     <div id="modeler">
         <div id="front-body" class="float-left">
             <div class="full scalable" id="female-heads" class="head"></div>
             <div class="full scalable" id="female-body"></div>
         </div>
     </div>   
     <div class="range float-left"> 
         <div id="head-class"> <label for="name">Head Size:</label></div>
         <input type="range" min="1" max="5" value="1" id="slider-head-shape" >            
     </div>

The CSS:

#female-heads {
  position: relative;
  margin: 0 auto;
  top: 48px;  
  width: 481px;
  height: 145px;   
  background-image: url('[https://drive.google.com/file/d/1O4jeEPLKAV4DCfPFkKbeN9IWCZI0LGXz/view?usp=sharing]');  
  z-index: 101;
}

#female-body {
  position: relative;
  margin: 0 auto;
  top: 102px;   
  background-image: url('[https://drive.google.com/file/d/1SPGhRx_3L6SKCovr_7_g7AVXdtp1Dcxl/view?usp=sharing][2]');
}

The JavaScript

var $slider = $("#slider-head-shape");
var $target = $("#female-above-heads");
var cols = 5;
var rows = 1;
var gridWidth = $target.width();
var gridHeight = $target.height();

var tl = new TimelineLite({onUpdate:updateSlider});
var sliderValue = $slider.value;
var xpos = -cols/gridWidth * sliderValue;
var ypos = -rows/gridHeight * sliderValue;

function updateSlider() {
    tl.set($target, {backgroundPosition: xpos + "px " +  ypos + "px"});
  console.log(sliderValue);
}

How to build a webpage for searching and updating a MySql database?

This is a part of a larger project. It’s basically a team management tool that can:

  1. Create groups
  2. Add people from a ‘user’ table in MySql to certain group (e.g. add user ‘Sam’ to group ‘Sales’)

What I’m looking for is a page where you can search by a user’s name, and the website displays a list of results with a checkbox next to them. You can check it and add that person to a group. Is there a way to do this with javascript/html? Thanks!

For whom the Bell tolls (Codewars)

KATA PROBLEM

Problem link: https://www.codewars.com/kata/62665d43e67fbaf7b37212d2/train/javascript

Hi! I’ve been working on this problem, what seems the problem on my solution.
Also can you show me more efficient way to solve it, I’m somewhat inexperience working with objects. Thanks

function bell(n) {
 
  let obj = {
    1 : [1],
    2 : [2, 2],
    3 : [3, 4, 3],
    4 : [4, 6, 6, 4],
    5 : [5, 8, 9, 8, 5],
    6 : [6, 10, 12, 12, 10, 6],
    7 : [7, 12, 15, 16, 15, 12, 7],
    8 : [8, 14, 18, 20, 20, 18, 14, 8],
    9 : [9, 16, 21, 24, 25, 24, 21, 16, 9],
    10 : [10, 18, 24, 28, 30, 30, 28, 24, 18, 10],
    11 : [11, 20, 27, 32, 35, 36, 35, 32, 27, 20, 11],
    12 : [12, 22, 30, 36, 40, 42, 42, 40, 36, 30, 22, 12]  
  };
       
     Object.keys(obj).forEach((elem) => {
          if(n.toString() == elem) {
              return obj[elem];
          }
      });
}