I add Elements to my list. But the Event Listener is only working for buttons I added in Html, alltough they have the same class.
I tried to add the Event Listener, after i added the button, but that also wasn´t working.
Blancer.com Tutorials and projects
Freelance Projects, Design and Programming Tutorials
Category Added in a WPeMatico Campaign
I add Elements to my list. But the Event Listener is only working for buttons I added in Html, alltough they have the same class.
I tried to add the Event Listener, after i added the button, but that also wasn´t working.
I want to fetch data from google analytics via google data api. The request is given below.
export async function fetchAnalyticsData() {
// getAccessToken();
const GA4_PROPERTY_ID = "";
const url = `https://analyticsdata.googleapis.com/v1beta/properties/${GA4_PROPERTY_ID}:runReport`;
const requestOptions = {
method: "POST",
headers: {
"Content-Type": "application/json",
// Add your authorization token here if required
Authorization: "Bearer YOUR_ACCESS_TOKEN",
},
body: JSON.stringify({
dateRanges: [{ startDate: "2023-09-01", endDate: "2023-09-15" }],
dimensions: [{ name: "country" }],
metrics: [{ name: "activeUsers" }],
}),
};
try {
const response = await fetch(url, requestOptions);
const data = await response.json();
console.log(data); // Do whatever you need with the data
} catch (error) {
console.error("Error fetching data:", error);
}
}
This request gives 401. “Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential”.
So, I created Oauth2 client id and client secret:
(https://i.stack.imgur.com/iDSSU.png)
How can i take a token for the request by using client id and secret if possible. I do not want users to login.
–
For a example a user goes to a page, but quickly goes back to another page – I use the AbortController from axios to abort the calls from the previous page to not slow down the app.
My question is – now that I’ve aborted the call – what do I do with the state?
For example FAQ’s were starting to load, so the react state is iLoading: true,
after aborting – it will continue being isLoading: true
even thought the user is not on the page I do not think this is correct, how should I proceed with the state? I also cannot call a FAILURE action because there is no error that has happened?
I’ve created an AbortController class that handles and keeps track of each call and on path change I cancel any ongoing requests.
I am validating an input for a password, where I require that the user must enter at least one special character, for example: (@#$%&.), in my code with jquery I am detecting the keyup event to evaluate what the user writes, while I write in the input all the characters are written correctly, until I try to do the @ with the key combination Alt + 64, the event detects when the Alt is pressed but in the result of the jquery code where I look for the value of the input it is not there the @ even though it is in the input.
This is my jquery code to evaluate the keyup event:
function validate_pass(element) {
let password = $(element).val();
if (!(/^(.{8,20}$)/.test(password))) {
return 'It must be between 8 and 20 characters.';
}
else if (!(/^(?=.*[A-Z])/.test(password))) {
return 'It must contain at least one capital letter.';
}
else if (!(/^(?=.*[a-z])/.test(password))) {
return 'It must contain at least one lowercase letter.';
}
else if (!(/^(?=.*[0-9])/.test(password))) {
return 'It must contain at least one digit (0-9).';
}
else if (!(/^(?=.*[@#$%&])/.test(password))) {
return "Must contain special characters (@#$%&).";
}
return true;
}
$('#user-pass').on('keyup',(e)=>{
if(e.which == 20 || e.which == 16){ //prevent bloq mayus and shift
return false;
}
console.log($('#user-pass').val());
let resp = validate_pass('#user-pass');
if(resp == true){
$('label[for="user-pass"]').text('Password').css('color','#9e9e9e');
$('#user-pass').removeClass('invalid');
$('#user-pass').addClass('valid');
}else{
$('label[for="user-pass"]').text(resp).css('color','red');
$('#user-pass').addClass('invalid');
}
});
Let’s imagine that I write the following password in the input so that I test the code: Jhon000@
In the console I get the following results:
J
Jh
Jho
John
Jhon0
Jhon00
Jhon000
but when I execute the combination of Alt + 64 to write the @ the console shows me this again in the log:
Jhon000
and I have to press some other key so that the keyup event shows me Jhon000@ in the console, for example I use the same Alt key.
Javascript ka question
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
To make an app but don’t know backend how to do it
I am currently building a website and have run into an issues. I am trying to create a slider and display images in this slider. I have all the images in an assets folder in my visual studio and I have imported into the slider component. I watched a tutorial on how to do it and the video uses url while I am trying to use imported pictures so the code is not working. can some one help me. this is the code below: return (
<div className=’w-full h-full rounded-2xl bg-center bg-cover duration-500′ style={{backgroundImage: ‘img(${slides[0].img})’}}>
)
I have looked for different videos on how it is done but most of all the videos I have seen use urls and not imports.
I’ve integrated AbortController into my React application to cancel Axios requests as part of my state management with Redux. My setup includes dispatching actions to update the application state when initiating and completing requests.
The issue arises when a request is cancelled using AbortController. Currently, if a request is cancelled, my application’s state may incorrectly remain in an isFetching: true state or it or worse, set an error state hasError: true, even though the request was intentionally cancelled and not actually in error or still fetching. ( this is because sometimes the cancellation is registered as an error and an error action is dispatched)
How can I efficiently manage my Redux state for cancelled requests to accurately reflect the state of the UI and not leave parts of my application in a perpetual loading or erroneous state due to cancelled operations?
AND another main question – is updating the state even needed in my case? The user has aborted the call, but the state is on another page
I am implementing loader functions on my browser router. The functions trigger an api which updates a context state value. Updating the state is causing the loader function to run again which initiates an infinite loop.
My browser router:
const createRouter = (
baseRoute: string,
currentUser: CurrentUser | undefined,
errorMessage: string,
getSubmission: (
appTypeId: string,
submissionId: string
) => Promise<SubmissionDetails | void>,
isError: boolean
) =>
createBrowserRouter([
{
path: '/:appTypeId/:submissionId/:referralMasterId?',
element: (
<AppLayout
name={currentUser?.name || 'User Name Not Found'}
isError={isError}
errorMessage={errorMessage}
/>
),
id: 'root',
loader: ({ params }) => {
const { appTypeId, referralMasterId, submissionId } =
params as ReferralParams
return defaulNewAPIs(
appTypeId,
currentUser?.username || 'User Name Not Found',
submissionId,
getSubmission
)
},
children: [
{
index: true,
},
],
},
])
export const AppRoutes: React.FC<{ baseRoute?: string }> = ({ baseRoute }) => {
const {
errorMessage,
getSubmission,
isError,
} = useContext(AppContext) as SelectedContextType
const currentUser = getCurrentUser()
return (
<RouterProvider
router={createRouter(
baseRoute ?? '',
currentUser,
errorMessage,
getSubmission,
isError
)}
/>
)
}
The important parameters above are the isError and getSubmission prop. Both of these come from a context file.
const [isError, setIsError] = useState(false)
const [errorMessage, setErrorMessage] = useState('Error')
function getSubmission(appTypeId: string, submissionId: string) {
return commonAxios
.get(
`/api/GetSubmissionInfo?appTypeId=${appTypeId}&submissionId=${submissionId}`
)
.then(function (response) {
return response.data
})
.catch(function (error: { message: string }) {
setIsError(true)
setErrorMessage(error.message)
setTimeout(() => setIsError(false), 5000)
})
}
getSubmission has a timeout which toggles the isError state after a failed api call.
Finally the implementation of isError is on the AppLayout component.
export const AppLayout: React.FC<{
name: string
showHeader?: boolean
isError: boolean
errorMessage: string
}> = ({ name, showHeader = true, isError, errorMessage }) => {
const currentUser = { name: name }
return (
<>
{showHeader && (
<AppHeader
appName="REFERRALS"
currentUser={currentUser}
showGenStar={true}
showGenesis={true}
showNotifications={false}
// notificationNumber={4}
/>
)}
{isError && <MuiAlert severity="error" text={errorMessage} />}
<Outlet />
</>
)
}
I am struggling to understand why this is causing an infinite loop
I’m creating a medical management website[Front End = HTML, CSS, JavaScript] [Backend = PHP, SQL] consisting of services like consultation and record management.
I’m currently having a confusion on how to display input data taken from a Patient which will be stored in the database and display that data in a form or receipt format to the Doctor treating that patient.
There’s no suitable YT videos regarding this problem. Please Help. I have a tight deadline
Currently I am using the shallow method from the enzyme library to write my jest unit test.
test("returns component when modal render mode is passed in", () => {
const wrapper = shallow(
<MyComponentRenderer appRenderMode={Example.Modal} />
);
expect.assertions(2);
expect(wrapper.getElement()).not.toBeNull();
expect(wrapper.text()).toBe("<MyComponentRenderer />");
wrapper.unmount();
});
If I remove the use of the enzyme library, I tried to convert it to the following test
test("returns component when modal render mode is passed in", async () => {
expect.assertions(1);
render(<MyComponentRenderer appRenderMode={Example.Modal} />);
screen. debug()
const MyComponent = await screen.findByTestId(
"my-component"
);
expect(MyComponent).toBeDefined();
});
But the issue is that the screen is coming up empty
TestingLibraryElementError: Unable to find an element by: [data-testid="my-component"]
Ignored nodes: comments, <script />, <style />
<body>
<div />
</body>
Ignored nodes: comments, <script />, <style />
<body>
<div />
</body>Error: Unable to find an element by: [data-testid="my-component"]
Ignored nodes: comments, <script />, <style />
<body>
<div />
</body>
Does anyone know how to fix this? My actual component that I am testing has nested components, maybe this is why?
Example of my component
const ViewComponent: React.FC = () => (
<DialogComponent customContent={<NewDialog />} /> // imported from another file
);
export const MyComponentRenderer = ({
appRenderMode,
}: IMyComponentRendererProps) => {
if (appRenderMode === AppRenderModes.Modal) {
return <ViewComponent />;
} else {
return null;
}
};
I have observed something strange in JS. If I do the following:
console.log(Object.getPrototypeOf({});
The above points to Object.prototype. To check:
console.log(Object.getPrototypeOf({}) === Object.prototype) //true
We know that the Prototype chain ends at null, which means Object.prototype.__proto__ should be null, and it is:
console.log(Object.getPrototypeOf(Object.getPrototypeOf({}))); //null
If the above is true, then why does the browser console show the presence of a circular chain at the end of the prototype chain? Check out the below image:
In the above image why does the __proto__ in the red box point back to Object.prototype? Why is this not null? And why is the __proto__ of __proto__ in the red box null?
I tried this on Chrome and Edge. Same results.
Thank you.
Tengo problemas para mostrar filas secundarias en DataTables.
Al principio cuando actualizo la tabla según lo seleccionado en la primera opción de selección “Select Combo” me muestra la columna secundaria, el problema se da cuando selecciono otra opción en el mismo “Select Combo” o en el segundo o tercero no me muestra las filas secundarias.
// JavaScript Document
$(document).ready(function(){
$("#estado_reside").on("change",function(){
var estado_reside = $(this).val();
$.ajax({
url :"get_data_chance.php",
type:"POST",
cache:false,
data:{
estado_reside:estado_reside
},
success:function(data){
$("#municipio_reside").html(data);
},
});
var table = $('#table_01').DataTable({
"ajax": "get_estructuras_edo.php",
"rowId": 'id',
"columns": [{
"className": 'dt-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "nombre_cargo" },
{ "data": "nombre_apellido" },
{ "data": "cedula" },
{ "data": "telefono" }
],
order: [[1, 'asc']],
destroy: true,
processing: true,
responsive: true,
dom: 'Blfrtip', /*Bfrtip*/
buttons: ['copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ],
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json'
},
});
$('#table_01').on('click', 'tbody td.dt-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
row.child.hide();
}
else {
row.child( format(row.data()) ).show();
}
} );
$('#table_01').on('requestChild.dt', function(e, row) {
row.child(format(row.data())).show();
})
table.on('stateLoaded', (e, settings, data) => {
for(var i = 0; i < data.childRows.length; i++) {
var row = table.row(data.childRows[i]);
row.child(format(row.data())).show();
}
})
});
$("#municipio_reside").on("change",function(){
var municipio_reside = $(this).val();
$.ajax({
url :"get_data_chance.php",
type:"POST",
cache:false,
data:{municipio_reside:municipio_reside},
success:function(data){
$("#parroquia_reside").html(data);
}
});
var table = $('#table_01').DataTable( {
"ajax": "get_estructuras_mp.php",
"rowId": 'id',
"columns": [ {
"className": 'dt-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "nombre_cargo" },
{ "data": "nombre_apellido" },
{ "data": "cedula" },
{ "data": "telefono" }
],
order: [[1, 'asc']],
destroy: true,
processing: true,
responsive: true,
dom: 'Blfrtip', /*Bfrtip*/
buttons: ['copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ],
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json'
},
} );
});
$("#parroquia_reside").on("change",function(){
var parroquia_reside = $(this).val();
$.ajax({
url :"get_data_chance.php",
type:"POST",
cache:false,
data:{parroquia_reside:parroquia_reside},
});
var table = $('#table_01').DataTable( {
"ajax": "get_estructuras_pq.php",
"rowId": 'id',
"columns": [ {
"className": 'dt-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ "data": "nombre_cargo" },
{ "data": "nombre_apellido" },
{ "data": "cedula" },
{ "data": "telefono" }
],
order: [[1, 'asc']],
destroy: true,
processing: true,
responsive: true,
dom: 'Blfrtip', /*Bfrtip*/
buttons: ['copyHtml5', 'excelHtml5', 'csvHtml5', 'pdfHtml5' ],
language: {
url: 'https://cdn.datatables.net/plug-ins/1.13.7/i18n/es-ES.json'
},
} );
});
});
function format ( d ) {
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Estado:</td>'+
'<td>'+d.des_estado+'</td>'+
'</tr>'+
'<tr>'+
'<td>Municipio:</td>'+
'<td>'+d.des_municipio+'</td>'+
'</tr>'+
'<tr>'+
'<td>Nivel de Estructura:</td>'+
'<td>'+d.nivel_estructura+'</td>'+
'</tr>'+
'</table>';
}
I’m making a website with images that enlarge when you click on them. I got the inspiration from W3 schools
https://www.w3schools.com/howto/howto_css_modal_images.asp
On my website I want to have multiple modal images on the same page, so I wanted to change the code so that I can create as much modals as I want. Once I click on an image there appears an error message. By default the modals are hidden.
Here is my js code:
var amountOfModals = 2;
var modalDivs = []
var imgs = []
var modalImgs = []
for (i = 0; i < amountOfModals; i++) {
modalDivs.push(document.getElementById("modal_" + String(i)));
imgs.push(document.getElementById("img_" + String(i)));
modalImgs.push(document.getElementById("modal_img_" + String(i)));
}
for (i = 0; i < amountOfModals; i++) {
imgs[i].onclick = function(x=i){
modalDivs[x].style.display = "block";
modalImgs[x].src = this.src;
};
}
var span = document.getElementsByClassName("close")[0];
span.onclick = function () {
for (i = 0; i < amountOfModals; i++) {
modalDivs[i].style.display = "none";
}
}
The error seems to be at line 13-15. The message:
Uncaught TypeError: Cannot read properties of undefined (reading 'style')
at imgs.<computed>.onclick (gallery.js:15:22)
What am I doing wrong?
btw here is my HTML:
<img src="../img/IMG_3444.JPG" id="img_0">
<div class="modal" id="modal_0">
<span class="close">×</span>
<img src="../img/IMG_3444.JPG" class="modal_horizontal" id="modal_img_0">
<div class="caption" id="caption_0">
<p>A sparrowhawk that has caught a prey.</p>
</div>
</div>
<br>
<img src="../img/IMG_4343.JPG" id="img_1">
<div class="modal" id="modal_1">
<span class="close">×</span>
<img src="../img/IMG_4343.JPG" class="modal_horizontal" id="modal_img_1">
<div class="caption" id="caption_1">
<p>A dragonfly sitting on a stick.</p>
</div>
</div>
I tried to define the function in which the error appears outside of the for-loop, but this didn’t fix the problem. It could have something to do with the parameter declaration or the arguments. I also tried to use addEventListener instead of onclick (with the proper syntax), but this also didn’t affect the error.
Thanks in advance.
I have an angular (16) application that I’m turning into an Android application using Ionic (version 7).
I have a page with a modal, in the browser it works fine, but when I try it on a real phone, the button does nothing and the modal won’t even open.
Here’s the parent component:
<div *ngFor="let timeframe of match.timeframes; index as i" class="ion-padding-top">
<ion-button expand="block" (click)="openModal(i)">
From: {{ convertDate(timeframe.start) | date : "short" }} to: {{ convertDate(timeframe.end) | date : "short" }}
</ion-button>
</div>
Basically every element that repeats in the ngFor cycle is a button that open a modal.
Here’s the openModal function:
async openModal(index: number) {
if (!this.match?.timeframes) return;
this.selectedTime = this.match.timeframes[index]?.start;
const modal = await this.modalCtrl.create({
component: AcceptModal,
componentProps: {
timeframe: this.match.timeframes[index],
},
});
modal.present();
const { data, role } = await modal.onWillDismiss();
if (role === "confirm") {
this.accept(data);
}
}
This is the AcceptModal component:
import { Component, Input } from "@angular/core";
import { IonicModule, ModalController } from "@ionic/angular";
import { Timeframe } from "../api/v1";
import { FormsModule } from "@angular/forms";
@Component({
selector: "accept-modal",
templateUrl: "./accept-modal.component.html",
styleUrls: ["./accept-modal.component.scss"],
standalone: true,
imports: [IonicModule, FormsModule],
})
export class AcceptModal {
@Input() timeframe: Timeframe | null = null;
selectedTimeframe: string | undefined = "";
constructor(private modalCtrl: ModalController) {}
ngOnInit() {
this.selectedTimeframe = this.timeframe?.start;
}
cancel() {
return this.modalCtrl.dismiss(null, "cancel");
}
confirm() {
return this.modalCtrl.dismiss(this.selectedTimeframe, "confirm");
}
}
and the html:
<ion-header>
<ion-toolbar>
<ion-buttons slot="start">
<ion-button color="medium" (click)="cancel()">Cancel</ion-button>
</ion-buttons>
<ion-buttons slot="end">
<ion-button color="medium" (click)="confirm()">Confirm</ion-button>
</ion-buttons>
</ion-toolbar>
</ion-header>
<ion-content class="block">
<ion-item>
<ion-datetime confirm="" [(ngModel)]="selectedTimeframe" min={{timeframe?.start}}
max={{timeframe?.end}}></ion-datetime>
</ion-item>
</ion-content>
What am I missing?
Here is the input that should be converted to JSON format as given below.
{RS0004036}:{1;2}:{0000003AB;0000003BC}_{RS0004036}:{0;3}:{0000003DE;0000003FG}_{RS0004036}:{3;3}:{0000003HI;0000003JK}
The code should read the above input, will create a JSON return string as follows. The returning JSON will return store which will be only one value of the index 0 of the input string and will not repeat as partList.Target JSON should be like this.
"storeList": [
{
"store": "RS0004036",
"partList": [
{
"part": "0000003AB",
"partSub": "0000003BC",
"qtyOnHand": "0",
"qtyMinMax": "3"
},
{
"part": "0000003DE",
"partSub": "0000003FG",
"qtyOnHand": "3",
"qtyMinMax": "3"
},
{
"part": "0000003HI",
"partSub": "0000003JK",
"qtyOnHand": "1",
"qtyMinMax": "2"
}
]
}
]
Here is my code:
const hdr_str = '{RS0004036}:{1;2}:{0000003AB;0000003BC}_{RS0004036}:{0;3}:{0000003DE;0000003FG}_{RS0004036}:{3;3}:{0000003HI;0000003JK}';;
var storeList = {};
var partList = [];
storeList.partList = partList;
//Processing
const partsDataEntries = hdr_str.split('_');
for (var index = 0; index < partsDataEntries.length; index++) {
const element = partsDataEntries[index].slice(1, -1);
console.log('element0'+element);
if (element != '') {
const storepart = element.split(':');
const storeId = storepart[0].slice(1, -1);
const [qtyOnHand, qtyMinMax] = element.split(':')[1].split(';');
console.log("element.split(':')[1]"+element.split(':')[1]);
const qtyOH = qtyOnHand.substring(1,qtyOnHand.length);
const qtyMM = qtyMinMax.substring(0,qtyMinMax.length-1);
const [partnum, partsub] = element.split(':')[2].split(';');
const part = partnum.substring(1,partnum.length);
storeList.storeId = storeId;
partList = {
"partnum": part,
"partsub": partsub,
"qtyOnHand": qtyOH,
"qtyMinMax": qtyMM
}
storeList.partList.push(partList);
}
}
console.log(JSON.stringify(storeList));
Somehow it is repeating the elements in my tool which has javascript engine which is very old and we cannot replace the tool.Can someone suggest how to fix it?
{"partList":[{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"}{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"},{"partnum":"0000003AB","partsub":"0000003BC","qtyOnHand":"0","qtyMinMax":"3"}],"storeId":"RS0004036"}