At my work there’s a component with an explicit “debugger” command that interrupts me every time I run the application with dev tools open. I do not have access to the source code of this component. How can I stop Chrome from EVER breaking on ANY “debugger” command? I tried going to sources and disabling breakpoints (Ctrl + F8) but that only remains as long as the browser is open.
Category: javascript
Category Added in a WPeMatico Campaign
AngularJS ng-repeat not working as expected
The ng-repeat works instantly, however, when data is changed programmatically, no changes occur on the html content.
HTML is as follows (index.html):
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="main-app-ctrl">
<div ng-repeat="dt in data" ng-click="change_data();">
<h1 ng-bind="dt"></h1>
</div>
</div>
</body>
</html>
AngularJS code (main.js):
let app = angular.module('app', []);
app.run(function($rootScope, $window){
});
app.controller('main-app-ctrl', function($scope, $window){
$scope.data = [1, 2];
$scope.change_data = function()
{
$scope.data = [1, 2, 3, 4, 5];
};
});
I tried to use bind the data differently but still the data doesn’t change. The HTML code is as follows:
<!DOCTYPE html>
<html lang="en">
<head>
<title>App</title>
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<div ng-app="app" ng-controller="main-app-ctrl">
<div ng-repeat="dt in data" ng-click="change_data();">
<h1>{{ dt }}</h1>
</div>
</div>
</body>
</html>
And AngularJS code as follows:
let app = angular.module('app', []);
app.run(function($rootScope, $window){
});
app.controller('main-app-ctrl', function($scope, $window){
$scope.data = [1, 2];
$scope.change_data = function()
{
$scope.data = [1, 2, 3, 4, 5];
};
});
Removing Last Text Parentheses Using jQuery From a String
I am trying to remove the text from the last parentheses within a string using jQuery. I am able to remove the parentheses from the string but the code removes every parentheses and I need the last one to be removed only. For example, I have the following string "This is a (test) string (where) last parentheses (needs) to be (removed) "
I wrote the code below to remove the parentheses and text within the parentheses.
$('p').text(function(_, text) {
return text.replace(/(.*?)/g, '');
});
The code I tried removed all the parentheses from within the string, I need to remove the last parentheses from within the string.
Removing Last Text Parenthesis Using jQuery From a String
I am trying to remove the text from the last paranthesis within a string using jQuery, I am able to remove the paranthesis from the string but the code removes every paranthesis and I need the last one to be removed only. For example I have the following string “This is a (test) string (where) last paranthesis (needs) to be (removed) ” I wrote the code below to remove the paranthesis and text within the parenthesis.
$('p').text(function(_, text) {
return text.replace(/(.*?)/g, '');
});
The code I tried removed all the paranthesis from within the string, I need to remove the last paranthesis from within the string.
How to create triangle geometry canvas with reactjs
Here is the image that I want to create with HTML Canvas in React/Next.js. I have no idea about HTML Canvas and I ask AI for this exact or similar things, but they are unable to create this type of Canvas Background.
Here is the Live Website link : Click
Image:
How can I add a second horizontal scrollbar to an image in Lightbox?
I’m trying to add a second horizontal scrollbar to the popup image generated by Lightbox. I know that scrollbars are not the way Lightbox is intended to be used; the image in Lightbox is traditionally constrained by the window size. But, scrollbars are what the client wants, and right now, there is one scrollbar on the bottom of the image, and I want to add a second scrollbar at the top of the image.
In my jsfiddle https://jsfiddle.net/mrgfvwd1/1/ the popup image has a scrollbar at the bottom (of course, we ignore the horizontal and vertical scrollbars added by jsfiddle).
I want to add a second horizontal above the image, and I’m following this earlier answer horizontal scrollbar on top and bottom of table and their jsfiddle https://jsfiddle.net/TBnqw/1/
But I can’t figure out which div or container to target in Lightbox with either the jQuery function that “echoes” the scrollbar to the top (in the accepted answer to the question above), or a pure CSS solution. Can I use jQuery append or prepend to add the div .wrapper1 to the markup output of Lightbox?
I’m loading the Lightbox script locally in the fiddle, in case it needs to be modified. I know that’s not a good idea, but worst case, we can.
HTML:
<a href="https://fastly.picsum.photos/id/11/2500/1667.jpg?hmac=xxjFJtAPgshYkysU_aqx2sZir-kIOjNR9vx0te7GycQ" data-lightbox="1">
<img src="https://fastly.picsum.photos/id/11/2500/1667.jpg?hmac=xxjFJtAPgshYkysU_aqx2sZir-kIOjNR9vx0te7GycQ" width="300">
</a>
CSS:
body.lb-disable-scrolling {
overflow: hidden;
}
.center {
text-align: center;
}
.new-div {
overflow-x: scroll;
overflow-y: hidden;
height: 20px;
background-color: red;
}
.lightboxOverlay {
position: absolute;
top: 0;
left: 0;
z-index: 9999;
background-color: black;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
opacity: 0.8;
display: none;
}
.lightbox {
position: absolute;
left: 0;
width: 100%;
z-index: 10000;
text-align: center;
line-height: 0;
font-weight: normal;
outline: none;
}
.lightbox .lb-image {
display: block;
width: 100% !important;
height: auto !important;
border-radius: 3px;
border: 4px solid white;
}
.lightbox a img {
border: none;
}
.lb-outerContainer {
position: relative;
*zoom: 1;
margin: 0 auto;
border-radius: 4px;
background-color: white;
margin-top: 30px;
}
.lb-outerContainer:after {
content: "";
display: table;
clear: both;
}
.lb-loader {
position: absolute;
top: 43%;
left: 0;
height: 25%;
width: 100%;
text-align: center;
line-height: 0;
}
.lb-cancel {
display: block;
width: 32px;
height: 32px;
margin: 0 auto;
background: url(../images/loading.gif) no-repeat;
}
.lb-nav {
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 100%;
z-index: 10;
}
.lb-container > .nav {
left: 0;
}
.lb-nav a {
outline: none;
background-image: url("data:image/gif;base64,R0lGODlhAQABAPAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==");
}
.lb-prev,
.lb-next {
height: 100%;
cursor: pointer;
display: block;
}
.lb-nav a.lb-prev {
width: 20%;
left: 0;
float: left;
background: url(../images/prev.png) left 48% no-repeat;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
opacity: 0;
-webkit-transition: opacity 0.6s;
-moz-transition: opacity 0.6s;
-o-transition: opacity 0.6s;
transition: opacity 0.6s;
}
.lb-nav a.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
}
.lb-nav a.lb-next {
width: 20%;
right: 0;
float: right;
background: url(../images/next.png) right 48% no-repeat;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
opacity: 0;
-webkit-transition: opacity 0.6s;
-moz-transition: opacity 0.6s;
-o-transition: opacity 0.6s;
transition: opacity 0.6s;
}
.lb-nav a.lb-next:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
}
.lb-dataContainer {
margin: 0 auto;
padding-top: 5px;
*zoom: 1;
width: 100%;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 4px;
}
.lb-dataContainer:after {
content: "";
display: table;
clear: both;
}
.lb-data {
padding: 0 4px;
color: #ccc;
}
.lb-data .lb-details {
width: 85%;
float: left;
text-align: left;
line-height: 1.1em;
}
.lb-data .lb-caption {
font-size: 13px;
font-weight: bold;
line-height: 1em;
}
.lb-data .lb-caption a {
color: #4ae;
}
.lb-data .lb-number {
display: block;
clear: left;
padding-bottom: 1em;
font-size: 12px;
color: #999999;
}
.lb-data .lb-close {
display: block;
float: right;
width: 30px;
height: 30px;
background: url(../images/close.png) top right no-repeat;
text-align: right;
outline: none;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=70);
opacity: 0.7;
-webkit-transition: opacity 0.2s;
-moz-transition: opacity 0.2s;
-o-transition: opacity 0.2s;
transition: opacity 0.2s;
}
.lb-data .lb-close:hover {
cursor: pointer;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
}
.lb-linkContainer {
position: relative;
}
#lightbox {
overflow-x: auto;
cursor: pointer;
}
#lightbox.active {
cursor: grabbing;
}
#lightbox::-webkit-scrollbar {
display: none;
}
.lb-data .lb-close {
display: block;
float: right;
width: 30px;
height: 30px;
background: url(../images/close.png) top right no-repeat;
text-align: right;
outline: none;
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=70);
opacity: 0.7;
-webkit-transition: opacity 0.2s;
-moz-transition: opacity 0.2s;
-o-transition: opacity 0.2s;
transition: opacity 0.2s;
position: absolute;
top: 10px;
right: 20px;
}
.lb-closeContainer {
background: rgba(0, 0, 0, 0.5);
left: 0;
width: 100%;
height: 50px;
position: fixed;
top: 0;
z-index: 99;
}
.admin-bar .lb-closeContainer {
top: 32px;
}
.lb-closeContainer:before {
content: "<-- Esc to close image. Use scroll bar to move left and right on wide images -->";
color: white;
font-size: 18px;
position: relative;
top: 25px;
}
Using LaunchDarkly’s React Web SDK, is there a way to send a context as a request body, rather than URI
I’m set up with LaunchDarkly’s React Web SDK in my app, and it works fine for small contexts. But I need to send a very large context with a lot of data, which cannot be done the default way in the URI (I get a 414 HTTP error).
I’ve read that it seems the way to get around this is to send the context as part of the request body, but I can’t seem to find a way to do it with the React Web SDK. I’ve tried sending the context as part of a call to identify, after initialization, but it still puts the context in the URI.
It seems like I may be able to use the rest API in tandem with the React SDK, but would require me to implement some extra safeguards and data sync. What is the easiest way to send a very large context?
Weird behaviour with JS split in a long string
What I’m trying to do with this code is to get all text after the “phraseToFind” from this really long string, but it just logs something completely different. In fact regardless of whatever I put in phraseToFind it just gives something unexpected.
Sorry character limit was exceeded had to put it in a pastebin. Sorry for the inconvenience.
Code with the long string:
https://pastebin.com/gzqh08MS
Rest of the code :
const phraseToFind = "metadataText ":null,"text ":{"textDirection ":"FIRST_STRONG ","text ":"";
const startIndex = x.indexOf(phraseToFind);
if (startIndex !== -1) {
const result = x.slice(startIndex + phraseToFind.length);
console.log(result);
}
Google GenAI Gemini returning package code instead of a response to the prompt
When trying to use the Google Gemini GenAI API, instead of actually creating text that responds to the code, I instead get passed code from the package itself.
(For context, I am using this in a Chrome extension using Plasmo).
This is the response I get:
()=>{
if (response.candidates && response.candidates.length > 0) {
if (response.candidates.length > 1) console.warn(`This response had ${response.candidates.length} ` + `candidates. Returning text from the first candidate only. ` + `Access response.candidates directly to use the other candidates.`);
if (hadBadFinishReason(response.candidates[0])) throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response);
return getText(response);
} else if (response.promptFeedback) throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response);
return "";
And this is the full class that makes use of the API.
require('dotenv').config();
const {GoogleGenerativeAI } = require("@google/generative-ai");
class AdviceLogic {
async getAdvice(pageText, question, mainPageUrl){
console.log("AL GA"+question+mainPageUrl+pageText);
if (pageText === undefined || pageText === null || pageText === "" || mainPageUrl === "" ){
return false;
}
else{
try{
const prompt = "Give the user 1-3 (max, if only 1 is necessary that's fine) CLICKABLE links EXCLUSIVELY from ones that are present on the current page and that are relevant to their request."
+ "with a short of what the link does based on their request and the page body. " +
"DO NOT, under any circumstance, include ANY links that are not present on the page. If there are no relevant links, please let the user know that there are no relevant links on the page. If there are no links at all, please let the user know that there are no links on the page."+
"If the user's request is not clear, please let the user know that the request is not clear. If the page content is not clear, please let the user know that the page content is not clear. If the page content is not relevant to the user's request, please let the user know that the page content is not relevant to the user's request."+
"Links will be automatically embedded if they follow the format of [Text](Link). Use 10 words at MOST for describing why to click on a link.";
pageText = pageText.replace(/href="/([^"]*)"/g, `href="${mainPageUrl}/$1"`);
console.log("1");
var queryPrompt = prompt + "This is the user's question: " + question + " This is the page content: " + pageText + "Give a clear and concise answer.";
console.log("2");
const result = await this.QueryAI(queryPrompt);
console.log("3");
console.log("response"+result.toString());
console.log("4");
return result;
}
catch(err){
console.log(err);
return false;
}
}
}
async QueryAI(question){
const genAI = new GoogleGenerativeAI(process.env.PLASMO_PUBLIC_GEMINI_API_KEY.toString());
// console.log("APIKEY"+process.env.PLASMO_PUBLIC_GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent(question);
console.log("result"+result.response.text);
return result.response.text;
}
}
export default AdviceLogic;
I based my implementation based on the offficial documentation found here: https://ai.google.dev/gemini-api/docs#node.js
If someone could help me with this it’d be greatly appreciated!
Set react state in high charts interactive map on click
const [externalState, setExternalState] = useState(null);
const options = {
chart: {
height: "60%", // Full height of the parent div
// width: "100%", // Full width of the Highcharts container
events: {
load: function() {
// Hide tooltip on load
this.tooltip.hide();
}
}
},
mapNavigation: {
enabled: true,
buttonOptions: {
theme: {
r: 8,
},
verticalAlign: 'bottom'
}
},
series: [{
type: 'map',
mapData: mapDataWorld,
data: data
dataLabels: {
enabled: true,
useHTML: true,
style: {
textOutline: '1px contrast(black)',
},
},
point: {
events: {
click: function() {
setExternalReactState({this.data}); // THIS IS WHERE THE ISSUE IS
this.series.chart.update({
tooltip: {
enabled: true
}
});
},
mouseOut: function() {
this.series.chart.update({
tooltip: {
enabled: false
}
});
}
}
}
}],
legend: {
enabled: false
},
tooltip: {
enabled: true,
useHTML: true,
style: {
fontSize: 16,
},
},
};
Above is my options for the HighCharts interactive map. In my current functionality, the tooltip does not appear unless you click on a part of the map. When I add the line setExternalReactState({this.data}); to series.point.events.click, it causes a rerender, and this.series no longer exists. this only has the property destroyed. How can I set externalState while maintaining this.series.chart.update?
Array.push is overwriting the 0 index over and over
Just like the title says, in my react app, array.push is not ever pushing anything. Im not talking about state, im talking about vanilla JS arrays. Im sure im doing something really dumb.
In the code below i will send over an answer object to selectedAnswer().
The object looks like
{answer: “first answer”, correct: true}
or
{answer: “second answer”, correct: false}
…etc
var userAnswers = [];
function selectedAnswer(choice) {
userAnswers.push(choice)
}
I will ALWAYS receive back the userAnswers array as the last object i tried to push to the array. If i answer 4 times in a row, the last thing i pushed to the array is in the [0] index and nothing else is in the array
i have also tried this with no luck
function selectedAnswer(choice) {
var newArray = [...userAnswers, choice]
userAnswers= newArray;
}
What am i doing wrong here, what basic JS fundamental did i forget.
HIKVISION ISAPI iDS-TCM203-A
A am trying to get the car license plate Hikvision iDS-TCM203-A by using ISAPI. The camera admin panel allow you to recognize plate number by using the next button
The problem is I need to get that value in the NodeJS application. I have subscribed to /ISAPI/Event/notification/alertStream long polling channel, but sometimes it does not emit the license plate value from a car in camera viewport
const request = require("request");
const xml2js = require("xml2js");
const { errorData } = require("../utils/errorData");
const parser = new xml2js.Parser();
const createListener = (requestUrl, { auth, logger, onData } = {}) => {
const handlePackage = (data) => {
try {
logger.log(JSON.stringify(data));
onData(data);
} catch {
console.log("not json :-(");
}
};
return request
.get(requestUrl)
.auth(auth.username, auth.password, false)
.on("response", function (response) {
if (response.statusCode === 200) {
console.log("Listening");
logger.log("Connection opened");
response
.on("data", function (chunk) {
parser.parseString(chunk, function (err, result) {
if (!result) {
return;
}
handlePackage(result);
});
})
.on("error", (error) => {
logger.log(`Listener error: ${JSON.stringify(errorData(error))}`);
process.exit(-1);
})
.on("close", () => {
logger.log("Connection closed");
process.exit(-1);
});
} else {
logger.log(`Listener error (endpoint): code ${response.statusCode}`);
process.exit(-1);
}
})
.on("error", function (error) {
logger.log(`Listener error (request): ${JSON.stringify(errorData(error))}`);
process.exit(-1);
});
};
module.exports = { createListener }
To solve the missing license plates problem I want to spam the detect request for each 1 second. I need to get the endpoint to read all license plates from a current capture frame. The reference code is
const main = async () => {
await pb.admins.authWithPassword(POCKETBASE_ADMIN_EMAIL, POCKETBASE_ADMIN_PASSWORD).catch(() => {});
while (true) {
const image = await captureImage();
const cars = await captureLicensePlate(image);
if (!cars.length) {
fs.unlinkSync(`./public/image/${image}`);
}
for (const { licensePlate, bbox_bottom, bbox_left, bbox_right, bbox_top } of cars) {
logger.log(`DETECT CREATED licensePlate=${licensePlate} image=${image}`);
const dto = {
licensePlate,
bbox_top,
bbox_left,
bbox_right,
bbox_bottom,
image,
};
console.log(JSON.stringify(dto, null, 2))
await pb.collection("DETECT").create(dto);
}
await sleep(DETECT_TIMEOUT);
}
};
I have tried a lot of code to achieve required behavior. The /ISAPI/Traffic/channels/1/licensePlateAuditData/record?format=json and /ISAPI/Traffic/channels/1/vehicleDetect/plates are giving me 401 no matter if auth credentials works for /ISAPI/Event/notification/alertStream. Could you give me an example which just works well, not googled solution which will not work especially with this camera. Maybe steps to reproduce to setup the admin panel?
Error: Unknown authentication strategy “google” in Passport.js OAuth Setup
I’m trying to implement Google OAuth in my Node.js application using Passport.js, but I keep getting the following error when accessing the /auth/google route:
Error: Unknown authentication strategy "google"
at attempt (/path/to/project/node_modules/passport/lib/middleware/authenticate.js:193:39)
at authenticate (/path/to/project/node_modules/passport/lib/middleware/authenticate.js:379:7)
...
I’ve already set up my GoogleStrategy and initialized Passport, but something seems to be missing. Below are the relevant files.
auth.ts (Passport Configuration)
import passport from "passport";
import { Strategy as GoogleStrategy } from "passport-google-oauth20";
import User from "../models/user.model"; // Mongoose User model
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID!,
clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
callbackURL: "/auth/google/callback",
},
async (accessToken, refreshToken, profile, done) => {
try {
let user = await User.findOne({ googleId: profile.id });
if (!user) {
user = await User.create({
googleId: profile.id,
email: profile.emails![0].value,
displayName: profile.displayName,
profilePic: profile.photos![0].value,
});
}
done(null, user);
} catch (error) {
done(error, undefined);
}
}
)
);
passport.serializeUser((user: any, done) => done(null, user._id));
passport.deserializeUser(async (id: string, done) => {
try {
const user = await User.findById(id);
done(null, user);
} catch (error) {
done(error, null);
}
});
export default passport;
app.ts (Main Server File)
import express from "express";
import helmet from "helmet";
import cors from "cors";
import morgan from "morgan";
import dotenv from "dotenv";
import mongoose from "mongoose";
import session from "express-session";
import MongoStore from "connect-mongo";
import passport from "./auth"; // Importing the configured Passport instance
import authRoute from "./routes/auth"; // Auth routes
dotenv.config();
const app = express();
// Middleware
app.use(helmet());
app.use(cors());
app.use(morgan("dev"));
app.use(express.json());
app.use(
session({
secret: process.env.SESSION_SECRET!,
resave: false,
saveUninitialized: false,
store: MongoStore.create({ mongoUrl: process.env.MONGODB_URI! }),
cookie: {
secure: process.env.NODE_ENV === "production",
sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
maxAge: 24 * 60 * 60 * 1000, // 24 hours
},
})
);
// Initialize Passport
app.use(passport.initialize());
app.use(passport.session());
// MongoDB Connection
mongoose
.connect(process.env.MONGODB_URI!)
.then(() => console.log("Mongodb connected successfully"))
.catch((err) => console.error(err));
// Routes
app.use("/auth", authRoute);
const port = process.env.PORT || 8000;
app.listen(port, () => {
console.log(`Server listening on port ${port} http://localhost:${port}`);
});
auth.ts (Router)
import express from "express";
import passport from "../auth"; // Using the same Passport instance
const router = express.Router();
router.get(
"/google",
passport.authenticate("google", { scope: ["profile", "email"] })
);
router.get(
"/google/callback",
passport.authenticate("google", { failureRedirect: "/login" }),
(req, res) => {
res.redirect(`${process.env.CLIENT_URL}/dashboard`);
}
);
export default router;
Packages Installed:
"dependencies": {
"connect-mongo": "^5.1.0",
"cors": "^2.8.5",
"dotenv": "^16.4.5",
"express": "^4.21.1",
"express-session": "^1.18.1",
"helmet": "^8.0.0",
"mongoose": "^8.7.3",
"morgan": "^1.10.0",
"passport": "^0.7.0",
"passport-google-oauth20": "^2.0.0",
"passport-local": "^1.0.0"
},
"devDependencies": {
"@types/cors": "^2.8.17",
"@types/express": "^5.0.0",
"@types/express-session": "^1.18.0",
"@types/morgan": "^1.9.9",
"@types/node": "^22.8.1",
"@types/passport": "^1.0.17",
"@types/passport-google-oauth20": "^2.0.16",
"nodemon": "^3.1.7",
"ts-node": "^10.9.2",
"typescript": "^5.6.3"
}
I’ve verified that:
- Google OAuth strategy is registered before routes are used.
- The same passport instance is being used across the app.
- All necessary packages are installed.
- All my env secrets are correct
I’ve also restarted the server multiple times but the error persists.
Double-checked the environment variables.
Ensured only one instance of passport is being used.
Verified the MongoDB connection and session configuration.
Why am I getting the Unknown authentication strategy “google” error, and how can I fix it?
MUI with TypeScript MultiSelect Dropdown Not Selecting or Updating Values
I have been trying to build a multiselect dropdown list with checkboxes. The dropdown is being populated by an API call, and I am trying to updated a set of values to write back to the DB. I can get the dropdown to populate, but I cannot seem to get the checkboxes to be checked or set the values.
Here is my Dropdown:
import * as React from 'react';
import axios from 'axios';
import { Checkbox, FormControl, FormHelperText, InputLabel, Select, MenuItem, ListItemText, OutlinedInput } from '@material-ui/core';
import { FormControl, FormHelperText, InputLabel, Select, MenuItem, ListItemText, OutlinedInput } from '@material-ui/core';
export default function dropdownMultiSelect(props) {
const { label, name, handleInputChange, prompt, value, url } = props;
const [options, setOptions] = React.useState([]);
// Fetch Data for Dropdown list
React.useEffect(() => {
const fetchData = async () => {
const res = await axios.get(url);
setOptions( res.data);
};
fetchData();
}, []);
return (
<FormControl variant='outlined' >
<InputLabel>{label}</InputLabel>
<Select
multiple
value={value}
onChange={handleInputChange}
renderValue={(selected) => selected.map((x) => x.name).join(', ')}
>
{options.map((option, id) => (
<MenuItem
key={option.id}
value={option.id}
>
<Checkbox checked={value.includes(option.id)} />
{option.name}
</MenuItem>
))}
</Select>
</FormControl>
);
}
I am using the same onChange event that I have used for the rest of my form to catch the input change and set the values.
OnChange Event:
const [values, setValues] = React.useState({} as any);
const [errors, setErrors] = React.useState({} as any);
const handleInputChange = e => {
const { name, value } = e.target;
setValues({
...values,
[name]: value
});
if (validateOnChange) { validate({ [name]: value }); }
};
Can someone please show me what I am doing wrong so I can get this thing working.
WhatsApp adds extra char after coping phone number
I’m using macOs 15.0.1, using WhatsApp client 2.24.20.79.
When you try to copy a phone number from receiver profile (by clicking on it), WhatsApp adds a special char after such number.
Such char is [U+202C], which seems to be “an empty string“
Be aware of this beacuse regex in JavaScript and PHP are not seeing this as a char, so you funcitons like this will not work:
function checkNumber(elem) {
let floatRegex = /^((d+(.d *)?)|((d*.)?d+))$/;
let error = 'error';
elem.val(elem.val().replace(",", "."));
if(!floatRegex.test(elem.val()) && elem.val() !== '') {
elem.addClass(error);
}
else {
elem.removeClass(error);
}
}
Any suggestion about a regex that can include such char?
I’m looking for a regex to remove such char

