I’m encountering an issue with live reload being enabled in my web development environment, and it’s causing an error message to appear in the console every time I refresh the page. I’m using extension live server, I’d like to disable it temporarily to avoid this error message cluttering my console output.console image
Category: javascript
Category Added in a WPeMatico Campaign
Select2 X button missing ver [email protected]
Hello I’m Regan I am developing website using laravel 10. As you can see in my screenshot the x button is missing. The first time I implement this its working fine, but after months, when I came back to the page, it happens.
Missing x button to unselect
Here are the script of my select2 maybe it helps. I wanted to append an HTML to a div when selected a data from guidebooksData. I also check my console it doesn’t have any errors. Have anyone met this problem before?
<script>
$(document).ready(function() {
$('#dropDownSelectBooks{{$pricing->id}}').select2({
placeholder:'{{__("search-guidebook")}}',
maximumSelectionLength: {{$pricing->total_guidebook}}
});
// Function to update selected guidebooks
function updateSelectedGuidebooks() {
var selectedGuidebooksContainer = $('#selected-guidebook{{$pricing->id}}');
var selectedGuidebooks = $('#dropDownSelectBooks' + currentSectionId).select2('data');
selectedGuidebooksContainer.empty();
var count = 1;
selectedGuidebooks.forEach(element => {
// Loop through guidebooksData to find the guidebook with the matching ID
var dataId = element.id.trim();
for (var i = 0; i < guidebooksData.length; i++) {
if (guidebooksData[i].id == dataId) {
// Create HTML elements to represent the guidebook
var guidebookHTML = '<div class="block">';
guidebookHTML += '<h3>Guidebook ' + count + '</h3>';
guidebookHTML += '<div class="book">';
guidebookHTML += '<div class="img" style="background: url('' + guidebooksData[i].thumbnail + '') no-repeat;"></div>';
guidebookHTML += '<div class="desc">';
guidebookHTML += '<p>Guidebook</p>';
guidebookHTML += '<h3>'+ guidebooksData[i].title +'</h3>';
guidebookHTML += '<span>by ' + guidebooksData[i].user.first_name + '</span>';
guidebookHTML += '</div>';
guidebookHTML += '</div>';
guidebookHTML += '</div>';
// Append the guidebook HTML to selectedGuidebooksContainer
selectedGuidebooksContainer.append(guidebookHTML);
break; // Exit the loop since the guidebook has been found
}
}
count = count + 1;
});
}
// Event listener for dropdown change
$('#dropDownSelectBooks{{$pricing->id}}').on('change', function (e) {
updateSelectedGuidebooks();
});
});
</script>
I have tried to search any missing x button in stackoverflow but it’s not the same problem as me. I also have tried to remove my functions but still its not working. Any ideas how to make it appear?
How can modify transformation in material design js file?
I have cloned this repository material design
In the catalog folder of this project catalog, at the path of /scripts/copy-docs.mjs, the following command remove some specific comments from md files.
const transforms = [
// catalog-only code comments are removed
{
before: /<!-- catalog-only-start -->(n)*?<!--s*/gm,
after: '',
},
{
before: /s*-->(n)*?<!-- catalog-only-end -->/gm,
after: '',
},
// removes everything in between github-only-start and github-only-end
// comments
{
before: /s*<!-- no-catalog-start -->(.|n)*?<!-- no-catalog-end -->s*/gm,
after: 'nn',
},
// eleventy pages end with `/` so `components/checkbox.md` will turn into the
// url `/components/checkbox`. Thus we need to transform the relative
// `./images` links to `../images`.
{
before: /images//gm,
after: '../images/',
},
];
async function fileIncludeTransform(filepath, fileContents) {
const catalogIncludeRegex = /<!--s?catalog-include "(.+)"s?-->/g;
const matches = [];
let match = catalogIncludeRegex.exec(fileContents);
// Collect all the regex matches
while (match) {
matches.push(match);
match = catalogIncludeRegex.exec(fileContents);
}
const fileDir = dirname(filepath);
// Iterate through the regex matches backward and splice in the file contents.
// Iterating backwards so that injecting won't affect match string indices.
for (let i = matches.length - 1; i >= 0; i--) {
const match = matches[i];
const matchedString = match[0];
const includePath = match[1];
console.log(`Injecting ${includePath} file contents into ${filepath}...`);
const includeContents = await readFile(join(fileDir, includePath), 'utf8');
fileContents = fileContents.slice(0, match.index) + includeContents +
fileContents.slice(match.index + matchedString.length);
}
return fileContents;
}
async function transformReadmes(filepaths, outdir = '', replacements = []) {
const readmePromises = filepaths.map(async (entry) => {
let readme = await readFile(entry, 'utf8');
console.log(`Transforming ${entry}`);
transforms.forEach((transform) => {
readme = readme.replaceAll(transform.before, transform.after);
});
readme = await fileIncludeTransform(entry, readme);
// The `components/<component-name>.md` path.
let localPath = relative(join('..', 'docs'), entry);
for (const [pattern, replacement] of replacements) {
const regex = new RegExp(pattern);
localPath = localPath.replace(regex, replacement);
}
// The output path at
// /catalog/site/components/<?local path>/<component name>.md
const outputPath = join('site', outdir, localPath);
console.log(`Writing trasnformed file to: ${outputPath}`);
return writeFile(outputPath, readme);
});
await Promise.all(readmePromises);
}
When i build the project, these pieces of codes does not remove specific comments from found files. I have this problem in windows, not linux based systems.
How can modify this transformation in windows?
In Boostrap 4 how can I change the the translucency of toasts to fully opaque?
I am using Boostrap 4.6 (and I cannot upgrade to BS 5 yet). How can I change the translucency of toasts to fully opaque?
My toast looks like this:
<div id="help" style="position: fixed; top: 0.5vw; bottom: 0.5vw; right: 10vw;">
<div class="toast" role="alert" aria-live="assertive" aria-atomic="true">
<div class="toast-header">
<strong class="mr-auto">Help for <%=systemName%></strong>
<button type="button" class="ml-2 mb-1 close" data-dismiss="toast" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="toast-body">
hallo
<!-- <zero-md src="help/hallswell_all_towers.md"></zero-md> -->
</div>
</div>
</div>
I tried to add in our CSS style sheet (which is loaded after the Bootstrap CSS) the following:
.toast {
opacity: 1;
}
but this does not have the desired effect.
So, how can I change the translucency of toasts?
Publishing a npm module but it’s not getting text predict (intellisense) when installed by users
I’m currently working on my package @xatsuuc/startonomy.
For some reason, it’s not getting intellisense when I’m installing it on user side. Below are my files. When I install the package and go to node_modules/@xatsuuc/startonomy it shows the .d.ts files but for some reason not a single bit of text predict works. Also, any suggestions for it? I don’t know if I’m doing things right when compiling on the user’s pc, or if I’m exporting modules correctly. Thanks in advance.
tsconfig.json
{
"compilerOptions": {
"target": "ESNext",
"resolveJsonModule": true,
"module": "commonjs",
"lib": [],
"allowJs": true,
"declaration": true,
"outDir": "./compiled",
"rootDir": "./src",
"removeComments": false,
"moduleResolution": "node",
"rootDirs": ["./src"],
"types": ["@types/mysql", "@types/node"],
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": [
"./src/**/*"
],
"exclude": []
}
package.json
{
"name": "@xatsuuc/startonomy",
"version": "2.0.0-Gamma",
"description": "A discord-based economy system",
"main": "compiled/index.js",
"repository": "https://github.com/xAtsuUC/Startonomy.git",
"author": "Tiziano Fioretti <[email protected]>",
"license": "CC BY-SA 4.0",
"private": false,
"dependencies": {
"mysql": "^2.18.1"
},
"files": [
"src",
"README.md",
"tsconfig.json"
],
"devDependencies": {
"@types/mysql": "^2.15.26",
"@types/node": "^20.11.30",
"@typescript-eslint/eslint-plugin": "^7.3.1",
"@typescript-eslint/parser": "^7.3.1",
"eslint": "^8.57.0",
"typedoc": "^0.25.12",
"typedoc-material-theme": "^1.0.2",
"typescript": "^5.4.3"
},
"publishConfig": {
"registry": "https://registry.npmjs.org/",
"access": "public"
},
"scripts": {
"preinstall": "npm i typescript",
"install": "tsc",
"postinstall": "npm uninstall typescript"
}
}
GuildManager.ts
import { Pool, ConnectionConfig } from "mysql"
import { EventEmitter } from "node:events"
import Util from "./Util"
/**
* Guild Manager
* @class GuildManager
* @extends EventEmitter
* @param {ConnectionConfig} database - The database connection configuration
* @example
* const economy = new guildManager({
* host: "localhost",
* user: "root",
* password: "password",
* database: "database"
* });
*/
class GuildManager extends EventEmitter {
database: ConnectionConfig
util: Util
constructor(database: ConnectionConfig) {
super()
this.database = database
this.util = new Util()
}
public test() {
console.log("Test")
}
}
export default GuildManager
index.ts
import GuildManager from "./GuildManager"
import Util from "./Util"
module.exports = { GuildManager, Util }
EJS is not being rendered
index.js
import express from "express";
import bodyParser from "body-parser";
const app = express();
const port = 3000;
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (req, res) => {
res.render("index.ejs");
});
app.post("/submit", (req, res) => {
const numLetters = req.body["fName"].length + req.body["lName"].length;
res.render("index.ejs", { numberOfLetters: numLetters });
});
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
index.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Name Letters</title>
</head>
<body>
<!-- Write your code here -->
<h1>Write your name below</h1>
<% if(locals.numberOfLetters){ %>
<h1>There are <%= numberOfLetters %> letters in your name.</h1>
<% } %>
<form action="/submit" method="POST">
<input type="text" name="fName" placeholder="First name">
<input type="text" name="lName" placeholder="Last name">
<input type="submit" value="OK">
</form>
</body>
</html>
Can someone help me? I have installed all the required libraries.
It’s not a big problem so I have tried whatever I could find on the internet.
My previous activity was successfully rendered and I did nothing different this time.
Filtering output on AWS State Machine
I’m currently stuck on how to filter the output from the previous step in my state machine.
Say the previous step in the state machine has an output of:
"input": {
"Configuration": [
{
"Hours billed": "40",
"Billing class": "A",
"Taxonomy": "261QB0400X",
},
{
"Hours billed": "40",
"Billing class": "B",
"Taxonomy": "261QB0400X",
},
{
"Hours billed": "20",
"Billing class": "C",
"Taxonomy": "261QR1300X",
}
]}
Is there to filter that output? Say the filter is “Taxonomy”: “261QB0400X”, and we want the answer to look like this:
"Configuration": [
{
"Hours billed": "40"
"Billing class": "A"
"Taxonomy": "261QB0400X",
},
{
"Hours billed": "40",
"Billing class": "B"
"Taxonomy": "261QB0400X",
}
]
I have tried using ResultSelector, Parameter, and OutputPath. But I haven’t had much success.
I would love your insight on how I should write the next step/how to filter the data out by using a specific Taxonomy coming from the front-end.
Thank you
Login form validation with jsf with javascript , create alert
I am trying to duplicate a program with primefaces and I need to show alert windows when validating the username and password fields of my login form.
Next I show you how the first program looks like

In my duplicated program that I don’t use primefaces I don’t know how to show the same alert result with bootstrap and javascript.
Next I show you the form of my duplicated program:

Currently I am not validating fields as I need to first show the alert as many times as I want by pressing the button, here the xhtml code:
<div class="col-6 position-absolute">
<div id="alertMessage"
class="alert alert-warning alert-dismissible fade show hidden"
role="alert">
<strong>Holy guacamole!</strong> You should check in on some of those
fields below.
<button type="button" class="btn-close" data-bs-dismiss="alert"
aria-label="Close"></button>
</div>
</div>
<div class="bg-white p-4 rounded-5"
style="box-shadow: 2px 2px 5px black;">
<div class="justify-content-center">
<img src="recursos/images/logo_empresarial.png" class="mb-1"></img>
</div>
<h:form id="formLogin">
<div class="text-center mt-2">
<h:outputLabel for="username" value="Usuario:"></h:outputLabel>
<h:inputText id="username" value="#{obeanlogin.usuario}"
required="true" requiredMessage="Ingrese un usuario"
class="form-control" />
</div>
<div class="text-center mt-2">
<h:outputLabel for="password" value="Password:"></h:outputLabel>
<h:inputText id="password" value="#{obeanlogin.contrasena}"
class="form-control" />
</div>
<div class="text-center mt-4">
<h:commandButton id="submitLogin" class="btn btn-primary"
onclick="return sendForm();"
value="Aceptar" action="#{obeanlogin.validaUsuarioContrasena()}" />
</div>
</h:form>
</div>
And my javascript code:
var form = document.getElementById('formLogin');
var username = document.getElementById('formLogin:username');
var password = document.getElementById('formLogin:password').value;
var alerta = document.getElementById('alertMessage');
var closeButton = document.querySelector('.alert .btn-close');
function sendForm() {
alerta.classList.remove('hidden');
console.log('se abrió ventana');
console.log(alerta);
return false;
}
/*closeButton.addEventListener('click', function() {
console.log(alerta);
alerta.classList.add('hidden'); // Oculta el alerta al añadir la clase 'hidden'
});*/
alerta.addEventListener('close.bs.alert', event => {
alerta.classList.add('hidden');
console.log('close close');
console.log(alerta);
})
Quiero saber como puedo lograr la misma ventana de mi primer programa con los campos vacíos, además de validar el usuario y contraseña incorrectos con la función de mi bean
How to host private files on github and link them in public html website? [duplicate]
i made a web game with html, css, javascript and published it in blogger.com but the problem is that anyone can open inspector and copy my code. how to make private files in github, and link them in my html, for example script.js, and so that users will not be able to copy or see the code of my script.js file through inspector, but that the game will still work fine and be public?
i tried to link the github script.js private file with the game logic in it in the html public website game, i didnt expect it to work, and it didnt
DataTables: (TypeError) m[v] is undefined
Trying to set up a DataTable with data provided as JSON by PHP.
function request_data() {
$.ajax({
url: './inc/get_data.php?mode=1',
method: 'POST',
data: $("#frmMain").serialize(), // Serialize form data
dataType: 'json',
success: function(baseData) {
makeDataTable(baseData);
}
});
}
function makeDataTable(new_data) {
console.table(new_data);
$('#table_log').DataTable({
columns: [
{ data: 'id' },
{ data: 'zeitstempel' },
{ data: 'tag' },
{ data: 'message' },
{ data: 'file' }
],
data: new_data
});
}
The result from get_data.php in DevConsole looks like:
05:37:52.373 new_data
05:37:52.403
Array(3) [ {…}, {…}, {…} ]
0: Object { id: "3", zeitstempel: "2024-03-24 21:32:49.525789+01", tag: "#1", … }
1: Object { id: "2", zeitstempel: "2024-03-24 19:50:17.568385+01", tag: "tag1", … }
2: Object { id: "1", zeitstempel: "2024-03-24 19:49:44.23372+01", tag: "tag1", … }
An empty DataTable is visible, and getting error:
TypeError: m[v] is undefined
Network Error AxiosError: Network Error at XMLHttpRequest.handleError, at Axios.request, and at async getUsers
I try to make CRUD in my project fullstack. I hope this error can be fine and find something helpful. Thanks in advance.
Verify Token To Login In Firebase (Aauthorization)
I’m coding a website, I us Firebase to store data. I’m currently coding the authorization function and have some questions. My idea of building a decentralized part is like this. When the user logs in, it will send to the API of the server that I host. Then from that API, the token will be sent to the user. Then I use the token to verify. I have some questions as follows:
- What do I use to save pre-authorized accounts on Firebase?
- Is the process that I authorize the account first, then I log in with that account, then create a token and then I authenticate that token with the command verifyToke(your_token)
I dont really understand how the verifyToken work, how it’s know that token is valid? Is it that I have to save an authorized account somewhere on Firebase so that account’s token will be valid then i can verify?
Vue i18n needs to be refreshed to change language
- I’m using a child Locale component imported into a parent Header component:
<Locale />
import Locale from '@/components/Locale/index.vue';
- Below is the code for the child Locale component:
<template>
<div class="locale">
<img
@click="toggleMenu()"
src="@/assets/svgs/icon_locale.svg"
class="icon localeBtn"
/>
</div>
<div v-show="isLocale" class="text-gray-500 right-8 px-2 dropdown">
<div v-for="(item, index) in locales" :key="index" @click="setLocale(item)">
{{ item.label }}
</div>
</div>
</template>
<script setup lang="ts">
import { locales } from '@/config/constants/locale.ts';
import { ref, onMounted, onBeforeUnmount } from 'vue';
import { useStore } from 'vuex';
const store = useStore();
const isLocale = ref(false);
const toggleMenu = () => {
isLocale.value = !isLocale.value;
};
function setLocale(locale) {
store.commit('system/SET_LOCALE', { lang: locale.name });
}
</script>
- The data iterated over with v-for is the following array:
export const locales = [
{
name: ‘kr’,
label: ‘Korean’,
},
{
name: ‘en’,
label: ‘English’,
},
];
- Therefore, I’m storing the selected language in the store by passing a string argument:
import makeLocale from '@/locale';
import { getItem, setItem } from '@/utils/localStorage';
export default {
namespaced: true,
state: {
locale: getItem('locale') || 'kr',
},
getters: {},
mutations: {
SET_LOCALE(state, { lang }) {
state.locale = lang;
setItem('locale', lang);
makeLocale.global.locale = lang;
},
},
actions: {},
};
5.makeLocale.global.locale = lang; Because of the code
This code creates a createI18 object in the selected language.
import { createI18n } from 'vue-i18n';
import en from './modules/en';
import kr from './modules/kr';
import { getItem } from '@/utils/localStorage';
import { locales } from '@/config/constants/locale';
export default createI18n({
locale: getItem('locale') || locales[0].name,
messages: {
kr,
en,
},
legacy: false,
});
- We then register this file globally in main.ts:
import makeLocale from '@/locale';
app.use(makeLocale);
- Below is the code for a child component using the language pack
<div class="mb-2">{{ t('myWallet.cautionSub') }}</div>
import { useI18n } from 'vue-i18n';
const { t } = useI18n();
===> But the selected language changes only after refreshing the page.
What part of the code is wrong if I want to change the language without refreshing?
Geolocation function buggy on mobile
This script seems to run successfully about 80% of the time on mobile, but it fails silently now and then. I ran console.log statements on it and plugged it into my PC and the console just returns >Getting location…
Most of the time, the user has to reboot the phone to get it working again. Isn’t there a safer way to run this script?
function getLocation() {
console.log("Getting location...");
navigator.geolocation.getCurrentPosition(showPosition);
}
function showPosition(position) {
console.log("Location received:", position);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log("Latitude:", latitude);
console.log("Longitude:", longitude);
document.getElementById("Latitude").value = latitude;
document.getElementById("Longitude").value = longitude;
}
EventListener is not being added to button elements
I have a list of products, each product having an id and item property. I have to add a remove button for every item. With every click of the remove button, that product should be removed.
I’m trying to loop though the list and for each product I’m creating a button element and setting its id attribute to the id of the product.
However, for some reason, the event listener is not getting added to the buttons except the last button (button#5) .
Below is the JS code I have written..
const div = document.body.querySelector('div');
let products = [
{
id: "1",
item: "Shirt"
},
{
id: "2",
item: "Jeans"
},
{
id: "3",
item: "T-shirt"
},
{
id: "4",
item: "Denim Jacket"
},
{
id: "5",
item: "Casual Shoes"
}
];
const removeItem = (itemId) => {
products = products.filter((prod) => {
return prod.id !== itemId;
})
console.log(products)
updateDom();
}
function updateDom() {
div.innerHTML = '';
div.style.padding = '20px';
for (let prod of products) {
let btn = document.createElement('button');
btn.id = prod.id;
btn.textContent = 'Remove';
btn.addEventListener('click', () => {
removeItem(btn.id);
console.log(btn.id);
})
div.innerHTML += `<li>${prod.item}</li> `
div.appendChild(btn);
}
}
updateDom();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div></div>
<script src="prac.js"></script>
</body>
</html>
Above is the html code where I’m trying to append the li and the button elements to the div. Why is the event listener only getting added to the last button element and not to every buttons? Am I missing something here? Thankyou for your time.