Global variable not working as an input value

I am a JavaScript beginner, I am stuck with a problem regarding variables.

I wrote this code :

var acNo = document.getElementById("ac").value;

function doSomething(){
    alert(acNo);
}

The output is: undefined

But when I did this :

var acNo = 3

The output is 3

Can you please tell me how can I fix it while keeping the variable global only.

change pseudo element :before with JavaScript

Is it possible to change a CSS pseudo element in JS?

This is my CSS code

.lang-menu .selected-lang:before {
    content: "";
    display: inline-block;
    width: 24px;
    height: 24px;
    background-image: url(../img/icons/armenia-flag-round-icon-32.png);
    background-size: contain;
    background-repeat: no-repeat;
}

Here is my JS code

function changeCss() {
let elem = window.getComputedStyle(selLang, ':before');
elem.backgroundImage = "url(../img/icons/united-states-of-america-flag-round-icon-32.png'))"
}
changeCss()

Vue3: Toggle Class on Click

Yesterday I started working with Vue and have already learned quite a bit. Now I have seen, you can toggle classes directly on the HTML object via the @click event.

Unfortunately, I do not really succeed. With Blank Javascript no problem, but I want to implement this with Vue.

<li @click=" show = !show" :class="{ active: show }" class="nav-item dropdown">

setup() {
    const show = false

    return { show };
},

In this is “show” the class which i want to toggle.

How to disable or get the HTMLAudioElements being played when they are generated using “new Audio”?

When I started writing this question, I read a lot of other similar questions on the same topic but still couldn’t find my own answer.

The problem appears when I approach playing audio using “new Audio()” of HTMLAudioElement (Web APIs https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement). Specifically, how to control the running sound that way?

See the following example. If it is not possible to control those running HTMLAudioElements, it will become a disaster for the user. The sounds will overlap and a mess will occur.
The sounds will overlap and a mess will occur.

    setTimeout
    (
            function ()
            {
                let audio = new Audio("https://www.bensound.com/bensound-music/bensound-dreams.mp3");
                
                audio.autoplay = true;
                audio.play()
                     .then(function ()
                           {
                               console.log("Audio 01 is playing.");
                           })
            },
            1000 // Audio has a duration of about 2 to 3 minutes
    )
    
    setTimeout
    (
            function ()
            {
                let audio = new Audio("https://www.bensound.com/bensound-music/bensound-ukulele.mp3");
                
                audio.autoplay = true;
                audio.play()
                     .then(function ()
                           {
                               console.log("Audio 02 is playing.");
                           })
            },
            5000 // Audio has a duration of about 2 to 3 minutes
    )
    
    setTimeout
    (
            function ()
            {
                let audio = new Audio("https://www.bensound.com/bensound-music/bensound-creativeminds.mp3");
                
                audio.autoplay = true;
                audio.play()
                     .then(function ()
                           {
                               console.log("Audio 03 is playing.");
                           })
            },
            10000 // Audio has a duration of about 2 to 3 minutes
    )

I know it’s possible to get around that problem by creating an “audio” tag with some identifier, like an id or a class. And so the problem will be solved with a few lines of simple JS.

But what if we have to deal with this problem? Any comments or feedback is highly appreciated. Thanks.

How to filter and map a list of items by targeting a property with javascript

Im working on a ReactJS project and in my data structure, i have 2 buttons: ATM, and PARKING:

buttons: [
    {
      value: 'ATM',
      icon: 'atm',
      floors: [
        { 
          value: 'L1',
          floor: 0,
        },
        { 
          value: 'L2',
          floor: 0,
        },
      ]   
    },
    {
      value: 'PARKING',
      icon: 'parking',
      floors: [
        { 
          value: 'L1',
          floor: 0,
        },
        { 
          value: 'L2',
          floor: 0,
        },
      ]   
    },
   ],

I want to target the available floors values: 'L1', 'L2' of ATM and display it as individual titles on HTML.

My approach is first to apply a filter for ATM, then map out the floors like so:

const filteredButton = _.filter(buttons, {value : 'ATM'}); // Filter for ATM

const mappedAtm = filteredButton.map((item)=>(item.floors)) // Map for Floors

const mappedFloor = mappedAtm.map((floors)=>(floors.value)) // Map for Floors values

However, when I console.log(mappedFloor) it returns undefined

My expected output is: "L1", "L2"

Ideally if i get mappedFloor to work, i would then display it on html like so(on browser it should show 2 span tags):

<p className="floors">
  { 
    mappedFloor.map((items, i) => (
        <span key={i}>
          {items}
        </span>
    ))
  }
</p>

Any suggestions and tips are greatly appreciated.

How to loop through object of strings with dates in typescript?

I have object, keys are dates, before dot are months, after are years:

const dataObj = {
  '01.2015': 0.01,
  '02.2015': 0.10,
  '03.2015': 0.05,
  '04.2015': 0.25,
  // ...
}

the function takes two dates and return an array with objects containing values from the dataObj

interface Point {
  date: string;
  value: number;
}

type Digit = '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9';
type Day = `${Digit}${Digit}`;
type Month =
  | '01'
  | '02'
  // ...
  | '11'
  | '12';

type Year = '2015' | '2016' | '2017';
type DateString = `${Day}.${Month}.${Year}`;

type MonthDateString = `${Month}.${Year}`;

function count(firstDate: DateString, secondDate: DateString): Point[] {
 const result: Point[] = [];
 let currentDate = firstDate.slice(3) as MonthDateString;
 // loop through dataObj and push in result
 return result // [{date: '01.2015', value: 0.01}, {...}, ...]
}

How to loop through dataObj? I tried for loop

for(let i = currentDate; i !== secondDate.slice(3);  )

but have no idea what to do with final-expression, how to update counter variable, pass next key(string with date) from dataObj.

UseSelector returns undefined even the state is updated correctly

I have a react admin project using React Redux.

Below is the detail:

slice.tsx:

import {createSlice} from "@reduxjs/toolkit";

const newRevisionSlice = createSlice({
    name: 'newRevision',
    initialState: {
      dataList: [],
      status: 'idle'
    },
  reducers: {
    postSaveNewRevision: (state  = { dataList:[], status:"idle" }, action) => {
      return { ...state, dataList: action.payload, status: 'success' };

      }
    }
  });


export const { postSaveNewRevision } = newRevisionSlice.actions;
export default newRevisionSlice.reducer;
component.tsx: 

const newRevision  = useSelector((state: RootState) => state.newRevision)

store.tsx:

declare global {
  interface Window {
    __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
  }
}

const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;

const rootReducer = combineReducers({
  fleetType: fleetTypeApi,
  revisionNo: revisionNoApi,
  revisionDate:revisionDateApi,
  newRevision: newRevisionApi,
});

const store = createStore(rootReducer, composeEnhancers(applyMiddleware(thunk)));

const useAppDispatch = () => store.dispatch;

export type RootState = ReturnType<typeof store.getState>;

export { useAppDispatch };

ReactDOM.render(
  <Provider store={store}>
    <React.StrictMode>
      <App />
    </React.StrictMode>
  </Provider>,
  document.getElementById('root')
);

In react redux devtool I see that the state is updated correctly when I dispatch.
However, useSelector so newRevision in the component returns undefined.

Could you please help me?

Thanks in advance.

Counting in array by ID

I have an array object containing multiple user IDs and hours worked. What I want to do, is count the hours worked for a specific user and once the hours have exceeded (299 for example) do something.

I want this logic tracked against the individual ID only, but currently, when the hours worked > 299 for a combination of users, then logic is fired. So currently if each user worked 100 hours each the logic would be triggered. I am working with datatables so will show my current logic below.

let newCount = 0;
var data = dataTable.rows().data();
                    console.log(data)

                    for (let i = 0; i < data.length; i++) {                       
                        
                        if (data[i].employeeId == '1234' && hoursWorked > 299) {
                            newCount += data[i].hoursworked
                            console.log(newCount)
                            newNum = vol
                        }
                        console.log(newCount)
                    }      

So to summarise I guess what I’m after is a way to only count the hours worked for a certain user ID.

Delete values at a specific index associated with lowest points value

new here and could use some help

I want to take the smallest value in points range (G9:L9) and delete the values at that indexexample. In this case it’s index 5 or game 6.

I plan on connecting the script to a button so I can drop the smallest match score out of 6 games (best 5/6 games count) all at once for 58 teams.

Any help?

Thanks!

I can’t workout the logic to delete a range of cells based on the associated index of smallest points value, (Game 1 range or cells G3:G6, H3:H6, I3:I6, etc)

How to use NPM modules in plane javascript and html project?

I want to use axios in my simple project but it doesn’t work but when I use CDN for axios it works..!!

HERE’S THE MY CODE

<!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">
    <title>Document</title>
</head>
<body>
    
    <script type="module" src="./app.js"></script>
</body>
</html>

APP.JS

import {  axios } from ("axios");

const getData = async () => {
  const data = await axios.get("https://swquotes.herokuapp.com/random");
  console.log(data);
};
window.onload = getData();

I want to know ho can i use npm packages directly in my project without react

JS originated buttons wont exectue an onclick function

while building a fairly simple calculator I have encountered the issue of an array+function generated buttons not reacting to a click all though they have an onclick event tag.

HTML:

<div class="calculator">
    <div class="monitor">
        <div id="prev-line">0</div>
        <div id="current-line">0</div>
    </div>
    <div id="pad"></div>
    
</div>

JS:

const buttons =["1", "2", "3", "4", "5", "6", "7", "8", "9", ".", "+", "-", "*", "/", "=", "DEL", "AC"];
    let text = "<button oncliclk='execute()'>0";
    buttons.forEach(myFunction);
    text += "</button>";
    document.getElementById("pad").innerHTML = text;

    function myFunction(value){
        text += "<button oncliclk='execute()'>" + value + "</button>";
    }


     var previous = document.getElementById("prev-line");
        function execute() {
            var buttonValue = event.target.textContent;
            var previousLineVar = previous.innerText;
            var currentLineVar = document.getElementById("current-line");
            switch (buttonValue) {
                case 'DEL':
                    previous.innerText = previous.innerText.slice(0, -1)
                    break;
                case '=':
                    previous.innerText = `(${previousLineVar})`
                    currentLineVar.innerText = `${eval(previousLineVar)}`
                    break;
                case 'AC':
                    previous.innerText = ''
                    currentLineVar.innerText = ''
                    break;
                default:
                    previous.innerText = `${previousLineVar}${buttonValue}`
                    break;
            };
        }

Convert arrays to an object of object literals

I have 5 arrays:

let people = [
  'Alica Brereton',
  'David Ernest',
  'David Ernest',
  'Gabriella Hyde',
  'Gabriella Hyde',
  'Joel Forro',
  'Joel Forro',
  'William Kotai'
]

let keys = [ 'product', 'cost per unit', 'units', 'Total Price' ]

let drugs =   ['Marijuana',
  'Methamphetamine',
  'cocaine',
  'Marijuana',
  'Methamphetamine',
  'ecstasy',
  'heroin',
  'ecstasy'
]

let unitPrice = [
  '9.18',   '108.78',
  '80',     '9.18',
  '108.78', '19.12',
  '91.16',  '19.12'
]

let amount =  ['50', '5',  '2',
  '10', '8',  '10',
  '5',  '20'
]

How can I convert the arrays to an object of object literals resembling something like this:

{  
   'Alica Brereton':[  
      {  
         product:'Marijuana',
         unitPrice:'9.18',
         units:'50',
         totalPrice:'459.00'
      }
   ],
   'William Kotai':[  
      {  
         product:'ecstasy',
         unitPrice:'19.12',
         units:'20',
         totalPrice:'382.40'
      }
   ],
   'Joel Forro':[  
      {  
         product:'heroin',
         unitPrice:'91.16',
         units:'5',
         totalPrice:'455.80'
      },
      {  
         product:'ecstasy',
         unitPrice:'19.12',
         units:'10',
         totalPrice:'191.20'
      }
   ],
   'David Ernest':[  
      {  
         product:'Methamphetamine',
         unitPrice:'108.78',
         units:'5',
         totalPrice:'543.90'
      },
      {  
         product:'cocaine',
         unitPrice:'80',
         units:'2',
         totalPrice:'160.00'
      }
   ],
   'Gabriella Hyde':[  
      {  
         product:'Marijuana',
         unitPrice:'9.18',
         units:'10',
         totalPrice:'91.80'
      },
      {  
         product:'Methamphetamine',
         unitPrice:'108.78',
         units:'8',
         totalPrice:'870.24'
      }
   ]
}

I understand i still need to total total price which is a simple multiplication and that there are some duplicates of people who have two orders that need to be corrected also but just looking for some help to move in the right direction

How to get substring from an HTML string?

I have a quick question. How do I get the Hello from here part from the following string with javascript or vue, taking in consideration though that this could be any other string with any length?

<span class="font-semibold">client1</span><br> Hello from here <br> June 1st 2014, 2:00 pm

found no layout file for “HTML” for kind “home”

I am using this command to run a hugo project in my MacBook Pro with M1 chip:

hugo new site example
cd example
hugo server

the output log like this:

➜  example hugo server
Start building sites …
hugo v0.92.0+extended darwin/arm64 BuildDate=unknown
WARN 2022/03/27 15:49:33 found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
WARN 2022/03/27 15:49:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.
WARN 2022/03/27 15:49:33 found no layout file for "HTML" for kind "taxonomy": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.

                   | EN
-------------------+-----
  Pages            |  3
  Paginator pages  |  0
  Non-page files   |  0
  Static files     |  0
  Processed images |  0
  Aliases          |  0
  Sitemaps         |  1
  Cleaned          |  0

Built in 4 ms
Watching for changes in /example/{archetypes,content,data,layouts,static}
Watching for config changes in /example/config.toml
Environment: "development"
Serving pages from memory
Running in Fast Render Mode. For full rebuilds on change: hugo server --disableFastRender
Web Server is available at http://localhost:1313/ (bind address 127.0.0.1)
Press Ctrl+C to stop
WARN 2022/03/27 15:49:36 found no layout file for "HTML" for kind "home": You should create a template file which matches Hugo Layouts Lookup Rules for this combination.

when I access the url http://localhost:1313/, the web page was blank. why did this happen? what should I do to fix it? At least make it show the default page.