I found out that this error comes out because the internet signal is bad
I hope this can help you if you have the same error.
Category: javascript
Category Added in a WPeMatico Campaign
setState works when i empty obj manually instead of passing in the obj
I am trying to reuse an object in different components so my initial obj. is empty but when i export it into my component and setState to obj., it doesn’t clear the state. but when I console.log the obj., it comes back as expected. any idea why this is happening?
this.state = {
name: '',
lastName: '',
age: 0,
kids: 0
}
const myEmptyObj = {
name: '',
lastName: '',
age: 0
}
// lets pretend this function has name, lastName, age, and kids with values
// this function should clear the state but update the kids to value 3. so everything
// empty but the kids field
myFunctionClearState() {
myEmptyObj.kids = 3;
setState(myEmptyObj);
}
Regular Expression Allowing Input For Only Numbers and One Decimal
The regular expression I am using currently is /[^d.]/g.
Currently this allows the user to only input numbers and decimals but also allows for more than one decimal number. I am using it for a text box to allow only a string of numbers along with one decimal following another string of numbers but ends.
Text box code:
onkeyup= "this.value=this.value.replace(/[^d.]/g, '' )".
Full html block:Enter your second number <input type="text" id="num2" onClick="(this.value='')" onkeyup= "this.value=this.value.replace(/[^d.]/g, '' )" />
I have this expression here that highlights what I’m looking for /^d+(.d+)?/gm it’s just I need it completely in-versed.
/^d+(.d+)?/gm
/d+(.d+)/gm
/[^d.]/g
/[^0-9.]/g
The preceding expressions allow input for everything but numbers and decimals. I need to allow only numbers and decimals for input.
I have seen others but none seem to accomplish exactly what I am looking for. I don’t not want to allow negative numbers either but would like it optional.
Thanks for the help.
Javascript: “Uncaught SyntaxError: Identifier starts immediately after numeric literal”
I am getting the error “Uncaught SyntaxError: Identifier starts immediately after numeric literal”. As I understand, this is from the variable identifier starting with a number, which I’m trying pass through in the function. I saw here to use escape identifiers, but there was no concrete solution on how to add them in when using PHP, which I am having difficulty implementing.
Html
<button class = "btn btn-primary edButton" onclick='edit_function(""<?php echo $var; ?>"\")'>action</button>
Js
function edit_function(id) {
...
Tab selection without JQuerry
I have a function in JQuerry to switch tabs and as it the only onle using JQuerry, I want to convert it to JS only. After hours of trying (still learning) and feeling miserable to fail at this trivial thing, I humbly ask for help.
$(document).ready(function() {
var previousActiveTabIndex = 0;
$(".tab-switcher").on('click', function (event) {
if (event.type === "click") {
var tabClicked = $(this).data("tab-index");
$(".tab-switcher").removeClass("active")
$(this).addClass("active")
if(tabClicked != previousActiveTabIndex) {
$(".tab-container").hide();
$("#allTabsContainer .tab-container").each(function () {
if($(this).data("tab-index") == tabClicked) {
$(this).show();
previousActiveTabIndex = $(this).data("tab-index");
return;
}
});
}
}
});
});
#header ul {
margin: 0.15em;
padding-bottom: 0.3em;
padding-left: 0.4em;
}
.tab-switcher {
display: inline-block;
cursor: pointer;
margin-right: 1.7em;
}
.tab-switcher:hover {
color: #0f0;
border-bottom: 0.15em solid var(--mainCol);
}
.tab-switcher.active {
color: var(--mainCol);
border-bottom: 0.15em solid var(--mainCol);
font-weight: bold;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="header">
<ul>
<li class="tab-switcher active" data-tab-index="0" tabindex="0">Locations</li>
<li class="tab-switcher" data-tab-index="1" tabindex="0">Inventory</li>
<li class="tab-switcher" data-tab-index="2" tabindex="0">Profile</li>
</ul>
</div>
<div id="allTabsContainer" data-tab-show="0">
<div class="tab-container" id="locations" data-tab-index="0">
content 1
</div>
<div class="tab-container" data-tab-index="1" style="display:none">
content 2
</div>
<div class="tab-container" data-tab-index="2" style="display:none">
content 3
</div>
</div>
I was about here when I gave up, my forEach/event listener won’t even work and I don’t know even why, any help/explanation appreciated.
function Tabmenu() {
var previousActiveTabIndex = 0;
let Tab = document.querySelectorAll('tab-switcher');
let Content = document.getElementsByClassName("tab-container");
Tab.forEach(t => t.addEventListener("clic", function(x) {
alert("coucou");
}))
}
window.onload = Tabmenu;
Vue3 window.print() results in 32k pages pdf
Im trying to print whole page using pretty simple print function. Currently page displays valid html and it looks good. But I have problem after window.print() execution which wants to print 32079 pages as we can see on attached image.
What am I missing?

Here is my code
// Html element that i want to print (whole page)
const prtHtml = document.getElementById('printer').innerHTML;
// Get all stylesheets HTML (using tailwind)
let stylesHtml = '';
for (const node of [...document.querySelectorAll('link[rel="stylesheet"], style')]) {
stylesHtml += node.outerHTML;
}
// Open the print window
const WinPrint = window.open('', '', 'left=0,top=0,width=1200,height=1600,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(`<!DOCTYPE html>
<html>
<head>
${stylesHtml}
</head>
<body>
${prtHtml}
</body>
</html>`);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print(); // trying to print 32k pages
```
How would I edit my code to add a square on mouse click?
I’m trying to draw a square on mouse click over an image that has been drawn in my canvas. My code already allows me to load my image but how would I edit the code to draw this square on mouse click? I’ve already looked on other examples, but to no avail..
`
<script>
var loadImg = document.getElementById('previewImg');
loadImg.addEventListener('change', handleImage, false);
var canvas = document.getElementById('canvasImg');
var ctx = canvas.getContext('2d');
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
canvas.width = img.width;
canvas.height = img.height;
canvas.style.width = '950px';
canvas.style.height = '600px';
ctx.drawImage(img,0,0);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
</script>
Why message.guild.me.permissions.has(“X”) returning me true
whatever i am writing inside message.guild.me.permissions.has it returns me true
Why ?
for example :
message.guild.me.permissions.has("X") // true ??
i am using Discord.js v13
Ruby on Rails 7, show a result in a view, before saving
I am trying to implement a dynamic function in Rails 7, the method is in the model.rb and i want to show the result on the onblur function of the field, any ideas how can I solve it using ajax?
Thanks in advance
how to focus next textfield when button clicked using pure javascript
I’m trying to focus on previous or next textfield on button click using pure javascript; NOT with jQuery.
There is an existing sample code here, but using jQuery:
http://jsfiddle.net/arunpjohny/stq4xn2d/
HTML
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="text" class="mytextbox">
<input type="button" class="mybutton" value="focus next" onclick="focusNext()">
<input type="button" class="mybutton" value="focus prev" onclick="focusPrev()">
JS
var focused = null;
$(".mytextbox").focus(function () {
focused = $(this);
}).first().focus();
function focusNext() {
if (focused && focused.length) {
focused.next('.mytextbox').focus();
}
}
function focusPrev() {
if (focused && focused.length) {
focused.prev('.mytextbox').focus();
}
}
echarts – custom toolbox feature does not work
I ‘m trying to add a custom toolbox feature to an echart and I’m getting the following error:
Uncaught TypeError: Bind must be called on a function
at bind (<anonymous>)
at echarts.js:80214:30
at each (echarts.js:423:24)
at createIconPaths (echarts.js:80158:11)
at DataDiffer.processFeature (echarts.js:80104:11)
at DataDiffer._performRestAdd (echarts.js:30822:31)
at DataDiffer._executeOneToOne (echarts.js:30739:14)
at DataDiffer.execute (echarts.js:30702:79)
at ToolboxView.render (echarts.js:80047:143)
at echarts.js:29722:27
The feature I’m trying to add is the following:
myTool1: {
show: true,
title: 'custom method',
icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
onclick: function () {
alert('myTool1')
}
}
It looks like that the onclick feature option is not passed correctly to the featureManager in echarts.
Has anyone experienced something similar? Any idea how to solve this?
how to filter a array of object by another object as key in JS?
I have an array of objects
let allData = [
{title:"Adams",age:24,gender:"male"},
{title:"Baker",age:24,gender:"female"},
{title:"Clark",age:23,gender:"male"},
{title:"Davis",age:23,gender:"female"},
{title:"Ghosh",age:23,gender:"female"},
{title:"Adams",age:23,gender:"male"},
{title:"Irwin",age:25,gender:"male"},
]
and list of filter in a Object like this
let filters = {
title:{filterTerm:[]},
gender:{filterTerm:["male"]},
age:{filterTerm:[23]}
}
i want to apply multiple filters on top of allData i tried using Array.some with Array.includes but it is not working when with multiple filters items below is my code
const getFilterRows = (rows, filters) => {
let filterCols = Object.keys(filters)
if (filterCols.length == 0) {
return rows
}
else {
let filteredR = rows.filter(i => {
return filterCols.some((s) => {
return filters[s].filterTerm.includes(i[s])
})
});
return filteredR
}
}
let filterd = getFilterRows(allData,filters)
How to go through this redux-devtools/extension, as I am facing an error as shown in attached image?
This is what I am getting error. I have tried npm install redux-devtools/extension and npm install, but didn’t work.
Alternative access control to fields of graphql types
I’d like to propose alternative approach to limiting user access to certain fields of graphql types.
One example usage of presented technique could be user preferences. Some users would like to see full details of, let’s say, system notifications. Others would like to see less details.
In another use case let’s say we have two types of users. One has full access to a certain type called SensitiveData, the other user type should see only parts of information. We’re going to handle all the logic in backend, so frontend just have to display what was handed to it.
I’m going to use nexusjs-like and prisma-like syntax. Some of the code is pseudo-code, some resemble real life example.
We start by defining common interface type that will be exposed on our server:
export const sensitiveDataInterface = interfaceType({
name: 'SensitiveDataBase',
definition(t) {
t.nonNull.string('id');
t.string('name');
t.field('createdAt', {
type: 'DateTime',
});
{
});
It doesn’t have to have any real implementations. It’s just a container.
Next we’re going to define two descendant types, first with full access, no restrictions (I omitted resolvers implementations, but you’d write them as you normally do):
export const sensitiveDataFullAccess = objectType({
name: 'SensitiveDataFullAccess',
definition(t) {
t.implements('SensitiveDataBase');
// prisma model can be used here as well
t.nonNull.string('id', resolve() ...);
t.string('name', resolve () ...);
t.field('createdAt', {
type: 'DateTime',
resolve () { return new Date(); } // returning actual data
});
t.field('fullAccessSpecificField', {
type: 'CustomType',
resolve () ...
});
{
});
Secondly we’re defining descendant type with limited access:
export const sensitiveDataRestrictedAccess = objectType({
name: 'SensitiveDataRestrictedAccess,
definition(t) {
t.implements('SensitiveDataBase');
t.nonNull.string('id', resolve() ...); // this is optional, unless we want to return real data, the ones we still want to expose
// we're skipping some of the fields, since they'll be exposed through SensitiveDataInterface interface and won't contain any real data anyway
t.field('createdAt', {
type: 'DateTime',
resolve () { return null; }
});
{
});
The last part is implementing root query. The query resolver will determine what actual type will be returned and what will be exposed to clients. This is the only place containing permission control logic:
export const sensitiveDataRoot = queryField('sensitiveData', {
type: 'SensitiveDataBase',
resolve: async (_parent, _args, context) => {
const user = context.getUser();
const allSensitiveData = await ctx.db.sensitiveDataTable.findMany();
if (isUserAllowedToViewFullData(user)) {
return allSensitiveData.map(sensitiveData => ({
...sensitiveData,
__typename: 'SensitiveDataFullAccess',
});
}
return allSensitiveData.map(sensitiveData => ({
...sensitiveData,
__typename: 'SensitiveDataRestrictedAccess',
});
},
});
Here lies the beauty of this technique. There’s no need for scraping data, convoluted data mapping, mixing permission logic with fields resolver.
Once we determine __typename, nexus will do the rest for us.
For the __typename part to work you might need to enable it in creating schema part (https://nexusjs.org/docs/guides/abstract-types):
...
features: {
abstractTypeStrategies: {
resolveType: false,
__typename: true,
isTypeOf: false,
},
}
Finally, when querying for the types from client we can simply write:
query getAllData () {
sensitiveData {
id
name
createdAt
// optionally
... on SensitiveDataFullAccess {
fullAccessSpecificField
}
}
}
Hope it will be useful to someone. It wasn’t for me, as the solution didn’t meet my company’s standards LOL.
Solving the above ‘problems’ can obviously be achieved in many different ways, however I haven’t seen similar approach across all Internet.
Type Error Cannot find module ‘x’ or its corresponding type declarations. Nextjs + TS
When I run npm run build on localhost, there are no errors, but when I try to deploy to some host like Vercel or Digital Ocean I get the following error:
Project Structure:
structure
Code: code
I also tried to add the path.
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"paths": {
"@/components/*": ["components/*"],
},
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx","components/*"],
"exclude": ["node_modules"]
}