Multiple email input fields autofilling to same value

I have a form with a variable number of email input fields. The user can click a button to add an additional email input if the wish. My form then maps out the inputs:

function renderEmailFields() {
  return [...Array(numberOfEmails).keys()].map((i) => {
    return (
      <div key={i} className={styles.inputContainer}>
         <InputValidatable
            autoFocus={true}
            className={styles.input}
            id={`supportSquadEmail-${i}`}
            isValid={Validation.isEmailAddress(inviteEmails[i])}
            name={`supportSquadEmail-${i}`}
            value={inviteEmails[i]}
            onChange={(e) => handleEmailChange(i, e)}
            placeholder="Enter email here..."
          />

 </div>
 );
});
}

When I click on any of the email inputs, my Chrome browser gives my autocomplete options. Selecting one of the autocomplete options is causing ALL of the email inputs to populate with that value.

Calling third party middlewares inside a custom middleware in NodeJS Express

I’m learning NodesJS Express. I am using Express-Validator for my testing purposes.
Here is my testing program.

const express = require("express");
const app = express();
const port = 5000;
let bodyParser = require("body-parser");

const { body, validationResult } = require("express-validator");

app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.post(
  "/user",
  body("username").isEmail(),
  body("password").isLength({ min: 5 }),
  (req, res) => {
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    console.log("Login successfully!");
    res.send(200);
  }
);

app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

When I tried to use a post request with the body parameter: { username:test@, password:12345a }, it worked as my expectation. The server will response like this:

response

The problem happened when I tried to wrap all the logic in the post request handler into a single middleware. When I sent the same post request, it didn’t show the error like the example above. That means the two express-validator donot work. Here is my new program.

const express = require("express");
const app = express();
const port = 5000;
let bodyParser = require("body-parser");

const { body, validationResult } = require("express-validator");

app.use(express.json());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

const validateEmailAndPwdlength = (req, res, next) => {
  body("username").isEmail(); // the express-validator middleware doesn't work here.
  body("password").isLength({ min: 5 });  // the express-validator middleware doesn't work here.
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.status(400).json({ errors: errors.array() });
  }
  console.log("Login successfully!");
  res.sendStatus(200);
};

app.post(
  "/user",
  validateEmailAndPwdlength
);

app.listen(port, () => {
  console.log(`Server is listening on port ${port}`);
});

The two express-validator body(“username”).isEmail() and body(“password”).isLength({ min: 5 }) are the validation chains. From Express-Validator document, it says that ‘The validation chain is a middleware, and it should be passed to an Express route handler’. Why should we place them a Express route handler? If not, how can we call them inside my second example?

Thank you so much for your time!

document.execCommand(‘removeFormat’) failing on Chrome when trying to remove format set by document.execCommand(‘hiliteColor’)

I’m adding a background to some selected text in a contenteditable element via document.execCommand('hiliteColor', false, '#d4ecff');.

If the selected text contains some formatting tags (<b></b> for instance), calling document.execCommand('removeFormat') on the selection does not remove all the formats. It’s like the background colour is passed to the text formerly encompassed into <b></b>.

I’m facing the issue on Chrome (version 100.0.4896.75 – 64 bits) as well as Brave (version 1.37.111 Chromium: 100.0.4896.79 – 64 bits). Everything seems to work as expected on Firefox.

Here’s a demo and steps to reproduce: https://jsfiddle.net/L82ogcf5/

How do I retrieve URLs that are used when clicking buttons on a website?

On this website I need to download 17 xlsx files after picking the names in a dropdown window. This must be automated so I need the 17 URLs to be transferred using HTTP.

This is the HTML code related to this part:

<div class="card-body">
    <strong> Listino </strong><br>
    <form action="https://b2b.bergamaschi.com/commerciale/listino-personalizzato" method="post">
     <input type="hidden" name="cliente" class="form-control" value="008701"> 
     <div class="form-group">
      <!-- <label class="control-label mb-1"> Linea: </label> -->
      <select class="form-control" id="linea" name="linea" required="">
       <option value="*" selected=""> TUTTE LE LINEE </option>
       <option value="AC">ACCESSORISTICA</option>
       <option value="AM">AMMORTIZZATORI</option>
       <option value="AO">ATTREZZATURE PROFESSIONALI</option>
       <option value="BA">BATTERIE</option>
       <option value="CA">CANDELE</option>
       <option value="CS">CASCHI</option>
       <option value="FA">FANALERIA E LAMPADE</option>
       <option value="FI">FILTRI</option>
       <option value="GD">KIT E VARIE</option>
       <option value="LG">LOGISTICA</option>
       <option value="LU">LUBRIFICANTI</option>
       <option value="OE">MOBILITA' ELETTRICA</option>
       <option value="PN">PNEUMATICI</option>
       <option value="RE">RICAMBI ELETTRICI</option>
       <option value="RI">RICAMBISTICA</option>
       <option value="FR">SISTEMI FRENANTI</option>
       <option value="TM">TRASMISSIONI MOTO</option>
       <option value="TR">TRASMISSIONI SCOOTER</option>
      </select>
     </div>  
     <div class="form-group">
      <button name="xls" type="submit" class="btn btn-success">
       <span>Scarica XLS </span>
      </button>
      <button name="pdf" type="submit" class="btn btn-danger">
       <span>Scarica PDF </span>
      </button>
     </div>    
    </form>
   </div>

Manually I’d need to pick the name in a dropdown window (select tag) and click a button (the first one, named “xls”).

I tried with no success:

  • right-click, inspect
  • event listener tab
  • network tab
  • to use the link given in the form tag

How can I get those URLs?

Javascript: Make calculator display result after clicking operator

in Javascript, i’m making a simple calculator. I would like for it to display the result of an expression not only after using the equal button, but also when clicking a new operator to start a new equation.

Example: 2 then + is clicked and stored as firstNum, then 3 is clicked and the output shows 5, which then replaces firstNum

const btns = document.querySelector('.button');
const input = document.querySelector('#txtresult')
let btn = {
  zero: document.querySelector('#zero'),
  one: document.querySelector('#one'),
  two: document.querySelector('#two'),
  three: document.querySelector('#three'),
  four: document.querySelector('#four'),
  five: document.querySelector('#five'),
  six: document.querySelector('#six'),
  seven: document.querySelector('#seven'),
  eight: document.querySelector('#eight'),
  nine: document.querySelector('#nine'),
  add: document.querySelector('#add'),
  subtract: document.querySelector('#subtract'),
  multiply: document.querySelector('#multiply'),
  divide: document.querySelector('#divide'),
  dot: document.querySelector('#dot'),
  equal: document.querySelector('#equal'),
  clear: document.querySelector('#clear'),
}

let firstVal;
let secondVal;
let operator;

function storeNum(op) {
  firstVal = parseFloat(input.value);
  input.value = op;
  operator = op;
  return firstVal;
}

function storeSec() {
  secondVal = parseFloat(input.value);
  input.value = operate(firstVal, secondVal, operator);
}

const removeZero = () => (input.value === '0') ? input.value = '' : false;

const removeOp = () => (input.value === '+' || input.value === '/' || input.value === '*' || input.value === '-') ? input.value = '' : false;

function operate(x, y, operator) {
  if (operator === '+') {
    return add(x, y);
  } else if (operator === '-') {
    return subtract(x, y);
  } else if (operator === '*') {
    return multiply(x, y);
  } else if (operator === '/') {
    return divide(x, y);
  }
}

function click() {
  btn.zero.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 0;
  });
  btn.one.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 1;
  });
  btn.two.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 2;
  });
  btn.three.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 3;
  });
  btn.four.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 4;
  });
  btn.five.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 5;
  });
  btn.six.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 6;
  });
  btn.seven.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 7;
  });
  btn.eight.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 8;
  });
  btn.nine.addEventListener('click', () => {
    removeZero();
    removeOp();
    input.value += 9;
  });
  btn.divide.addEventListener('click', () => {
    storeNum('/');
  });
  btn.multiply.addEventListener('click', () => {
    storeNum('*');
  });
  btn.subtract.addEventListener('click', () => {
    storeNum('-');
  });
  btn.add.addEventListener('click', () => {
    storeNum('+');
    
  });
  btn.dot.addEventListener('click', () => {
    input.value += '.';
  });
  btn.clear.addEventListener('click', () => {
    firstVal = 0;
    secondVal = 0;
    input.value = 0;
  });
  btn.equal.addEventListener('click', () => {
    storeSec();
  });
}

function add(x, y) {
    const num = x + y;
  const rounded = Math.round(num * 1000) / 1000;
  return rounded;
}

function subtract(x, y) {
  const num = x - y;
  const rounded = Math.round(num * 1000) / 1000;
  return rounded;
}

function multiply(x, y) {
  const num = x * y;
  const rounded = Math.round(num * 1000) / 1000;
  return rounded;
}

function divide(x, y) {
    if(x === 0 && y === 0) {
    return 'no';
  }
  const num = x / y;
  const rounded = Math.round(num * 1000) / 1000;
  return rounded;
}

click();
body {
  display: flex;
  justify-content: center;
}

button {
  font-size: 15px;
  display: flex;
  flex: 1;
  font-weight: bold;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #8e8e8e;
  background-color: #ccc;
  border: none;
  border-radius: 8px;
  box-shadow: 0 9px #999;
  font-family: sans-serif;
}

button:active {
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

#split {
  display: flex;
  flex: 1;
  margin-top: 12px;
  justify-content: center;
  border-radius: 10px;
}

#container {
  display: flex;
  width: 500px;
  height: 300px;
  padding: 20px;
  flex-direction: column;
  border-radius: 10px;
  background-color: #DEDEDE;

}

#top {
  display: flex;
  flex: 1;
  margin: 5px;
  border-radius: 10px;
}

#txtresult {
  display: flex;
  flex: 1;
  margin: 5px;
  border-radius: 10px;
  background-color: #ccc;
  border: none;
  font-size: 50px;
  font-family: 'M PLUS 1p', sans-serif;
  text-align: right;
  padding-right: 10px;
  color: #8e8e8e;

}

#txtresult:hover {
  background-color: #bfbfbf;
  box-shadow: none;
  border-color: transparent;

}

#txtresult:focus {
  outline: 2px solid grey;
  box-shadow: none;
  border-color: transparent;
}

#buttons {
  display: flex;
  flex: 3;
  margin: 5px;
}

.row {
  display: flex;
  flex: 1;
  flex-direction: column;
}

.button {
  display: flex;
  flex: 1;
  margin: 10px;
  justify-content: center;
  border-radius: 10px;

}

#reset {
  font-weight: bold;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: #8e8e8e;
  background-color: #ccc;
  border: none;
  border-radius: 8px;
  box-shadow: 0 9px #999;
  font-family: sans-serif;
}

#reset:active {
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}
<!DOCTYPE html>
<html lang='en'>

  <head>
    <meta charset='UTF-8'>
    <title>calculator</title>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=M+PLUS+1p:wght@400;500&display=swap" rel="stylesheet">
  </head>

  <body>
    <div id='container'>
      <input type='text' id='txtresult'>
      <div id='buttons'>
        <div class=row>
          <div class=button id='seven'><button>7</button></div>
          <div class=button id='four'><button>4</button></div>
          <div class=button id='one'><button>1</button></div>
          <div class=button id='zero'><button>0</button></div>
        </div>
        <div class=row>
          <div class=button id='eight'><button>8</button></div>
          <div class=button id='five'><button>5</button></div>
          <div class=button id='two'><button>2</button></div>
          <div class=button id='dot'><button>.</button></div>
        </div>
        <div class=row>
          <div class=button id='nine'><button>9</button></div>
          <div class=button id='six'><button>6</button></div>
          <div class=button id='three'><button>3</button></div>
          <div id='split'>
            <div class=button id='clear'><button>c</button></div>
            <div class=button id='equal'><button>=</button></div>
          </div>

        </div>
        <div class=row>
          <div class=button id='divide'><button>/</button></div>
          <div class=button id='multiply'><button>*</button></div>
          <div class=button id='subtract'><button>-</button></div>
          <div class=button id='add'><button>+</button></div>
        </div>
      </div>
    </div>
  </body>

</html>

Any ideas?

React Structure: Avoiding multiple ternary operators

Within a component I’m attempting to “hide” and “show” elements as a user clicks through content. I was told ternary operators are the way to do this. However now it’s getting far more complicated / messy due to nested ternary operators.

Is this the correct approach in React or is there a better way?

Example:

const [compltedWaveOne, compltedWaveOne] = useState(false);
const [compltedWaveTwo, compltedWaveTwo] = useState(false);
const [compltedWaveThree, compltedWaveThree] = useState(false);
const [compltedWaveFour, compltedWaveFour] = useState(false);
   
  {compltedWaveOne ?
  ...Large amount of content 
  : //else 
  ...Large amount of content 
  }

  ... Now I need more content here if completedWaveTwo is true etc. Also need to hide the other content 

Cypress and Javascript: Logging function gives a blank

I have a function that is looping through arrays and giving me numbers as the output. It is working correctly because the cy.get(values) gives what I want. However, when I try to call cy.log(<func>) I get a blank (undefined). I’m not sure what’s going on.

const func = () => {
        const nums = numArray.get() 
        let new = []
        for (let i = 0; i <= 2; i++) {
            const arr = nums[i].temps
            arr.forEach((element) => {
                new.push(element.aggregate)
            })
        }
     cy.get(new) 
}

enter image description here

However, when I do this in my it function it gives me a blank or undefined

it('test', function () {
    ..........
    cy.log(func())
  }
}

enter image description here

Can anyone help here?

Possible unhandled promise rejection (id:29)

Working on React-Native for first time and using keychain for login page where I got this issue.

import React, { useEffect, useState } from "react";
import { StyleSheet, Text, TextInput, View, Dimensions } from "react-native";
import * as Keychain from "react-native-keychain";

export default function App() {
  const [isLoggedIn, setIsLoggedIn] = useState(false);
  const [userDetails, setUserDetails] = useState({});
  useEffect(() => {
    (async () => {
      try {
        const credentials = await Keychain.getGenericPassword();
        if (credentials) {
          setIsLoggedIn(true);
          setUserDetails(credentials);
        } else {
          console.log("No credentials stored");
        }
      } catch (error) {
        console.log("Keychain couldn't be accessed!", error);
      }
    })();
  }, []);
  
  const handleLogin = async () => {
    // login api call here
   
    const username = "Shivam";
    const password = "shivam";
    await Keychain.setGenericPassword(username, password);
    setIsLoggedIn(true);
    setUserDetails({password, username});
  };
  const handleLogout = async()=>{
    const logout = await Keychain.resetGenericPassword();
    console.log({logout});
    if(logout){
      setIsLoggedIn(false);
      setUserDetails({});
    }
  }
  return (
    <View style={styles.container}>
      {!isLoggedIn ? (
        <View>
          <Text style={styles.helloText}>Hello Tayze User!</Text>
          <TextInput placeholder="email" style={styles.textInput} />
          <TextInput
            placeholder="password"
            secureTextEntry
            style={styles.textInput}
          />
          <Text style={styles.loginBtn} onPress={handleLogin}>
            Login
          </Text>
        </View>
      ) : (
        <View>
          <Text style={styles.welcomeText}>
            Welcome back! {userDetails}
          </Text>
          <Text style={styles.logoutBtn} onPress={handleLogout} >Logout</Text>
        </View>
      )}
    </View>
  );
}
const screenWidth = Dimensions.get("screen").width;

I’m getting the following error:

Possible unhandled promise rejection (id:0: Network request failed)

Here’s the promise code, I don’t see what’s wrong here, any ideas?
This code is setting the user during login and getting to home page where user name will displayed and one logout button

My XMLHttpRequest isn’t receiving data from my local node.js server

I’m having a problem with receiving the data from my server, and I think the problem is a little less common than I would really want it to be.

I am trying to retreive data of a list of professionals from my company’s database, and then format the json data into my html list. I am able to successfully retreive the data from the server, but I can’t seem to have my javascript file to detect any changes received (using chrome v.100.0.4896.75 and firefox v.99.0).
Feel free to ask questions if I am not explaining this correctly.

I’ve tried to looking here: Returning data from Axios API
But I can’t seem to figure out the problem, or even if it’s a CORS error that I’m not being told about in the console.

I think the problem is because the request in my node.js server isn’t stopping, though I am unsure on how I can check that

Result of the console.log

My code currently:

The node.js server “server.js”

var express = require('express'),
    request = require('request'),
    axios = require('axios');
    bodyParser = require('body-parser'),
    app = express();

app.all('*', function (req, res, next) {

    // The config is so that I can add headers, but that part isn't the scope of my problem
    // like with the use of a token to access my database data.
    var config = {
        method: 'get',
        url: 'https://jsonplaceholder.typicode.com/posts', 
        // I've tested this site and you can easily make GET requests from it, since 
        // this is a similar example, I'm not showing the company's site and token 
        // password for obvious reasons.
    };

    axios(config)
    .then(function (response) {
        console.log("GET professionals: ")
        console.log(JSON.stringify(response.data));
        // I want to stop the response and return the data here to index.js
    })
    .catch(function (error) {
        console.log(error);
        return error;
        // And return error data here in case something went wrong
    });
});

app.listen(3000, function () {
    console.log("server started at port 3000");
});

My javascript file “index.js” making a request to the server

const http = new XMLHttpRequest();
const url='http://127.0.0.1:3000'; // This will call my server
http.open("GET", url);

http.onreadystatechange=function () {
   if(http.readyState == 4) {
     // I want to retreive my data here, but I'm not getting anything
     var data=JSON.parse(http.responseText);
     console.log(List of professionals:n  "+ data);
   }
}
http.send();

The head of my markup page “index.html”

<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">
  <script src="./node_modules/axios/dist/axios.min.js"></script>
  <script src="index.js"></script>
  <title>Document</title>
</head>

TypeScript conditional types for React props

I have a component that can have 2 different props. But these props are linked: if one is defined the other is not, and vice versa.

I followed this article here: https://dev.to/maissenayed/conditional-react-props-with-typescript-43lg
And ended up with something like this:

type PropsIconOrImg =
    { icon: string, img?: never } |
    { icon?: never, img: string };

This works well when using the component. I can give one and only one props otherwise Typescript is not happy.
But it is in the component itself that the behavior is not so good. If I do something like this:

if (icon) {
    // Here img should be of type never, but instead is of type string | undefined
}

Because my props icon is defined, Typescript should know that the props img should not be defined. Is it a limitation of Typescript of is there a better way to do it?

sonarcloud dont check duplication javascript

I’ve been looking for hours how to disable sonarcloud checking on duplicate lines/blocks in my sonar-project.properties file, and I still can’t make it, it’s driving me crazy.

I’ve tried
sonar.cpd.exclusions=**/*.js
sonar.cpd.exclusions=**/*

But it’s not working.

How to achieve this simple task ?

Thanks a lot for your help !

What JavaScript framework and library should i use for my Forum-like app?

So I’ve been thinking about coding a Foum-like website with features like stack overflow and other websites for a long time now and already have everything planned out. When I started to look into the coding side of things, a few questions popped into my head.

The main question being what framework and library i should use for this project. (Yes, I have researched for a long time now, and still can’t find a good answer). As you could imagine, a website like this would have to handle a large amount of user input like posts, comments, up/downvotes and more.

If someone could help me with this question, I would really appreciate a good answer!

(If someone is wondering, im looking forward to code this website with javascript)

Validate Regex in switch true/false [duplicate]

One of my switch cases checks this regex

regex_y = /[a-zA-Z0-9_]{3,20}$/;
str = 'sdsdsdsd:sdsdsdsdd.ssdsdsdsdds';

switch (true) {
    case !regex_y.test(str):
        // do anything
        return false;
        break;
// more switch cases to check
}

As the string sdsdsdsd:sdsdsdsdd.ssdsdsdsdds contains a .and a : I need the str to be defined as false but it is not. Please help me with this. What am I doing wrong?

It kind of looks like that the str is check from the beginning after unallowed characters. Same with sdsdsddsd...dsdsd....sdsdsd.

Thanks for your support!

Fix @ Jinja variable parsing at Javascript code in a static JS file …?

I am running into this “old problem”: Jinja variable parsing only works on the html template (passed in to render_template), so if your Javascript code is in a static JS file the Flask/Jinja variables can’t be accessed”.
Jinja Flask issue: Uncaught SyntaxError: Unexpected token { in JSON at position 1 at JSON.parse
Does anyone know if there is already a solution for this. It’s ugly to embed the JS code in the HTML file