Category: javascript
Category Added in a WPeMatico Campaign
AngularJS days dropdown does not update when month dropdown changes
Hi guys need help on this. I am working on DOB validation in AngularJS. However I am facing an issue. Whenever I’m changing the month from the dropdown, the days dropdown won’t get updated on the first click of the dropdown. So technically, I have to select first a random number of the days dropdown, only then the number of days will get updated on the second click, depending on the selected month. Sharing this code snippet. Any advice? Thanks.
$(document).ready(function () {
$('#monthOfBirth').change(function () {
var e = document.getElementById('monthOfBirth');
var monthValue = e.options[e.selectedIndex].value;
var monthLength = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var setNumberOfDays = monthLength[monthValue - 1];
console.log(monthValue, setNumberOfDays);
function populateDays() {
const days = [];
for (let i = 1; i <= setNumberOfDays; i += 1) { //
if (i < 10) {
days.push({ value: `0${i}`, text: `0${i}` });
} else {
days.push({ value: i, text: i });
}
}
return days;
}
function populateMonths() {
const months = [];
for (let i = 1; i <= 12; i += 1) {
if (i < 10) {
months.push({ value: `0${i}`, text: `0${i}` });
} else {
months.push({ value: i, text: i });
}
}
return months;
}
function populateYears() {
const years = [];
for (let i = 1950; i <= new Date().getFullYear(); i += 1) {
years.push({ value: i, text: i });
}
return years;
}
$scope.dayOfBirth_items = populateDays();
$scope.monthOfBirth_items = populateMonths();
$scope.yearOfBirth_items = populateYears();
});
})
VS code formatter is nto working correctly
Visual studio code is adding a new line for every letter I write. I don’t understand why, I think that this is a formatting issue. You can take look at it in this video –
[https://drive.google.com/file/d/1qZCM00yIZ7cMtGZKm_20dMcopSBktOPi/view?usp=sharing][1]
Take look at my settings.json file –
"files.autoSave": "afterDelay",
"editor.minimap.enabled": false,
"files.autoSaveDelay": 100,
"editor.wordWrap": "wordWrapColumn",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"workbench.colorTheme": "One Monokai",
"explorer.confirmDragAndDrop": false,
"explorer.confirmDelete": false,
"security.workspace.trust.untrustedFiles": "open",
"liveServer.settings.donotShowInfoMsg": true,
"editor.formatOnSave": true,
"json.format.enable": false,
"prettier.useTabs": false,
"diffEditor.wordWrap": "on",
"window.openFilesInNewWindow": "on",
"prettier.arrowParens": "avoid",
"git.ignoreMissingGitWarning": true,
"liveServer.settings.CustomBrowser": "chrome",
"breadcrumbs.enabled": true,
"liveServer.settings.donotVerifyTags": false,
"editor.formatOnPaste": true,
"prettier.htmlWhitespaceSensitivity": "ignore",
"prettier.singleQuote": true,
"editor.autoIndent": "none",
"diffEditor.ignoreTrimWhitespace": false
I am trying to make Nested commands in my command_handler.js discord.js
I am trying to create Nested commands in discord.js to make my bot read subfolders in my command folder (discord.js) Everything is basically in the title
command_handler.js:
const fs = require('fs')
module.exports = (client, Discord) => {
const command_files = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'))
for (const file of command_files) {
const command = require(`../commands/${file}`);
if (command.name) {
client.commands.set(command.name, command);
} else {
continue;
}
}
}
Most of Index.js:
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});
const token = process.env['DISCORD_TOKEN']
const fs = require('fs');
client.commands = new Discord.Collection();
client.events = new Discord.Collection();
['command_handler', 'event_handler'].forEach(handler => {
require(`./handlers/${handler}`)(client, Discord);
})
// Command Handler
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`)
client.commands.set(command.name, command)
}
// client.login token
client.login(token)
Thanks in advance
How to set random image in IFTTT from Gify, if PostImageUrl is null
I am trying to append a random image from Giphy in IFTTT, if PostImageUrl
is null.
let myImageURL = WordPress.anyNewPostWp.PostImageUrl;
let noImageURL = `http://ifttt.com/images/no_image_card.png`;
let myGifImageURL = Giphy.historyOfRandomGifBasedOnKeyword[0].ImageURL;
let wpPostContent = WordPress.anyNewPostWp.PostContent;
let msg = '<img src= myGifImageURL>'+ '<br>' + wpPostContent ;
if (myImageURL == noImageURL) {
Blogger.createPostBlogger.setBody(msg);
//Blogger.createPostBlogger.skip(`Skipping post as No image URL present`);
}
By defaulti if PostImageUrl
is null, IFTTT automaticaly append http://ifttt.com/images/no_image_card.png
in place of PostImageUrl
.
I am trying to set Blogger Post body with existing post content + Random Giphy Image.
Pl suggest.
functional component to class component in react native
is it right or wrong please help
This is my functional component code
setaddCategories((prevState) => {
return [...prevState, { category_name: "", expense_categories_id: 0 }];
});
and here I turn it into class component
this.setState({
addCategories: (prevState) => {
return [...prevState, { category_name: "", expense_categories_id: 0 }];
},
});
how can i transfer the data from my browser console to my php code. I am using a javascript in the browser console
This is the code I am using for the browser console
<!DOCTYPE html>
<html lang="en">
<head>
<title>Firebase</title>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/7.19.1/firebase-database.js"></script>
<style type="text/css">
/* Set the size of the div element that contains the map */
#map {
height: 400px;
/* The height is 400 pixels */
width: 100%;
/* The width is the width of the web page */
}
</style>
</head>
<!-- <body>
<div id="root"></div>
</body> -->
This is to connect the browser console to firebase database
const firebaseConfig = {
apiKey: "AIzaSyD2SevZI0FJV4jew4Z-c9pl7CxntknqEQY",
authDomain: "thesisesp8266.firebaseapp.com",
databaseURL: "https://thesisesp8266-default-rtdb.firebaseio.com",
projectId: "thesisesp8266",
storageBucket: "thesisesp8266.appspot.com",
messagingSenderId: "316864477515",
appId: "1:316864477515:web:56b460e9ce1d3a088550ce",
measurementId: "G-F3SG81M2L6"
};
This is to print the data from database to browser console
firebase.initializeApp(firebaseConfig);
database = firebase.database();
var ref = database.ref('GPS');
ref.on('value', gotData, errData);
function gotData(data){
console.log(data.val());
var GPS = data.val();
var keys = Object.keys(GPS);
console.log(keys);
}
function errData(err){
console.log('Error!');
console.log(err);
}
</script>
</body>
</html>
Why do you need deep comparison?
reference: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/
Following to the reference, deep comparison is:
The deep equality is similar to the shallow equality, but with one difference. During the shallow check, if the compared properties are objects, a recursive shallow equality check is performed on these nested objects.
const objA = {
propA: 123
propB: 'a'
propObj1: { // assume reference: 1234
propObj1: 'abc'
}
}
const objB = {
propA: 123
propB: 'a'
propObj1: { // assume reference: 1234
propObj1: 'abc'
}
}
Is it possible for objA
and objB
to be equal in shallow comparison but not in deep comparison?
Because their propObj1
have the same reference, change to objA.propObj1
will be also reflected to objB.propObj1
which means they will also be equal in deep comparison. Can you give an example where it is true
in shallow comparison but false
in deep comparison?
How to record audio and video using JAVASCRIPT ? (REACT JS)
I have tried but there is a error “TypeError: Cannot read properties of undefined (reading ‘stop’)”
I am calling function on button click
here is function as well 🙂
const getAudio=()=>{
let device = navigator.mediaDevices.getUserMedia({audio: true});
let chunks = [];
let recorder;
device.then(stream => {
recorder = new MediaRecorder(stream);
recorder.ondataavailable = e => {
chunks.push(e.data);
if (recorder.state === 'inactive') {
this.blob = new Blob(chunks, {type: 'audio/webm'});
let testAudioRecord = URL.createObjectURL(this.blob);
console.log(testAudioRecord)
}
}
recorder.start(1000);
});
setTimeout(() => {
recorder.stop(); // Cannot read ('stop') =error
}, 2000)
}
Array searching and slicing
Given a string nums that contains only digits and an array of numbers predefinedNumbers, I have to add colons in nums to construct a new string, where each number between colons has to be a valid number from predefinedNumbers and return all possibilities
EX: nums = “143163421154143” predefinedNumbers = [“21154”, “143”, “21154143”, “1634”, “163421154”]
Output: [ “:143:1634:21154:143:”, “:143:163421154:143:”, “:143:1634:21154143:” ]
So far I tried this code but it’s not the result I need and I’m stuck trying to understand how to go over it recursively.
Any hint is very much appreciated.
let nums = "143163421154143";
predefinedNumbers = ["21154", "143", "21154143", "1634", "163421154"];
let newArray=[];
function makeNumSentences (nums, predefinedNumbers) {
predefinedNumbers.map(item => {
if (nums.includes(item)) {
newArray.push(item)
}
})
console.log(newArray.join(':'));
};
makeNumSentences("143163421154143",["21154", "143", "21154143", "1634", "163421154"])
Add QR on top of html Canvas
I’m trying to load a QR code into HTML5 canvas on top of a background image but it’s not working for whatever reason. If I change the QR code to a normal it works fine but this is no good for my purposes.
I’ve tried a million variations but here’s where I’m at right now:
setTimeout(function() {
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var qr = document.getElementById('qrcode');
var imageObj = new Image();
imageObj.onload = function(){
context.drawImage(imageObj, 10, 10);
context.font = "40pt Arial";
context.fillStyle = "red";
context.fillText("Hello")
context.drawImage(qr, 10, 10);
};
imageObj.src = "https://via.placeholder.com/350x150";
}, 300);
<script src="https://cdn.rawgit.com/davidshimjs/qrcodejs/gh-pages/qrcode.min.js"></script>
<script type="text/javascript">
new QRCode(document.getElementById("qrcode"), "TESTQR");
</script>
<div style="width:100px; height:100px" id="qrcode"></div>
<canvas id="myCanvas" width="350" height="150"
style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.
</canvas>
Any help would be appreciated.
can threeBox use post-progress like threejs WebGLRenderTarget,ShaderPass and EffectComposer?
I hope to see an example to learn how to implement.
My teacher hopes that I can use the three boxes to achieve some post-processing effects of custom shaders, which involve obtaining scene depth maps, etc.
Javascript/jQuery beforeunload and unload not firing
I have a page where I want my script to let the server know that the user went offline when the browser/tab/page is closed.
$(document).ready(function() {
// Inform the server that the user went online
setStatus('online');
// Inform the server that the user went offline
$(window).on('beforeunload', function() {
setStatus('offline');
});
// Inform the server that the user went offline
$(window).on('unload', function() {
setStatus('offline');
});
});
async function setStatus(status) {
let { data } = await axios.post('/status', { status: status });
}
The part where I have setStatus('online');
works but I can never seem to set the status to offline
when I close the page/tab/browser.
jQuery credit card input format
I want to use jQuery validation for credit card input fields. When I seach for it I saw most people made this happen with additional validation methods.
I tried adding this to my code :
<script src="http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js"></script>
or this code :
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
But I’m getting this error
Is this about a version problem, I use the jQuery 3.6 version and tried 1.7 and 1.9 versions for validation plugin.
Note: I’m sure that I use validation plugin after adding jQuery cdn. I can reach jQuery but not to jQuery.validator method.
Addition: I’m tring to format name-surname input field with only letters and spaces. If you can help me with that too, I would be glad.(Or is there a plugin prepared for every input field for credit card inputs.)
Looping through nested array of objects
I have following array of objects with nested arrays in it. I wanted to traverse through those arrays and extract all those impact information to separate array:
this is how my input data looks like:
{
"violations": [
{
"impact": "serious",
"nodes": [
{
"any": [
{
"impact": "critical"
},
{
"impact": "serious"
}
],
"all": [
{
"impact": "moderate"
}
],
"none": [
{
"impact": "minor"
}
]
}
]
},
{
"impact": "serious",
"nodes": [
{
"any": [
{
"impact": "serious"
},
{
"impact": "minor"
}
],
"all": [
{
"impact": "moderate"
}
],
"none": [
{
"impact": "serious"
}
]
}
]
},
{
"impact": "serious",
"nodes": [
{
"any": [
{
"impact": "critical"
},
{
"impact": "critical"
}
],
"all": [
{
"impact": "moderate"
}
],
"none": [
{
"impact": "moderate"
}
]
},
{
"any": [
{
"impact": "critical"
},
{
"impact": "critical"
}
],
"all": [
{
"impact": "moderate"
}
],
"none": [
{
"impact": "moderate"
}
]
}
]
}
]
}
expected output:
[
{
"impact": "serious"
},
{
"impact": "critical"
},
{
"impact": "serious"
},
{
"impact": "moderate"
},
{
"impact": "minor"
},
{
"impact": "serious"
},
{
"impact": "serious"
},
{
"impact": "minor"
},
......
]
I’m currently trying with forEach loop like below:
const results = [];
violations.forEach(({ nodes, impact }) => {
results.push({ impact });
// flattening nodes
nodes.forEach(({ any, all, none }) => {
any.forEach((v) => results.push(v));
all.forEach((v) => results.push(v));
none.forEach((v) => results.push(v));
});
});
is there any better and shorter way to do the same?