Redacting some portion of words in an HTML input feed using javascript

A user will write/paste the same content into a form field and then specify the words that need to be scrambled (using another field). Note the user is allowed to specify more than one word (separated by space) to be scrambled.

After clicking a “Redact Now” button, the app scans through the original text and replaces the specified words to be scrambled with asterisks (i.e ***) Advanced features

Allow the user to specify what to use in replacing the words, so that the app can do the scrambling with what the user provides, be it asterisks, question marks, dashes, underscores, or even other words 2. Display some stats like how many words were scanned, how many matched the words to be scrambled, how many characters were scrambled in total, and how long it took (in seconds) to complete the scrambling task

Why does function only return on statement and not the others

So my function below is

const message = function (number) {
  for (let i = 0; i < 200; i++) {
    if (i % 7 == 0 && i % 9 == 0) {
      return "Why is the ground shaking";
    } else if (i % 7 == 0) {
      return "Here is the magic 7";
    } else if (i % 9 == 0) {
      return "Here is the magic 9";
    } else {
      return "You have failed";
    }
  }
};

console.log(message(9));
console.log(message(4));
console.log(message(36));
console.log(message(21));

But it always returns “Why is the ground shaking” not sure why though

Cannot update field even when allowed

My schema

type Group
  @model
  @auth(
    rules: [
      { allow: private, operations: [create, read] }
      {
        allow: owner
        ownerField: "adminIds"
        operations: [create, read, update]
      }
      { allow: owner, ownerField: "creatorId" }
      {
        allow: groups
        groups: ["AdminRoot"]
        operations: [create, read, update, delete]
      }
    ]
  ) {
  id: ID!
  userIds: [ID]!
    @auth(
      rules: [
        { allow: private, operations: [create, read, update] }
        { allow: owner, ownerField: "creatorId" }
      ]
    )
}

My problem is, whenever i try to update my field userIds as an logged-in user, i get the error Unauthorized on [id]

Why am i not able to update this userIds field?

My code:

let group = await DataStore.save(Group.copyOf(this.group, updated => {
  let i = updated.userIds.indexOf(this.userData.username)

  if (i === -1) return
  updated.userIds.splice(i, 1)

}))

Nuxt 3: Pinia: why is my mutating my state destorting the entire array

here lies my code

import { defineStore } from "pinia";

export const DB_CART = defineStore("CART", {
    state: () => ({
        CART: [
            {
                $id: "62616ffc6d13e2a9eb04",
                quantity: 1
            },
            {
                $id: "6261711719aa15827836",
                quantity: 1
            },
            {
                $id: "6275c020740fbd04db50",
                quantity: 1
            }
        ],
    }),
    actions: {
        // INCREMENT PRODUCT QUANTITY IN CART
        incrementCartQuantity(id) {
            const cartItem = this.CART.find(item => item.$id = id);
            cartItem.quantity++;
        },
        // DECREMENT PRODUCT QUANTITY IN CART
        decrementCartQuantity(id) {
            const cartItem = this.CART.find(item => item.$id = id);
            if (cartItem.quantity === 1) return
            cartItem.quantity--;
        },
        // ADD PRODUCT TO CART
        addToCart(item) {
            this.CART.push(item)
        }
    },
    persist: true
})

I’d like to understand why when I increment or decrement a cart item starting from the second in the array, the array rearranges.

incrementCartQuantity(id) {
   const cartItem = this.CART.find(item => item.$id = id);
   cartItem.quantity++;

   console.log(this.CART) /*EXPECTED OUTPUT
    [
            {
                $id: "62616ffc6d13e2a9eb04",
                quantity: 1
            },
            {
                $id: "6261711719aa15827836",
                quantity: 1
            },
            {
                $id: "6275c020740fbd04db50",
                quantity: 1
            }
        ]
  *//*RETURED OUTPUT
    [
            { $id: "6261711719aa15827836", quantity: 2 },
            { $id: "6261711719aa15827836", quantity: 1 }, INCREMENTED OBJECT
            { $id: "6275c020740fbd04db50", quantity: 1 }
        ]
  */
 },

in my Vue component, on incrementCartItem, I find out that the entire array kind of shuffles and pops out the one at the top, and replaces it with the item which is being mutated
I don’t think the array should be affected in any way.

How to allow a click to perform a function on input field and log some kind of success or error [duplicate]

As title says;
TL;DR – creating credit card app, built the logic to check the card and that works, my issue is linking the HTML and JS.

I have built this app for fun using JavaScript to deepen my knowledge but I’m stuck. What I want to happen is when a user inputs a credit card number, there to be some kind of success message, like the background turns green, or red if it doesn’t meet the criteria. The algo being used is Luhn’s method to validate.

https://learnersbucket.com/examples/javascript/credit-card-validation-in-javascript/#:~:text=Validating%20credit%20card%20in%20javascript%20with%20Luhn%27s%20algorithm.&text=Get%20a%20double%20of%20every,divisible%20then%20it%20is%20valid.

Project is here: https://github.com/Chaffexd/creditCardApp

This is my HTML:

<div class="card-body">
            <h4>Validate a credit card</h4>
            <form id="information">
                <div class="box">
                    <input id="credit-card-number" type="text" placeholder="Enter a credit card number">
                </div>
                <div class="validate">
                    <button id="check">Validate</button>
                </div>
            </form>
        </div>

Using the above link as an example, my algorithm is different but the same logic applies. How can I allow a user to input a 16 digit card number, then click validate and for the function to run and then return success/error.

Apologies, I have researched this for several hours and attempted multiple different routes but it just can’t click in my head. Would appreciate any help on this.

why addEventListener showing error in below code. please check

why addEventListener showing error in below code. please check

let minSlider = document.querySelector("#min");
let maxSlider = document.querySelector("#max");
maxSlider.addEventListener("input", () => {
let minValue = parseInt(minSlider.value);
let maxValue = parseInt(maxSlider.value);
if (maxValue < minValue + 10) {
minSlider.value = maxValue - 10;
if (minValue === parseInt(minSlider.min)) {
maxSlider.value = 10;
}
}
updateDollars();
});

Card Height adjusting on Button Click React

How to adjust this one whenever I click “Create Invoice” it will render a spinner with “Creating invoice”. However the height of the card is also changing. I want it to be in fixed position

Please check GIF
https://imgur.com/a/ymJSnpy

const Loading = () => {
  return (
    <div className="loading" style={divStyle}>
      <h4>Creating Invoice
        <Spinner size="15px" color="#6491c6"/></h4>
    </div> 

  )}```


jQuery steps custom previous step

I am using a multiform with jQuery steps. However it has custom steps to make based on the user’s decision. Both the next and previous buttons have their own respective steps to make, and how weird it is the next button does it’s job but the previous button won’t allow me to set a custom step.

I upgraded the jQuery steps method to set an custom step

function _goToStep(wizard, options, state, index)
{
    return paginationClick(wizard, options, state, index);
}

$.fn.steps.setStep = function (step)
{
    var options = getOptions(this),
        state = getState(this);
    return _goToStep(this, options, state, step);
};

onChanging function to do additional steps

onStepChanging: function (event, currentIndex, newIndex) {

            let options = document.querySelectorAll('.options')

            options.forEach((option) => {
                if(option.previousElementSibling.checked) {
                    option.previousElementSibling.checked = 'checked';
                    option.previousElementSibling.classList.add('checked');
                }
            });

            if(newIndex === 0) {
                $(".actions ul").removeClass("actions-next");
            } else {
                $(".actions ul").addClass("actions-next");
            }

            //Trigger either next or prev button

            return true;

        },
// Next button is working and going to the right index

$("a[href='#next']").click(function (e) {
        const currentIndex = form.steps("getCurrentIndex");
            switch(currentIndex) {
                case 2:
                    if(document.querySelector('#latex').checked) {
                        form.steps("setStep", 2);
                    } else {
                        form.steps("setStep", 3);
                    }
                break;
                case 3:
                    form.steps("setStep", 4);
                break;
                case 4:
                    if(document.querySelector('#wandvloer').checked) {
                        form.steps("setStep", 2);
                    } else {
                        form.steps("setStep", 6);
                    }
                break;
                case 5:
                    console.log(currentIndex);
                break;
            }

        return form.valid();
    });

    //Previous button is working when being clicked, but the correct step is not being set.

    $("a[href='#previous']").click(function (e) {
        const currentIndex = form.steps("getCurrentIndex");

            switch(currentIndex) {
                case 2:
                    if(document.querySelector('#wandvloer').checked) {
                        form.steps("setStep", 3);
                    } else {
                        form.steps("setStep", 2);
                    }
                    break;
                case 3:
                    if(document.querySelector('#latex').checked) {
                        form.steps("setStep", 3);
                    } else {
                        form.steps("setStep",3);
                    }
                    break;
                case 4:
                    if(document.querySelector('#wandvloer').checked) {
                        form.steps("setStep", 5);
                    } else {
                        form.steps("setStep", 6);
                    }
                    break;
                case 5:
                    form.steps("setStep", 6);
                    break;
            }
        return form.valid();
    });

Uncaught ReferenceError: dataProcessor is not defined

I follow a tutorial but I still having a problem as title say.
I have a index.html and a backend with Node connected to Mongodb and I can’t get it to work.

Here is my index.html

<!doctype html>

<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title>Basic initialization</title>
    <link rel="stylesheet" href="https://cdn.dhtmlx.com/scheduler/edge/dhtmlxscheduler_material_nofont.css">
    <script src="https://cdn.dhtmlx.com/scheduler/edge/sources/dhtmlxscheduler.js"></script>

    <style>
        html,
        body {
            margin: 0px;
            padding: 0px;
            height: 100%;
            overflow: hidden;
        }
    </style>
    <script>
        function init() {
            scheduler.config.xml_date = "%Y-%m-%d %H:%i";
            scheduler.init("scheduler_here", new Date(), "week");
            // enables the dynamic loading
            scheduler.setLoadMode("day");

            // load data from backend
            scheduler.load("/data", "json");
            // connect backend to scheduler
            var dp = new dataProcessor("/data");
            // set data exchange mode
            dp.init(scheduler);
            dp.setTransactionMode("POST", false);
        }
    </script>
</head>

<body onload="init();">
    <div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
        <div class="dhx_cal_navline">
            <div class="dhx_cal_prev_button">&nbsp;</div>
            <div class="dhx_cal_next_button">&nbsp;</div>
            <div class="dhx_cal_today_button"></div>
            <div class="dhx_cal_date"></div>
            <div class="dhx_cal_tab" name="day_tab"></div>
            <div class="dhx_cal_tab" name="week_tab"></div>
            <div class="dhx_cal_tab" name="month_tab"></div>
        </div>
        <div class="dhx_cal_header">
        </div>
        <div class="dhx_cal_data">
        </div>
    </div>
</body>

And as the title say I get this error:

(índice):28 Uncaught ReferenceError: dataProcessor is not defined
    at init ((índice):28:13)
    at onload ((índice):36:24)

And my backend works right because on my /data route with this code

app.get('/data', function (req, res) {
        events.find().toArray(function (err, data) {
            //set the id property for all client records to the database records, which are stored in ._id field
            for (var i = 0; i < data.length; i++){
                data[i].id = data[i]._id;
                delete data[i]["!nativeeditor_status"];
            }
            //output response
            res.send(data);
        });
    });

I can get this JSON object (that it works loaded from MongoDB):

[{"_id":"62d73a68fcb2de5910bd9f08","text":"Some Helpful event","start_date":"2022-08-31T22:00:00.000Z","end_date":"2022-09-04T22:00:00.000Z","id":"62d73a68fcb2de5910bd9f08"},{"_id":"62d73a68fcb2de5910bd9f09","text":"Another Cool Event","start_date":"2022-09-10T22:00:00.000Z","end_date":"2022-09-10T22:00:00.000Z","id":"62d73a68fcb2de5910bd9f09"},{"_id":"62d73a68fcb2de5910bd9f0a","text":"Super Activity","start_date":"2022-09-08T22:00:00.000Z","end_date":"2022-09-09T22:00:00.000Z","id":"62d73a68fcb2de5910bd9f0a"},{"_id":"62d73ab8fcb2de5910bd9f0b","text":"Some Helpful event","start_date":"2022-08-31T22:00:00.000Z","end_date":"2022-09-04T22:00:00.000Z","id":"62d73ab8fcb2de5910bd9f0b"},{"_id":"62d73ab8fcb2de5910bd9f0c","text":"Another Cool Event","start_date":"2022-09-10T22:00:00.000Z","end_date":"2022-09-10T22:00:00.000Z","id":"62d73ab8fcb2de5910bd9f0c"},{"_id":"62d73ab8fcb2de5910bd9f0d","text":"Super Activity","start_date":"2022-09-08T22:00:00.000Z","end_date":"2022-09-09T22:00:00.000Z","id":"62d73ab8fcb2de5910bd9f0d"},{"_id":"62d73ab9fcb2de5910bd9f0e","text":"Some Helpful event","start_date":"2022-08-31T22:00:00.000Z","end_date":"2022-09-04T22:00:00.000Z","id":"62d73ab9fcb2de5910bd9f0e"},{"_id":"62d73ab9fcb2de5910bd9f0f","text":"Another Cool Event","start_date":"2022-09-10T22:00:00.000Z","end_date":"2022-09-10T22:00:00.000Z","id":"62d73ab9fcb2de5910bd9f0f"},{"_id":"62d73ab9fcb2de5910bd9f10","text":"Super Activity","start_date":"2022-09-08T22:00:00.000Z","end_date":"2022-09-09T22:00:00.000Z","id":"62d73ab9fcb2de5910bd9f10"},{"_id":"62d73abafcb2de5910bd9f11","text":"Some Helpful event","start_date":"2022-08-31T22:00:00.000Z","end_date":"2022-09-04T22:00:00.000Z","id":"62d73abafcb2de5910bd9f11"},{"_id":"62d73abafcb2de5910bd9f12","text":"Another Cool Event","start_date":"2022-09-10T22:00:00.000Z","end_date":"2022-09-10T22:00:00.000Z","id":"62d73abafcb2de5910bd9f12"},{"_id":"62d73abafcb2de5910bd9f13","text":"Super Activity","start_date":"2022-09-08T22:00:00.000Z","end_date":"2022-09-09T22:00:00.000Z","id":"62d73abafcb2de5910bd9f13"},{"_id":"62d7d077c94c005194ecf8d7","text":"Some Helpful event","start_date":"2022-08-31T22:00:00.000Z","end_date":"2022-09-04T22:00:00.000Z","id":"62d7d077c94c005194ecf8d7"},{"_id":"62d7d077c94c005194ecf8d8","text":"Another Cool Event","start_date":"2022-09-10T22:00:00.000Z","end_date":"2022-09-10T22:00:00.000Z","id":"62d7d077c94c005194ecf8d8"},{"_id":"62d7d077c94c005194ecf8d9","text":"Super Activity","start_date":"2022-09-08T22:00:00.000Z","end_date":"2022-09-09T22:00:00.000Z","id":"62d7d077c94c005194ecf8d9"}]

Why I get this error if I follow the tutorial from official web https://dhtmlx.com/blog/using-dhtmlxscheduler-with-node-js/

Binding navigation menu to filters on collection page shopify vue

In shopify you have a filter object and you can filter products by product type. So if we have a collection clothing, and there are some products of type shirts, or of type pants, we can filter the products based on their type.

This leads me to believe that it isn’t necessary to have a list of collections or a subcollection. My question is I am using vue in shopify so this is mostly a javascript project as I converted liquid objects to javascript.

If we have a collection clothing with two types of products in the collection, and then we create a navigation menu:

|-Clothing
  |-View all
  |-Shirts
  |-pants

How could this be build that if you click on Shirts you are taken to the clothing collection page with the shirts filter already applied?

If view all is clicked you are taken again to the Clothing collection, but no product type filters would be applied.

How to reduce array to object with sub-keys

I cannot seem to get my head wrapped around the JS array.reduce() function. I have the following input array and want to transform it into an object with reduce to get the following output:

Input:

let cars = [ 
{ name: 'bmw', type: 'diesel' },
{ name: 'mercedes', type: 'gas' },
{ name: 'honda', type: 'electric' },
{ name: 'bmw', type: 'gas' }
];

Desired output:

{ 
"bmw": [{type: 'diesel'}, {type: 'gas'}],
"mercedes": [{"type": "gas"}],
"honda": [{"type": "electric"}]
}

What I have tried:

let output = input.reduce((acc, item) => {
  if (!acc[item.name]) {
    acc[item.name] = [{ type: item.type }];
  } else {
    acc[item.name] = []; // How can I add the value of the second bmw occurrence into the array?
  }
  return acc;
}, {});

console.log(output);

What I have got:

{ 
"bmw": [],
"mercedes": [{"type": "gas"}],
"honda": [{"type": "electric"}]
}

Any pointers greatly appreciated as JS newbie here. Thanks!

Embedding scripts in html buttons

So, I’m a beginner programmer and figured I could do something short and fun. I made a short program in like 5 minutes, but I ran into a problem where I can’t figure out, how to make a button that runs a said script when pressed (e.g. makes an alert with a random number in it)
Here’s my code

<!DOCTYPE html>
<html>
    <Head>
        <h2>
        Random number Generator
        </h2>
    </Head>
    <body>
         <script src ="Script.js"></script>
        <button type="button" onclick="alert(randomNum)"> Generate! </button>
    </body>
</html>

and the script part here

    let newNumber = Math.random()
    let oneToHundred = newNumber * 1000
    let result = Math.floor(oneToHundred)
    return result
};
alert(randomNum) ```

I just can't figure out how to make the button search for a script and run it when pressed. I tried to embed the script search to the onclick part, but i got a syntax error.
Any help appreciated
Seven

Merging Palindromes

Please Solve This Question in Javascript

Given two strings, find all palindromes that can be formed with the letters of each string. From those palindromes, select one from each set that, when combined and rearranged, produces the longest palindrome possible. If there are multiple palindromes of that length, choose the alphabetically smallest of them.

Example

s1 = ‘aabbc’

s2 = ‘ddefefq’

All of the letters of the first string can make a palindrome. The choices using all letters are [abcba, bacab].

All of the letters of the second string can make a palindrome. The choices using all letters are [defqfed, dfeqefd, edfqfde, efdqdfe, fdeqedf, fedqdef].

The two longest results in s1 have a length of 5.

The six longest results in s2 have a length of 6.

From the longest results for s1 and s2, merge the two that form the lowest merged palindrome, alphabetically. In this case, choose abcba and defqfed. The two palindromes can be combined to form a single palindrome if either the c or the q is discarded. The alphabetically smallest combined palindrome is abdefcfedba.

Function Description

Complete the function mergePalindromes in the editor below. The function must return a string.

mergePalindromes has the following parameter(s):

string s1:  a string

string s2:  a string

Constraints

1 ≤ | s1 | ≤ 105
1 ≤ | s2 | ≤ 105
s1 and s2 will contain only lowercase English letters in the range ascii[a-z]

Input Format For Custom Testing
Sample Case 0
Sample Input For Custom Testing

STDIN Function


aab → s1 = ‘aab’
cca → s2 = ‘cca’
Sample Output

acaca
Explanation

Characters [‘a’, ‘a’] can be picked from the first string to form the palindrome ‘aa’. Characters [‘c’, ‘c’, ‘a’] can be picked from the second string to form the palindrome ‘cac’ and merged with ‘aa’ to form ‘acaca’.

Trying to pass props( this props is from other component ) from one component to another component

I have a component comment.js and it contains this.props.description under . I want to pass this (this.props.description) to issueDetails.js page. But I tried to set this description in this.state. Then I am passing but still not working. Only I want to pass {this.props.description}

import React from "react";
import { Link } from "react-router-dom";
import IssuesDetails from "./issuesDetails";

export default class Comment extends React.Component {
  constructor(props) {
    super(props);
    
    this.handleClick = this.handleClick.bind(this);
    this.state = {
      href1: "",
      pass: ""
    };
  }
  componentDidMount(){
    this.setState({pass:this.props.description});
  }
  handleClick() {
    var result = window.confirm("Are you sure you want to view the details?");
    if (result === true) {
      this.setState({href1:"/details"});
    } else {
      this.setState({href1:""});
    }
    return(
      <>
      {/* trying to pass here but failed */}
      <IssuesDetails pass1={this.state.pass} /> 
      </>
    )
  }
  render() {
    return (
      <>
        {/* href={`/issues/details`} */}
        <tr>
          <td>
            <a href={`/issues${this.state.href1}`} onClick={this.handleClick}>
              {this.props.description}
            </a>
          </td>
          <td>{this.props.severity}</td>
          <td>{this.props.children}</td>
        </tr>
        {/* <div>
          
        </div> */}
      </>
      
    );
  }
}
import React, { Component } from 'react'

export default class IssuesDetails extends Component {
  constructor(props){
    super(props);
  }
  render() {
    return (
    <>
    
      <h1>Isssue Details</h1>
      <h2>Details: - {this.props.pass1}</h2></>
    )
  }
}