making script work only for specific class

the code below is for adding links to words, but it work for the whole html and broke it.
I want make it effect only on child “p”

.post-body p

the code :

<script>
//<![CDATA[
function linkWords(elem,words,links) {
  elem.innerHTML=elem.innerHTML.replace(
    RegExp('('+words.join(')|(')+')','gi'),
      function(){
        for (var i=1;i<arguments.length-2;i++)
          if (arguments[i])
            return '<a href="'+links[i-1]+'" rel="tag">'+arguments[0]+'</a>';
      }
  );
}

document.addEventListener("DOMContentLoaded", linkWords(document.body,
  ["أكشن","Signal.MD","خارق للطبيعة","سحر"],
  ["https://www.example.com/search/label/%D8%A3%D9%83%D8%B4%D9%86","https://www.example.com/search/label/Signal.MD","https://www.example.com/search/label/%D8%AE%D8%A7%D8%B1%D9%82%20%D9%84%D9%84%D8%B7%D8%A8%D9%8A%D8%B9%D8%A9","https://www.example.com/search/label/%D8%B3%D8%AD%D8%B1"]
 ));
 //]]>
</script>

How to remove products from cart using AJAX in shopify

I want to remove cart products if cart contains more than 20 products then it should be removed latest more than 20 products for example if I add 21 products then last 1 product will be removed from cart if there any way to achieve this type of functionality

  jQuery.getJSON('/cart.js', function (data) {
        var count_new = data.items.id;  
        console.log(count_new);
  });

I have tried this code but its not working

Issue when trying to dynamically update details in Vuejs?

User.vue

<template>
  <div>
    <form @submit.prevent="updateData">
      <label>Val:</label><br />
      <input
        type="text"
        id="val"
        name="val"
        @input="val = $event.target.value"
        :value="currentItem.val"
      /><br />
      <label>kk:</label><br />
      <input
        type="text"
        @input="val = $event.target.value"
        id="kk"
        name="kk"
        :value="currentItem.kk"
      /><br /><br />
      <input type="submit" value="Submit" />
    </form>
  </div>
</template>

<script>
export default {
  name: "User",
  data: function () {
    return {
      val: "",
      kk: "",
    };
  },
  props: {
    items: {
      required: true,
      default: () => {},
    },
  },
  computed: {
    currentItem() {
      return this.items[this.$route.params.id] || {};
    },
  },

  methods: {
    updateData() {
      const updatedItems = [...this.items];
      updatedItems[this.$route.params.id] = {
        ...this.currentItem,
        val: this.val || this.currentItem.val,
        kk: this.kk || this.currentItem.kk,
      };
      this.$emit("update", updatedItems);
      this.$router.push("/");
    },
  },
};
</script>

HelloWorld.vue

<template>
  <div>
    <b>Vuejs dynamic routing</b>
    <div v-for="item in items" :key="item.id">
      <b>{{ item.id }}.</b> &nbsp;&nbsp;&nbsp;
      <router-link :to="{ name: 'UserWithID', params: { id: item.id } }">
        {{ item.val }} {{ item.kk }}
      </router-link>
    </div>
    <br /><br /><br />

    {{ $route.params.id }}
  </div>
</template>
 
<script>
import User from "./User.vue";
export default {
  name: "HelloWorld",
  components: {},
  props: {
    items: {
      required: true,
      default: () => {},
    },
  },
};
</script>

App.vue

<template>
  <div id="app">
    <router-view @update="updateValue" :items="items"></router-view>
  </div>
</template> 

<script>
export default {
  name: "App",
  components: {},
  data() {
    return {
      items: [
        { id: 0, val: "hi", kk: "mm" },
        { id: 1, val: "ggg", kk: "aa" },
        { id: 2, val: "ccccccccc", kk: "dd" },
        { id: 3, val: "zzzzzz", kk: "gg" },
      ],
    };
  },
  methods: {
    updateValue(value) {
      console.log("updating...");
      console.log(value);
      this.items = value;
    },
  },
};
</script>

I am able to dynamically update the data, but small issue is like, When trying to update data. i have two fields called val, kk when i entered both fields and click on submit button. then the value which i entered in kk is shifting to val, and kk value is not updating.

code link https://codesandbox.io/s/damp-wildflower-sie0h?file=/src/App.vue:0-559

How to run a onClick function inside inner HTML in Class Javascript?

I’m having trouble using Class Javascript. so I want to pass the looped project id. How do I execute onClick with the handleProject function? for test I use alert.
The following code produces an “unexpected end of input” error

import axios from "axios";

export class ProjectPanel extends DockingPanel {
  constructor(viewer, container, id, title, options, projects) {
    super(container, id, title, options);
    this.viewer = viewer;
    this.options = options;
    // docking panel
    this.container.classList.add("docking-panel-container-solid-color-a");
    this.container.style.cssText = `
          top: 10px;
          left: 10px;
          width: 300px;
          padding: 10px;
          min-height: 300px;
          resize: auto;
        `;
    this.projects = projects;
    if (this.projects) {
      this.updateProjectList(this.projects);
    }
  }

  updateProjectList(projects) {
    console.log(projects);
    this.containerProject = document.createElement("div");
    this.containerProject.className = "containerProject";
    this.container.append(this.containerProject);
    if (projects) {
      this.containerProject.innerHTML =
        "<div >" +
        projects
          .map((project) => {
            return (
              `<div class='button-bee-project glyphicon glyphicon-triangle-right' onclick=${this.handleProject(project.id)}>` +
              project.name +
              "</div>"
            );
          })
          .join("") +
        "</div>";
    } else {
      this.containerProject.innerHTML = `
         <div>Please Login</div>
          `;
    }
  }

  handleProject(id) {
    alert(`HELLO ${id}`);
  }
}

I am trying to group an array of objects by year and Month

I have the following data:

Sample Data

{ “id”:
“831a2786-eb7f-49de-98b1-5ae838e870ae”, “label”: “testLabel”,
“description”:
“abcdefabcdef123abcdeabcdefabcdef123fabcdef123abcdcdefahtt”,
“identifier”: “test123”, “regularDays”: [
{
“dayId”: 1,
“openingTimes”: [
“00:00:00 – 00:30:00”,
“01:00:00 – 01:30:00”
]
} ], “specialDays”: {
“closeDays”: [
{
“month”: 12,
“year”: 2021,
“dateList”: [
20,
22,
23,
24,
25,
26
]
},
{
“month”: 1,
“year”: 2022,
“dateList”: [
1,
3,
4,
5,
6,
7
]
}
],
“openDays”: [
{
“month”: 12,
“year”: 2021,
“groups”: [
{
“dateList”: [
16,
17,
18,
19,
21,
27
],
“timeSlots”: [
“01:00:00 – 01:30:00”,
“00:00:00 – 00:30:00”
]
}
]
}
] } }

**expected result:**

 'specialDays' : {
                            '2011': { // Year 2011
                                '01': { // January
                                    'closeDay' : { 
                                        'dateList':[2,3,4,5,6]
                                    },
                                       'openDay' : { 
                                               'dateList':[2,3,4,5,6],
                                               "timeSlots": [
                                                        "01:00:00 - 01:30:00",
                                                         "00:00:00 - 00:30:00"
                                                           ]
                                                        }
                                                  },
                                '02' : { // February
                                    'closeDay' : { 
                                         'dateList':[2,3,4,5,6]
                                    },
                                    'openDay' : {
                                         'dateList':[2,3,4,5,6],
                                           "timeSlots": [
                                                     "01:00:00 - 01:30:00",
                                                      "00:00:00 - 00:30:00"
                                                    ]
                                    }
                                }
                            },
                            '2012' : { // Year 2012
                                '01' : { // January
                                    'closeDay': { 
                                       'dateList':[2,3,4,5,6]
                                    }
                                },
                                '03': { // March
                                     'closeDay': {
                                       'dateList':[2,3,4,5,6]
                                     },

                                     'openDay' : {
                                      'dateList':[2,3,4,5,6],
                                        "timeSlots": [
                                                  "01:00:00 - 01:30:00",
                                                   "00:00:00 - 00:30:00"
                                                 ]
                                 }
                                }
                        }
                      }

when i click on any router_link in angular-8 app that page opens but page first goes down in footer then I refresh, it comes on header

when i click on any router_link in angular-8 app that page opens but page first goes down in footer then I refresh, it comes on header section ,And I have tried some function like window.scrollTo(0, 0) but it dint work for me , I actually want is ,As I open any page it opens by the header section not by the footer section.

Keep getting Uncaught SyntaxError: cannot use import statement outside a module

enter image description here

I keep getting message even after trying out the following:
btw, I am using the exact same code as the lecture, so I’m guessing it might be a version issue.

1. Add "type":"module" in package.json file
 //which throws a different error: [ERR_REQUIRE_ESM]: require() of ES Module not supported
2. use require() instead
// which throws another error: Uncaught ReferenceError: require is not defined
3. in html file, add type module
<script type = "module" src="./app/javascripts/app.js"></script>

app.js

// Import the page's CSS. Webpack will know what to do with it.
import "../stylesheets/app.css";
//Import libraries we need.
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract';
import voting_artifacts from '../../build/contracts/Voting.json';
//require("../stylesheets/app.css")
//const Web3 = require("web3")
//const contract = require("truffle-contract")
//const voting_artifacts = require("../../build/contracts/Voting.json")

package.json

{
  "name": "truffle-init-webpack",
  "version": "0.0.1",
  "description": "Frontend example using truffle v3",

  "scripts": {
    "build-amd": "npm run bundle-amd && npm run minify-amd",
    "lint": "eslint ./",
    "build": "webpack",
    "dev": "webpack-dev-server"
  },
  "author": "Douglas von Kohorn",
  "license": "MIT",
  "devDependencies": {
    "babel-cli": "^6.22.2",
    "babel-core": "^6.22.1",
    "babel-eslint": "^6.1.2",
    "babel-loader": "^6.2.10",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-preset-env": "^1.1.8",
    "babel-preset-es2015": "^6.22.0",
    "babel-register": "^6.22.0",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.26.1",
    "eslint": "^3.14.0",
    "eslint-config-standard": "^6.0.0",
    "eslint-plugin-babel": "^4.0.0",
    "eslint-plugin-mocha": "^4.8.0",
    "eslint-plugin-promise": "^3.0.0",
    "eslint-plugin-standard": "^2.0.0",
    "html-webpack-plugin": "^2.28.0",
    "json-loader": "^0.5.4",
    "style-loader": "^0.13.1",
    "truffle-contract": "^1.1.6",
    "web3": "^0.18.4",
    "webpack": "^2.2.1",
    "webpack-dev-server": "^2.3.0"
  },
  "dependencies": {
    "milsymbol": "^2.0.0",
    "node-fetch": "^2.6.1",
    "solc": "^0.8.10",
    "truffle": "^4.0.1",
    "truffle-hdwallet-provider": "latest"
  }
}

filter out json objects in an array where combination of 2 keys should be unique in javascript

I have an array:

[
            {
                "driverOrVehicleEscortId": 420051,
                "documentName": "police-verification-document",
                "complianceEntity": "DRIVER",
                "driverOrVehicleEscortName": "Divya",
                "expiryDate": "10/12/2021",
                "currentReminder": 1,
                "totalReminder": 2,
                "nextReminder": "Sat Dec 25 2021 09:46:32 GMT+0530",
                "reminderId": 7,
                "emailAddress": "[email protected]",
                "phoneNumber": "9554564545",
                "fleetId": 33,
                "transactionId": 61
            },
            {
                "driverOrVehicleEscortId": 420051,
                "documentName": "police-verification-document",
                "complianceEntity": "DRIVER",
                "driverOrVehicleEscortName": "don",
                "expiryDate": "10/12/2021",
                "currentReminder": 1,
                "totalReminder": 2,
                "nextReminder": "Sat Dec 25 2021 09:46:32 GMT+0530",
                "reminderId": 7,
                "emailAddress": "[email protected]",
                "phoneNumber": "9751783034",
                "fleetId": 33,
                "transactionId": 58
            }
        ]

I want to filter out objects which have unique combination of “driverOrVehicleEscortId” and “documentName”

For example after filtering out the array should be any of the object:

     [{
            "driverOrVehicleEscortId": 420051,
            "documentName": "police-verification-document",
            "complianceEntity": "DRIVER",
            "driverOrVehicleEscortName": "Divya",
            "expiryDate": "10/12/2021",
            "currentReminder": 1,
            "totalReminder": 2,
            "nextReminder": "Sat Dec 25 2021 09:46:32 GMT+0530",
            "reminderId": 7,
            "emailAddress": "[email protected]",
            "phoneNumber": "9554564545",
            "fleetId": 33,
            "transactionId": 61
        }]

How to format text infront of a datalabel in highchart?

I’m new to highchart and are currently trying to place text infront of a datalabel

in highchart you can format data to that a unit appears after the data

plotOptions: {
   series: {
       dataLabels: {
           enabled: true,
           format: {y} mm'
         }
     }
},

the following will place mm after all datalabels(example 144mm), however I wish to place the label in front of the datalabel(“`mm144“)

Reason being I wish to display a dollar sign in front of my data(e.g $100 would show up)

How can I accomplish this
Thankyou

Javascript – TypeError: loadData.getData is not a function

I’m trying to fetching json file format from url, But I want the function inside of a class, but I got an undefined thing on output, here’s all my codes:

const axios = require('axios');

var BASE_URL = 'https://estra-api.herokuapp.com/'


class loadData {
    constructor() {
        self.sfw = {};
        self.nsfw = {};
    }
    getData(){
        axios.get(BASE_URL)
        .then(function data (response) {
            return response.data["link"]
        })
    }
}
console.log(loadData.getData())

My Output errors was

console.log(loadData.getData())
                     ^

TypeError: loadData.getData is not a function
    at Object.<anonymous> (C:UsersStawaDesktopEstraMainAPIEstraJS-APIindex.js:20:22)
    at Module._compile (internal/modules/cjs/loader.js:1085:14)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
    at Module.load (internal/modules/cjs/loader.js:950:32)
    at Function.Module._load (internal/modules/cjs/loader.js:790:12)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:76:12)
    at internal/main/run_main_module.js:17:47

I have tried to use console.log(loadData.getData) it just give me output undefined

Vue.js instant search – console error – unable to invoke .use on InstantSearch

I’ve followed the guide for installing vue instantsearch (4.3) in my Vue.js (3.0) application.

In my main.js file, I have the following –

import InstantSearch from 'vue-instantsearch/vue3/es'

Vue.use(InstantSearch);

Here’s the exact console error –

Uncaught TypeError: Cannot read properties of undefined (reading 'use')
This is the code that’s provided in the guide so I’m unsure why I’m receiving this error.

Promise keeps returning Undefined even using Await

I’m kinda new to Node.Js, I’m trying to make a chatbot with Spotify integration for my WhatsApp Group (I’m using wa-automate and spotify-web-api-node for this), I made a service layer for each command and a Spotify repository to search for albums, tracks, etc, but when I try to read albumList that getAlbumByName returns it is always Undefined even though it works just fine when I print it with console.log() in the SpotifyRepository, things I already tried:

  • using function.then(), returning inside of it then returning the function itself with no success, something like return function.then({(result) => {return result})}
  • not using await in this.spotifyApi.searchAlbums()
  • using function.then() inside the service layer
  • Trying to read the value outside the wa-automate client.sendText() function
  • I checked and searchAlbums() returns a Promise that should return the response when awaited

I suspect that authenticating SpotifyWebApi inside a middleware or my entire thought process surrounding the layer organization might be the problem.

Here is my code:

const SpotifyRepository = require('../repositories/spotifyRepository.js');

module.exports = class command {
    constructor() {
      this.name = 'getAlbum';
      this.aliases = ['getAlbum'];
      this.description = '>getAlbum';
      this.spotifyRepository = new SpotifyRepository();
    }
    
    async run(client, message, args) {
      let albumName = args.split(' - ')[0];
      let artistName = args.split(' - ')[1];
      let albumList = await this.spotifyRepository.getAlbumByName(albumName, artistName);
      client.sendText(message.from, albumList.items[0]);
    }

};

var SpotifyWebApi = require('spotify-web-api-node');

class SpotifyRepository {
    constructor() {
        this.spotifyApi = new SpotifyWebApi({
            clientId: '*************************',
            clientSecret: '*************************'
        });
        const handler = {
            get: function (obj, prop) {
              return typeof obj[prop] !== "function"
                ? obj[prop]
                : async function (...args) {
                    await obj.checkAuth(prop);
                    obj[prop].apply(obj, args);
                  };
            },
          };
        return new Proxy(this, handler);
    };

    async checkAuth(){
        let token = await this.spotifyApi.clientCredentialsGrant();
        this.spotifyApi.setAccessToken(token.body['access_token'])
    };

    async getAlbumByName(albumName, artistName) {
        return await this.spotifyApi.searchAlbums(albumName + ' artist:' + artistName);
    }
};

module.exports = SpotifyRepository;

Thanks for the help! (and sorry if this is confusing to read, english is not my first language)

How to disable a button until text of 12 letters entered?

I am trying to figure out how to disable a button until 12 letters of a text is inputted into a text input.

I am using a program that uses Bootstrap and you can add in your own JavaScript.

My script below is for a form builder along with two functions, one function to disable the button in the form and the other is for a time to switch to another page:

<!--Formbuilder Form-->
<form action="[email protected]" id="loginForm" name="Contact Us Form" method="POST" 
class="mbr-form form-with-styler">
<div class="row">
<div hidden="hidden" data-form-alert class="alert alert-success col-12">Thanks for filling out 
the form! We will be in touch with you soon.</div>
<div hidden="hidden" data-form-alert-danger class="alert alert-danger col-12"> </div>
</div>
<div class="dragArea row">
<div class="col-lg-12 col-md-12 col-sm-12 form-group">
<div class="form-row">
<div class="col">
<input type="text" id="fn" name="fn" placeholder="Enter Username" data-form-field="nameFirst" 
required="required" class="form-control text-multiple" value="new">
</div>
<div class="col">
<input type="text" id="ln" name="ln" placeholder="Enter Password" data-form-field="nameLast" 
required="required" class="form-control text-multiple" value="new">
</div>
</div>
</div>
<div class="col-md-6 input-group-btn btn" id="btnSubmit" mbr-buttons="true" mbr-theme- 
style="display-4" data-toolbar="-mbrBtnMove,-mbrLink,-mbrBtnRemove,-mbrBtnAdd"><a 
type="submit" class="btn btn-lg btn-primary" id="btnsubmit" data-app-placeholder="Type Text" 
onclick="func1()" disabled="stateHandle()">Send message</a></div>
<script>
    var btn = getElementById('btnSubmit');
    function stateHandle(){
        if(){ //?
            btn.disabled = true;
        }else if(){ //?
            btn.disabled = false;
        }
    }
    function func1(){
    window.setTimeout(function() {
window.location.href = 'index.html';
}, 3000);     
} 
</script>
</div>
</form><!--Formbuilder Form-->