Javascript remove multiple html list elements

On every change of input, i need to remove all <li> elements where inner text don’t match the input value. The problem is: it don’t remove all lines that doesn’t match at once.

My code:

        <input name="tag-input" id="tag-input" type='text'>
    <div id="list-pol">
        <ul id="list-pol-select">
            <li class="list-pol-item">Fish</li>
            <li class="list-pol-item">Dog</li>
            <li class="list-pol-item">Chameleon</li>
            <li class="list-pol-item">Cat</li>
        </ul>
    </div>
    <script type="text/javascript">

        var input = document.getElementById('tag-input');

        function updateList(){
            if(document.getElementsByClassName("list-pol-item")[0]){

                var list = document.getElementsByClassName("list-pol-item");

                for (var i = 0; i < list.length; i++) {
                    var tag = list.item(i).innerText;
                    if(input.value !== tag.substring(0,input.value.length)){
                        list.item(i).remove();
                    }
                }
            }
        }

        input.addEventListener('input', updateList);
    </script>

How to write a function that takes an Array of strings as an argument and prints the first letter of each element out (one per line)

I am working on my first javascript assignment and we have been asked to “Write a function that takes an Array of strings as an argument and prints the first letter of each element out (one per line)” however we must use a FOR OF loop, function, and charAt() the output should be
H
W
T
I
M
S each letter on its own line
I am struggling because I only know how to complete the task by using the toString.charAt method but that is not what the assignment asked for. I also am not sure if the for of loop goes in the function or the function goes in the loop. Just started JS last week very confused. Please help.

let arr = (["Hello", "World", "This", "Is", "My", "String"]);
//  required for of
for (let element of arr) {
    console.log(element.toString())
}
 



// required function
let myFunction = (element) => element.charAt(0);

 myFunction(arr)
 

// required charAt
var str = new String( "This is string" );

        
         console.log( arr.toString().charAt(0));
         console.log(  arr.toString().charAt(6));
         console.log(  arr.toString().charAt(12));
         console.log(  arr.toString().charAt(17));
         console.log(  arr.toString().charAt(20));
         console.log( arr.toString().charAt(23));

Any good javascript or angular data visualization libraries that would give me this look? [closed]

The designer on my team wants me to create a front end tracker chart that uses three number data points that would look like the following, depending on what the value of each color is. Here are the different scenarios in how it would look:

enter image description here

I tried making this custom but haven’t figured out how to achieve the blending effect of one color to the next, it looks like this:
enter image description here

Does anyone know of any good data visualization library that would help me achieve this? I would need to be able to customize to these colors. I’m using angular/typescript. Thanks in advance!

Remove result after submiting in form

I have a simple API that gives you the cover images of shows after submitting a word in a form. I want to clear the search result after the images have been displayed so that the next batch of images show. Is there a way to do this in vanilla Javascript?

const form = document.querySelector('#searchForm');
const input = document.querySelector('#inp');
const btn = document.querySelector('#btn');

form.addEventListener('submit', async function(e)
{
    e.preventDefault();
    console.log(form.elements.query.value);
    const response = await axios.get(`https://api.tvmaze.com/search/shows?q=${input.value}`);
    makeImages(response.data);
    input.value = '';
    const secondResponse = await (btn.addEventListener('click'));
    clearImages(response.data);
    
    
})

const makeImages = (shows) =>
{
    for(let res of shows)
    {
        if(res.show.image){
        const img = document.createElement('IMG');
        img.setAttribute("id","imgAttr");
        img.src = res.show.image.medium;
        document.querySelector('.bd').append(img);
        }
    }
    
}

const clearImages = (shows)=>
{
    for(let res of shows)
    {
        if(res.show.image)
        {
            let imgs = document.querySelector("#imgAttr");
            imgs.parentNode.removeChild(imgs);
        }
    }
}

Angular 12:set and get value from a textbox in a record inside grid

As title.
Let me use an example to explain what I want. Assume that I am a teacher and have a set of student exam scores like this:

[
{"name":"John","score":88},
{"name":"Andy","score":80},
{"name":"Mary","score":93},
{"name":"Sandra","score":76},
{"name":"Thomas","score":55},
{"name":"Peter","score":69}
]

I want to display it inside a grid with score field is shown in an input area that I can edit to change student’s score. And I need to get the changed score of a student. Could someone guide me a way to get it? I’ve searched use key word “angular set and get input inside grid” but find some didn’t match what I needed and some uses older Angular.js and may not suitable for my request.

How to get the parent element’s drag events to stop firing, in a nested drag and drop in React (without any DnD library)

Setup: A kanban style component, with draggable columns that contain draggable cards.

The columns are able to render correctly when you drag a column and reorder it. This is done by setting the Index of the column that is dragging when its “onDragStart” event is fired. Then, when another column fires an “onDragOver” event, the array of columns is spliced, to remove the dragging column from it’s original position and insert it into the new order. This is working fine.

The issue arises when I try to drag cards, instead of the columns. When the “onDragStart” event fires on a card, I am setting a flag in a state hook. setDragCategory(“card”). The event listeners on the column elements are supposed to check to see if the “dragCategory === ‘card'”. And if it does, they are supposed to exit the function and not run any of the code.

The goal is that when you start dragging on a column, all of its event listeners fire, per normal. But if you start dragging on a card, the columns’ event listeners are essentially deactivated via exiting them before they do anything.

Even though the “onDragStart” handler on the card is running first (where the state is set to dragCategory === “card”, it is not preventing the columns’ event handlers from running. The column’s event handlers are then setting dragCategory === “column.” So, I a trying to drag a card, but instead, the columns are reordering.

I do not understand why the column’s event listeners are not exiting their handlers before this can happen.

Thank you for any pointers!

This code should work, if you paste it directly into the App.js file of a create-react-app project.

App.js:

import React, { useState } from "react";
import { v4 as uuid } from "uuid";

import "./App.css";

const data = {};
data.columns = [
  { name: "zero", cards: [{ text: "card one" }, { text: "card two" }] },
  { name: "one", cards: [{ text: "card three" }, { text: "card four" }] },
  { name: "two", cards: [{ text: "card five" }, { text: "card six" }] },
  { name: "three", cards: [{ text: "card seven" }, { text: "card eight" }] },
  { name: "four", cards: [{ text: "card nine" }, { text: "card ten" }] },
  { name: "five", cards: [{ text: "card eleven" }, { text: "card twelve" }] },
];

function App() {
  // when a card starts to drag, dragCategory is set to "card."  This is supposed to be a flag that will stop the columns' event listeners before they cause any changes in the state.  
  let [dragCategory, setDragCategory] = useState(null);

  // all of this is for reordering the columns. I have not gotten it to work well enough yet, to be able to write the state for reordering the cards:
  let [columns, setColumns] = useState(data.columns);
  let [draggingIndex, setDraggingIndex] = useState(null);
  let [targetIndex, setTargetIndex] = useState(null);

  return (
    <div className="App">
      <header>drag drop</header>
      <div className="kanban">
        {columns.map((column, i) => {
          return (
            <div
              data-index={i}
              onDragStart={(e) => {
                console.log("column drag start");
                if (dragCategory === "card") {
                  e.preventDefault();
                  return null;
                }
                setDragCategory("column");
                setDraggingIndex(i);
              }}
             // using onDragOver instead of onDragEnter because the onDragEnter handler causes the drop animation to return to the original place in the DOM instead of the current position that it should drop to.
              onDragOver={(e) => {
                if (dragCategory === "card") return null;
                // allows the drop event
                e.preventDefault();
                setTargetIndex(i);
                if (
                  dragCategory === "column" &&
                  targetIndex != null &&
                  targetIndex != draggingIndex
                ) {
                  let nextColumns = [...columns];
                  let currentItem = nextColumns[draggingIndex];
                  // remove current item
                  nextColumns.splice(draggingIndex, 1);
                  // insert item
                  nextColumns.splice(targetIndex, 0, currentItem);
                  setColumns(nextColumns);
                  setTargetIndex(i);
                  setDraggingIndex(i);
                }
              }}
              onDragEnter={(e) => {}}
              onDragEnd={(e) => {
                setDragCategory(null);
              }}
              onDrop={(e) => {}}
              className="column"
              key={uuid()}
              draggable={true}
            >
              {column.name}
              {column.cards.map((card) => {
                return (
                  <div
                    onDragStart={(e) => {
                      
                      setDragCategory("card");
                    }}
                    key={uuid()}
                    className="card"
                    draggable={true}
                  >
                    {card.text}
                  </div>
                );
              })}
            </div>
          );
        })}
      </div>
    </div>
  );
}

export default App;

And paste this starter css in the App.css file.

App.css

.kanban {
  display: flex;
  height: 90vh;
}

.column {
  border: solid orange 0.2rem;
  flex: 1;
}

.card {
  height: 5rem;
  width: 90%;
  margin: auto;
  margin-top: 2rem;
  border: solid gray 0.2rem;
}

apexchart heatmap with list [[x,y, vlaue], [x,y,value]]

I tried to create apexchart heatmap. All example on the page shows various “name” in series. But I have a list of values [[x,y,value],[x,y,value]] … but the values is not categoriesed on the yaxis. Does anyone know how to handle this?

thanks in advance.

best regards

var options = {
  series: [{
    data: [[2012,2012,20],[2012,2013,20],[2012,2014,20],[2013,2012,0],[2013,2013,30],[2013,2014,25]],
  }],
  xaxis: {
    categories: [2012,2013,2014]
  },
  yaxis: {
    categories: [2012,2013,2014]
  },
  chart: {
    height: 350,
    type: 'heatmap',
  },
  plotOptions: {
    heatmap: {
      shadeIntensity: 0.5,
      radius: 0,
      useFillColorAsStroke: true,
      colorScale: {
        ranges: [{
          from: -30,
          to: 5,
          name: 'low',
          color: '#00A100'
        },
                 {
                   from: 6,
                   to: 20,
                   name: 'medium',
                   color: '#128FD9'
                 },
                 {
                   from: 21,
                   to: 45,
                   name: 'high',
                   color: '#FFB200'
                 },
                 {
                   from: 46,
                   to: 55,
                   name: 'extreme',
                   color: '#FF0000'
                 }
                ]
      }
    }
  },
  dataLabels: {
    enabled: false
  },
  stroke: {
    width: 1
  },
  title: {
    text: 'HeatMap Chart with Color Range'
  },
};

var chart = new ApexCharts(document.querySelector("#chart"), options);
        chart.render();

Phaser3, Creating Rounded Rectangle, Not Staying Put Relative To Window

I’m trying to create a scoreboard using phaser3. It creates the board when I do the following in create function:

    this.gr = this.add.graphics();

    this.gr.fillStyle(0xffffff, 0.3);

    this.gr.fillRoundedRect(32, 32, 100, 300, 32);

    this.gr.fillStyle(0xff00ff, 1);

But it creates it in the top left of the game world and not the screen itself (I’m having to travel to top left of the map to see it rather it being top left relative to window). For context, this is alike agar.io where the player moves around the map with the camera clipped to them.

Question: how can I have it be visible relative to the window and not game world?

How can I merge together objects that share the same property within an array? [duplicate]

Let’s say we have the following array:

[{time: 1600000000, a: 2}, {time: 1600000000, b: 1}, {time: 1700000000, a: 4}, {time: 1700000000, b: 3}, {time: 1800000000, a: 8}, {time: 1800000000, b: 9}]

How might one be able to efficiently merge together the objects to get the following array

[{time: 1600000000, a: 2, b: 1}, {time: 1700000000, a: 4, b: 3}, {time: 1700000000, a: 8, b: 9}]

class files structure in js

Hi folks.

I was really good in JS, but … 20 years ago. 😉
Then I learned PHP, then C++, a lil-bit Java and recently C#.NET.

Due to some upcoming private web projects, I’m trying to find back in JavaScript again. I looked at the prototypes and also how to create classes. The lack of type safety bothers me a bit, reminds me of the PHP mixed var types. Also, the annoying typing of “this.*” for each member/field of a class is exhausting. But well, that’s the way it is.

However, my main concern describes the clear structuring of an entire collection of classes, e.g. for larger model or MVVM structures.

I quickly took a look at the latest Vue.JS documentation, the getters and setters for the MVVM object are also generally nice.

Nevertheless, I would prefer a structure like the one known from C#.NET. So a separate file for each class. The question is how do I link all these files and how can I make sure that classes used within other classes (as member/field or via inheritance (extends, :)) are already available according to the order. So previously listed in a merge code.

Are there already libraries or is it somehow very easy to do it yourself? Or does anyone know of some more elegant ways?

It is important to me that with more than 250 classes, subclasses and nested combinations, I can find the classes I am looking for quickly and clearly and update them as cleanly and encapsulated as possible.

But I hope you understand, what I want to have. I’m looking for a way to combine/merge and minify a long list of class files into one *.js file, like a build compiler in C# creates an *.exe file. But in a valid order.

Or am I thinking too much in C#.NET here?
Please don’t see this post as a code question.
I enjoy in a discussion of techniques, libraries and would appreciate some help using these patterns or ideas.


Just for info: My first web project should be a small blog/community for “movies & games” with techniques like:

  • MVVM, binder/observers, shaddow DOM
  • speed ups (lazy load, shaddow DOM, preloads)
  • locally data storages (indexedDB)
  • offline page/js/css with serviceWorker
  • SPA and url manipulation (history.pushState or “/#/…”)

JavaScript: How to sum the values greater than 16 in a list of editable numbers

I’m a new at JavaScript and I’m trying to do the following:

I’m making a fillable .pdf file. The user enters numbers in 7 different fields and gets an output in an 8th field. I want to take the sum of the values greater than 16.

For example: The user enters the following numbers in each field (16, 16, 16, 16, 16, 16, 16). The program sees that no value is above 16, so the output appears in an 8th field as 0.

Now the user enters (17, 17, 16, 16, 16, 16, 16), so the output is 2.

I’m not sure if this requires an array or not? Any thoughts? Thank you in advance.

How to pass props in getStaticProps to a component in Next.js

Overview

I am trying to pass on object of data that contains strings and objects to my component

The Problem

When I check the Next.js documentation to pass props, I try to send it in the key value pair format. When I try to use any of my props in my component, they are undefined. Am I de-structuring wrong?

My attempts

This is what I am currently working with. I fetch some data, get the first object in an array of objects and de-structure only the keys I want. Then I set the keys to a park object.

export async function getStaticProps({params}) {
  const URL = 'https://developer.nps.gov/api/v1/'

  // Call API Data for /PARK
  const res = await fetch(
    `${URL}parks?parkCode=${params?.parkCode}&limit=465&api_key=${process.env.API_KEY}`,
    {
      method: 'GET',
      headers: {
        Accept: 'application/json, text/plain, */*',
        'User-Agent': '*',
      },
    }
  )

  const parkData = await res.json()

  if (!parkData) {
    return {notFound: true}
  }

  const park = parkData?.data[0]

//  The park object looks like this:
{
  name: 'A name',
  fullName: 'John Doe',
  parkCode: 'abcd',
  description: 'lorem ipsum',
  designation: 'park',
  imags: [
    {
      url: 'http://...',
      title: 'img1',
    },
    {
      url: 'http://...',
      title: 'img1',
    },
  ],
}


  const {name, description, parkCode, designation, images, fullName} = park

  return {
    props: {
      park: {name, fullName, description, parkCode, designation, images},
    },
    revalidate: 1,
  }
}

In my component, this is how I try to consume it, but I get undefined errors.

export default function Park({park}) {
  console.log(park) // undefined
}

function to generate cards

How do I write a function in vanilla javascript for a Memory Game to generate:

32 cards in total with shapes on them
each shape  in 4 colors
2 cards of each color

color               shapes
yellow     square, triangle, round, oval
green      square, triangle, round, oval
blue       square, triangle, round, oval
red        square, triangle, round, oval

React.js Uncaught SyntaxError: Unexpected token ‘:’

my first react-app

error in dev-console:

VM4091:1 Uncaught SyntaxError: Unexpected token ':'
        at a (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:254:358)
        at a.c._inlineJS (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:255:1551)
        at b (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:255:1002)
        at xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:3616
        at Array.forEach (<anonymous>)
        at j (xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:3596)
        at Object.appendContent (xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:2032)
        at Object.setContent (xyCIQCGmYe4.js?_nc_x=JMPQFHF0fM0:14:1880)
        at b.<anonymous> (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:39:2329)
        at qg (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:58304)
        at Pj (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:118010)
        at Oj (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:117570)
        at Nj (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:117105)
        at Lk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:127623)
        at Kk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:126938)
        at xk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:123399)
        at Sf (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:52366)
        at qk (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:120184)
        at Object.enqueueSetState (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:59:58710)
        at b.a.setState (9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:58:1753)
        at 9V7BbjlzW3O.js?_nc_x=JMPQFHF0fM0:39:2237
        at AsyncRequest._dispatchResponse (x9ZrO_yAkJs.js?_nc_x=JMPQFHF0fM0:16:6351)
        at Object.applyWithGuard (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:58:9982)
        at AsyncRequest.c (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:58:10686)
        at x9ZrO_yAkJs.js?_nc_x=JMPQFHF0fM0:15:84
        at e (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:322:291)
        at Object.applyWithGuard (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:58:9982)
        at d (-dmZoFVRvhD.js?_nc_x=JMPQFHF0fM0:296:2252)

I need help so the errors disappear from developer toolbar console tab.
Thank you,

The error exist only when i use:

<FacebookProvider appId="someAppId">
    <Page
      href="http://www.facebook.com/somePage"
      tabs="timeline"
    />
</FacebookProvider>

package.json:

{
      "name": "kpw",
      "version": "0.1.0",
      "private": true,
      "typings": "./global.d.ts",
      "babel": {
          "presets": [
              "@babel/preset-env",
              "@babel/preset-react"
          ]
      },
      "dependencies": {
          "@babel/cli": "^7.16.8",
          "@babel/core": "^7.16.10",
          "@babel/preset-env": "^7.16.11",
          "@babel/preset-react": "^7.16.7",
          "@fortawesome/fontawesome-svg-core": "^1.2.36",
          "@fortawesome/free-brands-svg-icons": "^5.15.4",
          "@fortawesome/free-regular-svg-icons": "^5.15.4",
          "@fortawesome/free-solid-svg-icons": "^5.15.4",
          "@fortawesome/react-fontawesome": "^0.1.16",
          "@testing-library/jest-dom": "^5.16.1",
          "@testing-library/react": "^12.1.2",
          "@testing-library/user-event": "^13.5.0",
          "@types/react-router-dom": "^5.3.3",
          "bootstrap": "^5.1.3",
          "eslint-import-resolver-typescript": "^2.5.0",
          "prop-types": "^15.8.1",
          "react": "^17.0.2",
          "react-bootstrap": "^2.1.0",
          "react-dom": "^17.0.2",
          "react-facebook": "^8.1.4",
          "react-router": "^6.2.1",
          "react-router-dom": "^6.2.1",
          "react-scripts": "5.0.0",
          "web-vitals": "^2.1.2"
      },
      "scripts": {
          "start": "react-scripts start",
          "build": "react-scripts build",
          "test": "react-scripts test",
          "eject": "react-scripts eject"
      },
      "eslintConfig": {
          "extends": [
              "react-app",
              "react-app/jest"
          ]
      },
      "browserslist": {
          "production": [
              ">0.2%",
              "not dead",
              "not op_mini all"
          ],
          "development": [
              "last 1 chrome version",
              "last 1 firefox version",
              "last 1 safari version"
          ]
      },
      "devDependencies": {
          "@types/react": "^17.0.38",
          "eslint": "^8.6.0",
          "eslint-config-prettier": "^8.3.0",
          "eslint-plugin-prettier": "^4.0.0",
          "eslint-plugin-react": "^7.28.0",
          "prettier": "^2.5.1"
      }
}

eslint.js:

{
“env”: {
“browser”: true,
“es6”: true,
“es2021”: true,
“jest”: true,
“node”: true
},
“extends”: [
“eslint:recommended”,
“plugin:react/recommended”,
“plugin:prettier/recommended”
],
“parserOptions”: {
“ecmaFeatures”: {
“jsx”: true
},
“ecmaVersion”: 13,
“sourceType”: “module”
},
“plugins”: [
“react”
],
“settings”: {
“import/resolver”: {
“typescript”: {}
}
},
“rules”: {
“react/react-in-jsx-scope”: “off”,
“react/jsx-filename-extension”: [
1,
{
“extensions”: [
“.js”,
“.jsx”
]
}
],
“react/forbid-prop-type”: [
0,
{
“forbid”: [
“any”
]
}
],
“react/self-closing-comp”: [
“error”,
{
“component”: true,
“html”: true
}
],
“prettier/prettier”: [
“error”,
{
“singleQuote”: true,
“parser”: “flow”
}
]
}
}