Category: javascript
Category Added in a WPeMatico Campaign
How do I append an input element with an attribute of checkbox?
I am new to JavaScript and attempting to create a to-do list. How can I append an input with a checkbox attribute to my code so that paragraphs can be checked off once completed?
Here is my code below:
// ! DOM ELEMENTS
const taskInput = document.getElementById('taskInput');
const taskList = document.getElementById('taskList');
// ! ADD TASK
function addTask() {
if (taskInput.value === '') {
alert('Oh no... You have not written anything?');
} else {
let paragraph = document.createElement('p');
paragraph.textContent = taskInput.value;
taskList.appendChild(paragraph);
saveTasks();
}
taskInput.value = '';
}
<div class="container">
<h1>TO DO LIST</h1>
<input type="text" id="taskInput" placeholder="ENTER TASK HERE!">
<button id="addButton" click="addTask()">ADD</button>
<div id="taskList">
</div>
<p> lorem 10</p>
</div>
Webpack unable to load FontAwesome Kit (6.x) via NPM into JS of App?
I have an app in which I’m trying to load some JS into their own .js files (i.e. bootstrap will be loaded via bootstrap.hash.js, fontawesome will be fontawesome.hash.js)
I’m using webpack to do this – but am struggling with fontawesome and their kits specifically (I have a pro subscription). I can load fontawesome via CSS/Fonts no problem – but wanted to use some of the other features available only to JS+SVGs (like layering and masking).
I can load fontawesome pro, it works great. Locally I can have webpack load up the all.min.js and it puts it in the fontawesome.hash.js for me – but I need to do that with the kit as it has custom icons that I have added.
This is an example of a working webpack.config.js that loads fontawesome into it’s own .js file and puts it in my template:
const autoprefixer = require("autoprefixer");
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
//const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
mode: "production",
entry: {
vendor: "./static/myapp/src/js/vendor.js",
fontawesome: "@fortawesome/fontawesome-pro/js/all.min.js",
main: "./static/myapp/src/js/main.js",
},
output: {
filename: "[name].[contenthash].js",
path: path.join(__dirname, "static/myapp/dist/js/"),
publicPath: "/static/myapp/dist/js/",
},
optimization: {
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
splitChunks: {
cacheGroups: {
bootstrapCss: {
name: 'bootstrap',
test: /bootstrap.scss$/,
chunks: 'all',
enforce: true,
},
// fontawesomeCss: {
// name: 'fontawesome',
// test: /fontawesome.scss$/,
// chunks: 'all',
// enforce: true,
// },
fontawesomeJs: {
name: 'fontawesome',
test: /[\/]@fortawesome[\/]fontawesome-pro[\/]js[\/]all.min.js$/,
chunks: 'all',
enforce: true,
},
},
},
},
module: {
rules: [
{
test: /.(scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {sourceMap: true}
},
{
loader: "postcss-loader",
options: {postcssOptions: {plugins: [autoprefixer()]}}
},
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: ['./static/myapp/src/css'],
},
},
},
],
},
{
test: /.(woff(2)?|ttf|eot|svg)(?v=d+.d+.d+)?$/,
type: 'asset/resource',
generator: {
filename: 'fonts/[name][hash].[ext]',
},
},
],
},
plugins: [
//new BundleAnalyzerPlugin(),
new MiniCssExtractPlugin({
filename: '../css/[name].[contenthash].css',
chunkFilename: '../css/[name].[contenthash].css',
}),
new CleanWebpackPlugin(),
new HtmlWebPackPlugin({
template: path.join(
__dirname,
"static/myapp/src/html/webpack_bundles.html"
),
filename: path.join(
__dirname,
"templates/myapp/webpack_bundles.html"
),
// Use our template to control placement of the bundles
inject: false,
chunks: ['bootstrap', 'fontawesome', 'vendor', 'main'],
chunksSortMode: 'manual',
scriptLoading: "blocking",
}),
],
};
Here is a non-working webpack.config.js where I try to load my kit (which is installed via npm):
const autoprefixer = require("autoprefixer");
const {CleanWebpackPlugin} = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const HtmlWebPackPlugin = require("html-webpack-plugin");
const path = require("path");
const CssMinimizerPlugin = require("css-minimizer-webpack-plugin");
const TerserPlugin = require("terser-webpack-plugin");
//const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
mode: "production",
entry: {
vendor: "./static/myapp/src/js/vendor.js",
fontawesome: "@awesome.me/kit-123456abc/icons/js/all.min.js",
main: "./static/myapp/src/js/main.js",
},
output: {
filename: "[name].[contenthash].js",
path: path.join(__dirname, "static/myapp/dist/js/"),
publicPath: "/static/myapp/dist/js/",
},
optimization: {
minimizer: [
new CssMinimizerPlugin(),
new TerserPlugin(),
],
splitChunks: {
cacheGroups: {
bootstrapCss: {
name: 'bootstrap',
test: /bootstrap.scss$/,
chunks: 'all',
enforce: true,
},
// fontawesomeCss: {
// name: 'fontawesome',
// test: /fontawesome.scss$/,
// chunks: 'all',
// enforce: true,
// },
fontawesomeJs: {
name: 'fontawesome',
test: /[\/]@awesome.me[\/]kit-123456abc[\/]icons[\/]js[\/]all.min.js$/,
chunks: 'all',
enforce: true,
},
},
},
},
module: {
rules: [
{
test: /.(scss)$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: "css-loader",
options: {sourceMap: true}
},
{
loader: "postcss-loader",
options: {postcssOptions: {plugins: [autoprefixer()]}}
},
{
loader: 'sass-loader',
options: {
sassOptions: {
includePaths: ['./static/myapp/src/css'],
},
},
},
],
},
{
test: /.(woff(2)?|ttf|eot|svg)(?v=d+.d+.d+)?$/,
type: 'asset/resource',
generator: {
filename: 'fonts/[name][hash].[ext]',
},
},
],
},
plugins: [
//new BundleAnalyzerPlugin(),
new MiniCssExtractPlugin({
filename: '../css/[name].[contenthash].css',
chunkFilename: '../css/[name].[contenthash].css',
}),
new CleanWebpackPlugin(),
new HtmlWebPackPlugin({
template: path.join(
__dirname,
"static/myapp/src/html/webpack_bundles.html"
),
filename: path.join(
__dirname,
"templates/myapp/webpack_bundles.html"
),
// Use our template to control placement of the bundles
inject: false,
chunks: ['bootstrap', 'fontawesome', 'vendor', 'main'],
chunksSortMode: 'manual',
scriptLoading: "blocking",
}),
],
};
However that gives me this error:
ERROR in fontawesome
Module not found: Error: Package path ./icons/js/all.min.js is not exported from package /Users/me/project/myapp/node_modules/@awesome.me/kit-123456abc (see exports field in /Users/me/project/myapp/node_modules/@awesome.me/kit-123456abc/package.json)
I can see the file if I open my node_module directory and navigate to it.
If I open the package.json it says in the error I see these relevant parts:
// Other similar stuff before this
"./icons/sharp/solid": {
"types": "./icons/modules/sharp/solid.d.ts",
"import": "./icons/modules/sharp/solid.mjs",
"require": "./icons/modules/sharp/solid.js",
"default": "./icons/modules/sharp/solid.js"
},
"./icons/sharp/thin": {
"types": "./icons/modules/sharp/thin.d.ts",
"import": "./icons/modules/sharp/thin.mjs",
"require": "./icons/modules/sharp/thin.js",
"default": "./icons/modules/sharp/thin.js"
},
"./icons/kit/custom": {
"types": "./icons/modules/kit/custom.d.ts",
"import": "./icons/modules/kit/custom.mjs",
"require": "./icons/modules/kit/custom.js",
"default": "./icons/modules/kit/custom.js"
},
"./icons/css/*.css": {
"default": "./icons/css/*.css"
},
"./icons/less/*.less": {
"default": "./icons/less/*.less"
},
"./icons/scss/*.scss": {
"default": "./icons/scss/*.scss"
},
// Other stuff after this
So I changed my webpack to include what I thought might be the appropriate thing:
entry: {
// ...
fontawesome: ["@awesome.me/kit-123456abc/icons/classic/solid", "@awesome.me/kit-123456abc/icons/kit/custom"],
// ...
},
It builds the fontawesome.hash.js file and inserts it into my html – but the file is empty.
The file only contains:
(()=>{"use strict"})();
Any help would be hugely appreciated!
React Native Styling doesn’t work unless it’s inline
I simply have 2 text elements that I want to style but giving them css via style file doesn’t change anything. However when I gave them inline css it works. I removed everything in case there are some conflicts but it still doesn’t work and here’s the whole file;
index.js
/* eslint-disable no-const-assign */
import React from 'react';
import { View, Text } from 'react-native';
import styles from './style';
/**
* creates a video screen view
*
* @param {object} props - props
* @param {object} props.route - current route object
* @returns {module:JSX.Element} - JSX.Element
*/
const Video = ({ route }) => {
return (
<View style={styles.stoppedContainer}>
<View>
<Text style={styles.redText}>Top</Text>
</View>
<View>
<Text>Bottom</Text>
</View>
</View>
);
};
export default Video;
Here’s the css
style.js
import { StyleSheet } from 'react-native';
/**
* @returns {object} - object
*/
const styles = () => {
return StyleSheet.create({
stoppedContainer: {
flex: 1,
display: 'flex',
flexDirection: 'column-reverse',
},
redText: {
color: 'red',
fontSize: 30,
},
});
};
export default styles;
Dont show in other select
I have a modal with chips and serial codes, when I select a chip I can change the serial code, but I don’t want to show the same serial code if it is selected by another select, I can’t do it, can anyone help?
var chipsSelecionados = [];
$("input[name='inventarios[]']").each(function() {
var id = $(this).val();
chipsSelecionados.push(id);
});
var optionsChips = seriais.map(function(seriais) {
//se o selecionado
var id = seriais.id;
if ($.inArray(id.toString(), chipsSelecionados) === -1) {
return "<option value='" + seriais.id + "'>" + seriais.serial + "</option>";
}
}).join("");
$('#modal-buscar-linha').modal("hide");
var novaLinha = "<tr>" +
"<input type='hidden' name='inventarios[]' value='" + idChip + "'>" +
"<td style='vertical-align: middle;'><select class='form-control' style='margin: 0 auto;'>" + optionsChips + "</select></td>" +
"<td>" + agenda + "</td>" +
"<td style='vertical-align: middle;'><select class='form-control' style='margin: 0 auto;'><option>Não selecionar</option>" + options + "</select></td>" +
"<td class='text-center'>" +
"<button class='btn btn-danger delete-button' type='button'><i class='fa fa-trash' aria-hidden='true'></i></button>" +
"</td>" +
"</tr>";
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
I can’t change the text of an element using textContent on Reddit
I need to highlight the text in the comment form and change the highlighted part to another word
But reddit won’t let me change the comment form in any way, the text just doesn’t change, I don’t know what to do anymore
I’m making a plugin for chrome and this functionality will be in my plugin.
I also tried to change the text in the form via the console, nothing works either
Polymorphic associations when you are not sure what the Datatype will be?
I am setting up a database for a CRM project. I’m trying to set-up polymorphic one-to-many associations with mySQL and Sequelize, following this tutorial, where the example is a Comment that can belong to an Image or a Video.
I have Reunions, Clients, Projects, Tasks, and possibly later other elements, where I want the user to be able to leave a Note, a Link, or a Document. I debated putting the Notes/Link/Document into one table but I think it might make it very chaotic and take a long time to filter?
The problem is our Clients and Projects have UUIDs for primary keys, but Tasks and Reunions have integers. From what I gather it’s not possible to have a column that accepts two types of Datatypes, so I’m thinking my options are:
– Change everything to have UUIDs
– Give an int ID number to the Clients and Projects
– Scratch everything because I am thinking about it wrong
– …???
Could you just point me in the right direction of what would be good practice in this case?
I am junior developer working with another junior on a huge project so we’re only slightly overwhelmed, ya kno
This is the first time I do something like this, so I am pretty sure I am missing a lot of elements moving forward.
Duplicating dialog box on the same html page won’t work
hope you’re all having a wonderful day.
<dialog></dialog><button></button>
<dialog></dialog><button></button>
I have this code set with its css and javascript to show a dialog by clicking a button to select the site’s language.
When I duplicate this dialog to the site’s footer it doesnt work anymore and when clicking the dialog on the footer it does nothing but the first dialog still works.
I tried adding ids for the javascript code but I didn’t get anything working.
validate and transform a field value using ajv in nodejs
I want to validate and change field json_data.childOrder.Order.triggerPrice using ajv. But my customKeyword function is never called.
I want to update it to 10% of json_data.ltp
I tried to read the documentation but its not very clear how to do this. And moany examples on stackoverflow are referring to old version of ajv library.
const Ajv = require('ajv')
const ajv = new Ajv({ coerceTypes: true }) // options can be passed, e.g. {allErrors: true}
const OrderSchema = {
type: 'object',
properties: {
childOrder: {
type: 'object',
additionalProperties: true,
properties: {
Order: {
type: 'object',
additionalProperties: true,
properties: {
qty: {
type: 'string'
},
triggerPrice: {
type: 'number'
}
},
required: ['triggerPrice', 'qty']
}
}
}
},
additionalProperties: true
}
json_data = {
childOrder: {
Order: {
buy: 'true',
orderType: '3',
price: 3999,
qty: '10',
triggerPrice: 3400
}
},
duration: 'DAY',
ltp: 3435,
orderType: '3',
price: 0,
product: 'wood',
qty: '10',
}
ajv.addKeyword({
keyword: 'triggerPrice',
type: 'number',
compile: (a, b) => {
// logic to transaform trigger price
console.log(a, b)
}
})
const validateOrder = ajv.compile(OrderSchema)
const _validate = validateOrder(json_data)
are there any other alternate ways of doing validatin in nodejs like there are in python marshmallow and django DRF.
Mongo DB is failing to fetch data from the request in Next js
I have a POST request in my Nextjs app, file path is app/api/gigs/new. The request is supposed to check for data in the request body, take that data and add it to the mongo db schema, then save it to the database. When I try sending the request via thunderclient(a tool like postman), I get the following error:
“Data has not been saved successfully: ValidationError: GigTitle: Path GigTitle is required., GigDesc: Path GigDesc is required., BasicPrice: Path BasicPrice is required., StandardPrice: Path StandardPrice is required., BasicFeatures: Path BasicFeatures is required., StandardFeatures: Path StandardFeatures is required.“.
The kind of payload that I am sending through thunder client is like this:
{
“gigtitle”: “Gigger”,
“gigdesc”: “Desc”,
“basicprice”: “20”,
“basicfeatures”: “Unlimited revisions”,
“stdprice”: “50”,
“stdfeatures”: “three revisions”
}
Here is my route.js file through which I am trying to send the request:
import { connectToDB } from "../../../../lib/mongo.js";
import Gig from "../../../../lib/models/Gigs.model.js";
export const POST = async (req) => {
try {
await connectToDB();
const {
gigtitle,
gigdesc,
basicprice,
basicfeatures,
stdprice,
stdfeatures,
} = req.body;
const gig = await new Gig({
GigTitle: gigtitle,
GigDesc: gigdesc,
// GigTags: tags,
BasicPrice: basicprice,
BasicFeatures: basicfeatures,
StandardPrice: stdprice,
StandardFeatures: stdfeatures,
});
await gig.save();
return new Response("Data saved successfully", { status: 200 });
} catch (error) {
console.log(error);
return new Response(`Data has not been saved successfully: ${error}`, {
status: 500,
});
}
};
Here is the mongo db schema:
import mongoose from "mongoose";
const GigSchema = new mongoose.Schema(
{
GigTitle: {
type: String,
required: true,
},
GigDesc: {
type: String,
required: true,
},
GigTags: {
type: Array,
},
BasicPrice: {
type: Number,
required: true,
},
StandardPrice: {
type: Number,
required: true,
},
BasicFeatures: {
type: String,
required: true
},
StandardFeatures: {
type: String,
required: true
},
Sales: {
type: Number,
default: 1
}
},
{ timestamps: true }
);
const Gig = mongoose.models.Gig || mongoose.model("Gig", GigSchema);
export default Gig;
What am i doing wrong here? Please someone advice.
Error 500 when I called webservice with AJAX
I have web service solution in Visual Studio with one parameter :
Public Function CheckPalletInLocation(location As String) As String
Dim ScaleConnnection As New SqlClient.SqlConnection("MYCONNEXION")
Dim ScaleCommand As New SqlClient.SqlCommand
ScaleCommand.Connection = ScaleConnnection
ScaleConnnection.Open()
ScaleCommand.CommandText = "SELECT DISTINCT LOGISTICS_UNIT FROM LOCATION_INVENTORY WHERE LOCATION = '" &
location & "'"
Return ScaleCommand.ExecuteScalar()
ScaleConnnection.Close()
'Return "True"
End Function
When I launch solution, webservice works. It return value.
Now I want to call it in HTML page with ajax code :
<pre><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<HTML>
<HEAD>
<title>TEST WEB SERVICE</title>
<script type="text/javascript" src="jquery-3.4.1.js"></script>
</HEAD>
<BODY onload="Click_BB();">PAGE
<script>
function Click_BB()
{
$.ajax({
type: 'post',
url: 'https://localhost:44341/WebService1.asmx?op=CheckPalletInLocation',
contentType: "application/xml",
data: { location: '110-01-03-10' },
success: function (d)
{
alert(d);
},
failure: function (response)
{
debugger;
alert(response.d);
}
});
}
</script>
</BODY>
</HTML>
I always have this error in the response page :
<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"><soap:Body><soap:Fault><soap:Code><soap:Value>soap:Receiver</soap:Value></soap:Code><soap:Reason><soap:Text xml:lang="fr">System.Web.Services.Protocols.SoapException: Le serveur n'a pas pu traiter la demande. ---> System.Xml.XmlException: Données non valides au niveau racine. Ligne 1, position 1.
I transale : server cannot process. Invalid data root, line 1 position 1
Can someone help please ?
Thanks
I tried to change AJAX code, I would like to have the result of my web service in HTML page. Until now I have error 500
Is it possible to automatically get the main color of an element in css / javascript? [duplicate]
Can css or javascript pick automatically the main color of an image for example? like on spotify where the website /app automatically adapts to whatever is the color of the artwork of an album
As for now i’m using a var that I set individually in each html pages:
<style>:root {
--primary-color: #9dff00;</style>
and indeed then in my css:
color: var(--primary-color);
Javascript loop goes too fast and does not change the api call [closed]
I am executing in the google chrome console the following script:

the button click suppose to call an API, but in the API call, I see alwazs the some ID, insted of getting the other two:
I did similar code with a foreach, this time I am using a promise with timeout.
Not sure what to do to resolve this, looks like the foreach goes too fast before the changes are applied to the html and the click even is triggered 3 times with the first ID of the array and it suppose to to have 3 different calls.
Any suggestion?
Node Hapi.js bulk update to mariaDB
I’m looking for a way to do a bulk update on my MariaDB. I use the Node.js mariaDB plugin and HAPI.js with Handlebars. I’m very new at javascript but got already a far way on my little project to do some research on working dogs (Belgium Malinois). It’s for myself to learn working with Javascript, Node and MariaDB.
My issue:
I have a webpage with multiple parameters to edit through a form.
The database: aped_db.parameters
TABLE `parameters` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_general_ci',
`description` VARCHAR(50) NOT NULL COLLATE 'utf8mb4_general_ci',
`opt0` VARCHAR(50) NOT NULL DEFAULT 'Unknown' COLLATE 'utf8mb4_general_ci',
`opt1` VARCHAR(50) NOT NULL DEFAULT 'Very bad' COLLATE 'utf8mb4_general_ci',
`opt2` VARCHAR(50) NOT NULL DEFAULT 'Bad' COLLATE 'utf8mb4_general_ci',
`opt3` VARCHAR(50) NOT NULL DEFAULT 'Ok' COLLATE 'utf8mb4_general_ci',
`opt4` VARCHAR(50) NOT NULL DEFAULT 'Good' COLLATE 'utf8mb4_general_ci',
`opt5` VARCHAR(50) NOT NULL DEFAULT 'Very good' COLLATE 'utf8mb4_general_ci',
`multiplier` FLOAT NULL DEFAULT '1',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE INDEX `name` (`name`) USING BTREE
)
The HTML code in short
{{#each parlist}}
<input type="hidden" name="id" value="{{this.id}}" form="form-edit">
<td style="text-align:center;">{{this.id}}</td>
<td><input type="text" name="name" value="{{this.name}}" form="form-edit"></td>
<td><input type="text" name="description" value="{{this.description}}" form="form-edit"></td>
<td><input type="text" name="opt0" value="{{this.opt0}}" form="form-edit"></td>
<td><input type="text" name="opt0" value="{{this.opt1}}" form="form-edit"></td>
<td><input type="text" name="opt0" value="{{this.opt2}}" form="form-edit"></td>
<td><input type="text" name="opt0" value="{{this.opt3}}" form="form-edit"></td>
<td><input type="text" name="opt0" value="{{this.opt4}}" form="form-edit"></td>
<td><input type="text" name="opt0" value="{{this.opt5}}" form="form-edit"></td>
<td><input type="text" name="multiplier" value="{{this.multiplier}}" form="form-edit"></td>
{{/each}}
The received payload to process into the table parameters:
req.payload = {
id: [ '1', '3', '' ],
name: [ 'Social', 'Work ethic', 'Dominance' ],
description: [ 'Desc 1', 'Desc 2', 'Desc 3'],
opt0: [ 'Unknown', 'Unknown', 'Unknown' ],
opt1: [ 'Very bad', 'Very bad', 'Very bad' ],
opt2: [ 'Bad', 'Bad', 'Bad' ],
opt3: [ 'Ok', 'Ok', 'Ok' ],
opt4: [ 'Good', 'Good', 'Good' ],
opt5: [ 'Very good', 'Very good', 'Very good' ],
multiplier: [ '1', '1', '1' ]
}
In the above payload 2 parameters are existing ones, and the third one needs to be a new INSERT.
The issue I have is, that for each key there is an array. I would have expected an array for each row.
Parameters id ‘1’ & ‘3’ are existing ones to update, par id ” is a new one to insert.
Because the payload gives an array for each key, I’m not sure how to proceed. How to convert the payload to something more usable.
I tried looking on google, but didn’t find a good example that I could follow (that I understand). I’m very new at this.
Anyone can put me on the right track?
Thx
In html page onclick and console.log is not working
I created a button on my html page
So, In index.html:
<button class="btn btn-sm btn-remove delete-product" data-product="{{product_id}}"><i class="fas fa-trash-alt" ></i></button>
When I am clicking on this button it is not working In function.js:
$(".delete_product").on("click",function(){
let product_id=$(this).attr("data_product")
let this_val=$(this)
console.log("Product ID:", product_id);
}
and the html page is also linked with js file
So that’s it… What is wrong here???

