Hello everyone I am new in Django I am looking for solution to get a column (“names”) from a Django model to a JavaScript array so when I write console.log (T) it returns the list of the names any help please
NB : please give the solution Well detailed because I am a beginner (Django part : what should I do, and JavaScript part too)
Category: javascript
Category Added in a WPeMatico Campaign
ReactJS call function once if query strings set
Explain:
In useEffect I get products via getProducts() function based on given data and data contains search filters and will be update by user so need to watch it in realtime, for example data contains an object like this {brand: 'x'}
const [data, setData] = useState({});
useEffect(() => {
getProducts(data) // get products via api based on data, if data is clear, it will return all products
.then(data => {
//
});
}, [data]) // watch data in realtime and send it to getProducts()
useEffect(() => {
getQuery(); // check if there are search querys
}, [])
Also there is a getQuery() function, it will check if there are any query strings in search params when page is reload, and will get query strings and set it to data, and by above code if data get update it will call getProducts() again, actually it update products.
const getQuery = () => {
let obj_url = new URL(window.location.href);
let params = obj_url.searchParams;
let searchParams = new URLSearchParams(params);
// some other code
setData(obj); // get query and set it to data
}
Problem:
I noticed while there are query strings in url it will call getProducts() twice! well this code definitely does that, but I don’t want it, how can I prevent to call this twice? I just want if there are query strings call once, if not call once.
Javascript match string contains bracket
I have string which contains bracket, and I want to match it, I tried below code but does not work
Example
let testString = "My First Name is (Ahmed), and Last Name is (Ali)";
let result = testString.match("My First Name is (Ahmed)");
consol.log(result);
the result is null
Table performs a calculation only in the first row
I’ve build an interactive table where you can manually add and delete rows (with bootstrap). This all works fine!
Now comes the problem:
I have some input fields with an automatic calculation. But the problem is, the table only performs the calculation in the standard row, and not in the addable row.
This is the .HTML and .JS of the table:
jQuery(document).delegate('a.add-record_venr', 'click', function(e) {
e.preventDefault();
var content = jQuery('#sample_table_venr tr'),
size = jQuery('#tbl_posts_venr >tbody >tr').length + 1,
element = null,
element = content.clone();
element.attr('id', 'rec_venr-'+size);
element.find('.delete-record_venr').attr('data-id', size);
element.appendTo('#tbl_posts_body_venr');
element.find('.sn').html(size);
});
jQuery(document).delegate('a.delete-record_venr', 'click', function(e) {
e.preventDefault();
var didConfirm = confirm("Ventilatierooster verwijderen?");
if (didConfirm == true) {
var id = jQuery(this).attr('data-id');
var targetDiv = jQuery(this).attr('targetDiv');
jQuery('#rec_venr-' + id).remove();
//regnerate index number on table
$('#tbl_posts_body_venr tr').each(function(index) {
//alert(index);
$(this).find('span.sn').html(index+1);
});
return true;
} else {
return false;
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div class="wellclearfix">
<a class="btn btn-primary pull-right add-record_venr" data-added="0"><i class="glyphicon glyphicon-plus"></i> Toevoegen </a>
</div>
<div class="container-fluid" style="margin-left:1px ;">
<table class="table table-stripped" id="tbl_posts_venr">
<thead style="background-color:#c7c8cc; width: 100% !important;">
<tr>
<th style="width:30px ;">Merk</th>
<th >Lengte rooster</th>
<th >Type rooster</th>
<th >Capaciteit [dm3/s]</th>
<th >Max. capaciteit [dm3/s]</th>
<th >Verblijfsgebied</th>
<th >Verblijfsruimte</th>
<th >Verwijderen</th>
</tr>
</thead>
<tbody id="tbl_posts_body_venr">
<tr id="rec_venr-1">
<td><input class="inputtext" type="text" name="" placeholder="Merk"> </td>
<td><input class="inputtext" type="text" name="lrooster" id="lrooster" placeholder="Lengte rooster"></td>
<td><input class="inputtext" type="text" name="" placeholder="Type rooster"></td>
<td><input class="inputtext" type="text" name="caprooster" id="caprooster" placeholder="Capaciteit [dm3/s]"></td>
<td><input class="inputtext" type="text" name="maxcaprooster" id="maxcaprooster" placeholder="Max. capaciteit [dm3/s]"></td>
<td><input class="inputtext" type="text" name="" placeholder="Verblijfsgebied"></td>
<td><input class="inputtext" type="text" name="" placeholder="Verblijfsruimte"></td>
<td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</tbody>
</table>
</div>
<div style="display:none;">
<table id="sample_table_venr">
<tr id="">
<td><input class="inputtext" type="text" name="" placeholder="Merk"> </td>
<td><input class="inputtext" type="text" name="lrooster" id="lrooster" placeholder="Lengte rooster"></td>
<td><input class="inputtext" type="text" name="" placeholder="Type rooster"></td>
<td><input class="inputtext" type="text" name="caprooster" id="caprooster" placeholder="Capaciteit [dm3/s]"></td>
<td><input class="inputtext" type="text" name="maxcaprooster" id="maxcaprooster" placeholder="Max. capaciteit [dm3/s]"></td>
<td><input class="inputtext" type="text" name="" placeholder="Verblijfsgebied"></td>
<td><input class="inputtext" type="text" name="" placeholder="Verblijfsruimte"></td>
<td><a class="btn btn-xs delete-record" data-id="1"><i class="glyphicon glyphicon-trash"></i></a></td>
</tr>
</table>
</div>
</div>
</div>
</table>
This is the JavaScript of the calculation:
$('#lrooster, #caprooster').keyup(function(){
var lrooster = parseFloat($('#lrooster').val());
var caprooster = parseFloat($('#caprooster').val());
$('#maxcaprooster').val(lrooster * caprooster );
});
If the linked code doesnt work good, here ‘s a fiddle
thanks in advance!!
ReactJS – Passing data as props that I’ve just extracted from Child Component
So i have just used the saveSavingGoalHandler to extract some Data from a child
component < SavingsGoal />..
i have it saved in SaveGoalData and when i run the Console.log() i get the correct
string.
The issue is i now need to pass it down to the other component < TransactionFeed />.
When i do savingGoalId={SaveGoalData} i get “SaveGoalData” is undefined..
my first thought was to us let SaveGoalData = “” outside the component then have
SaveGoalData = SavingsGoalID in the function but i just get undefined as it would
run the empty string before it gets filled..
any ideas???
const saveSavingGoalHandler = (SavingsGoalID) => {
let SaveGoalData = SavingsGoalID;
console.log(SaveGoalData);
};
return (
<div className="App">
<GetAccountName />
<TransactionFeed
accountUID={AccountID}
defCategory={DefCategory}
savingGoalId={SaveGoalData} <--- Is Undefined
/>
<SavingsGoal
accountUID={AccountID}
defCategory={DefCategory}
onSaveSavingGoal={saveSavingGoalHandler}
/>
</div>
);
Works on desktop won’t in iOS
Works like I want on desktop or notebook. Displays single video and video player controls on mobile (I have only tried iPhone) You can find the game at https://bruceworkman.com/matt/matt.html
Any tips will be appreciated! I have tried adjusting css which can make things look better on a smaller screen, but the associated images don’t appear and there is no way to advance the game and play in normally. I am not an experienced enough programmer to figure this one out on my own.
Index html:
<!DOCTYPE html>
<head>
<title>PLAY PUNCH MATT</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: auto;
text-align: center;
font-family: verdana;
}
button {
width: 88px;
height: 88px;
background-color: #000;
color: #fff;
border: none;
border-radius: 50%;
font-size: 1.6em;
font-weight: bold;
}
.show {
display: block;
margin: auto;
}
.hide {
display: none;
}
</style>
</head>
<body>
<div id='home' class='show'>
<h1 style="display: block; margin: 128px 0px 128px 0px; font-size: 2.8em;">PUNCH MATT</h1>
<button onclick="startGame()">PLAY</button>
</div>
<div id='main' class='hide'>
<div style='margin: 32px;'>
<video id="my_video" class='show' src=""></video>
<img id="matt_after" class='hide' src="images/matt_after.jpg">
</div>
<div id='hand' class='hide'>
<img src="images/hand.png" onclick="doSlap()" >
</div>
<button onclick="endGame()" style="position: absolute; bottom: 16px; right: 16px;">END</button>
</div>
<script src="js/game.js"></script>
</body>
</html>
game.js
const clip_src = [
"videos/clip1.mp4",
"videos/clip2.mp4",
"videos/clip3.mp4",
"videos/clip4.mp4",
"videos/clip5.mp4",
"videos/clip6.mp4",
"videos/clip7.mp4",
"videos/clip8.mp4",
"videos/clip9.mp4",
"videos/clip10.mp4",
"videos/clip11.mp4",
"videos/clip12.mp4",
"videos/clip13.mp4",
"videos/clip14.mp4",
"videos/clip15.mp4",
];
let my_video, wow_fx, slap_fx, ow_fx;
let home, main, hand, matt_after;
let ID, curr;
function loadAssets() {
// game element
my_video = document.getElementById("my_video");
my_video.src = clip_src[curr];
my_video.oncanplaythrough = function () {
if (gameStarted) {
my_video.play();
hand.setAttribute("class", "show");
}
};
my_video.onpause = function () {
setTimeout(function () {
wow_fx.play();
}, 100);
};
wow_fx = loadAudio("audios/effects/wow.wav");
slap_fx = loadAudio("audios/effects/slap.wav");
ow_fx = loadAudio("audios/effects/ow.wav");
wow_fx.onended = function () {
hand.setAttribute("class", "hide");
ID = setTimeout(function () {
slap_fx.play();
}, 10);
};
slap_fx.onended = function () {
matt_after.setAttribute("class", "show");
my_video.setAttribute("class", "hide");
ID = setTimeout(function () {
ow_fx.play();
}, 10);
};
ow_fx.onended = function () {
ID = setTimeout(function () {
matt_after.setAttribute("class", "hide");
my_video.setAttribute("class", "show");
curr = getRand(0, clip_src.length);
my_video.src = clip_src[curr];
}, 3000);
};
initGame();
}
function initGame() {
home = document.getElementById("home");
main = document.getElementById("main");
hand = document.getElementById("hand");
matt_after = document.getElementById("matt_after");
is_audio = !1;
gameStarted = !1;
curr = getRand(0, clip_src.length);
my_video.src = clip_src[curr];
}
function loadAudio(src) {
let t = new Audio();
t.src = src;
t.oncanplaythrough = function () {
console.log("audio loaded");
};
return t;
}
function startGame() {
gameStarted = !0;
home.setAttribute("class", "hide");
main.setAttribute("class", "show");
matt_after.setAttribute("class", "hide");
hand.setAttribute("class", "show");
setTimeout(function () {
my_video.play();
}, 100);
}
function endGame() {
home.setAttribute("class", "show");
main.setAttribute("class", "hide");
clearTimeout(ID);
wow_fx.pause();
slap_fx.pause();
initGame();
}
function doSlap() {
my_video.pause();
}
function getRand(min, max) {
return Math.floor(Math.random() * (max - min) + min);
}
window.onload = function () {
loadAssets();
};
Cross domain worker url, how to make it work?
I have been trying to make cross domain worker url work, this might be a duplicate question but I couldn’t make any solution to work, here is what I am doing:
const url = new URL('./worker/a.worker.js', import.meta.url);
const workerBlob = new Blob([
'importScripts(' + JSON.stringify(url) + ')',
], { type: 'application/javascript' });
const blobUrl = window.URL.createObjectURL(workerBlob);
this.WasmVisionWorker = new Worker(blobUrl);
This is throwing error – *
Cannot use import statement outside a module at ….
Basically, in my worker I am importing different scripts using ES6 ‘import’
i.e.
import scan from '../scan.js';
I read here – ES modules in service workers
to use import statements, we have to provide – type: ‘module’ while creating new worker:
this.WasmVisionWorker = new Worker(blobUrl, {type: 'module');
With this, getting error – cannot use ‘importScripts()’ with modules, should be related to this:
const workerBlob = new Blob(['importScripts(' + JSON.stringify(url) + ')',
], { type: 'application/javascript' });
What am I doing wrong?
ERR_CONNECTION_REFUSED Ionic6 transbank-pos-sdk-web
I am trying to connect an Ionic6 project with a transbank machine, via USB cable, transbank brings a virtual agent (https://pos.digitalpartner.cl/#/) with which I can connect to the machine without problems (for tests), but when trying to connect using the sdk “https://www.npmjs.com/package/transbank-pos-sdk-web”, for my project in Ionic6 it gives me an error that I don’t know how solve, the machine is configured correctly (integrated pos ignition). The error is the following: https://i.stack.imgur.com/YLhNQ.png.
The code that I use is the same that is shown as an example in the aforementioned sdk: https://i.stack.imgur.com/cl7ql.png.
The port is the correct one and I made sure of that (it is the same one that I use for tests, through the aforementioned virtual agent, without problems). If anyone can help me thank you very much.
How to fix jump is not a function error (Kaboom.js)
I was triyng to create a small flappy bird clone but I’ve run in into this error which I can’t fix. Also I’m using Vs Code if that matters.
ERROR:
TypeError: player.jump is not a function
at Object.cb (https://68045eae-6558-4e68-bc51-31bc244469a3.id.repl.co/:151:12)
at handleEvents (https://kaboomjs.com/lib/0.5.0/kaboom.js:55:19852)
at https://kaboomjs.com/lib/0.5.0/kaboom.js:56:181
at frame (https://kaboomjs.com/lib/0.5.0/kaboom.js:55:3425)
JAVASCRIPT PART:
kaboom({
global: true,
fullscreen: true,
scale: 1,
debug: true,
clearColor: [0,0,0]
})
const MOVE_SPEED = 120
const JUMP_SPEED = 800
loadSprite('tubo_sinistra', 'https://i.imgur.com/YVW4m89.png')
loadSprite('tubo_punta_sinistra', 'https://i.imgur.com/JcvhMs4.png')
loadSprite('tubo_punta_destra', 'https://i.imgur.com/wHB9HzE.png')
loadSprite('tubo_destra', 'https://i.imgur.com/Drs3q84.png')
loadSprite('player', 'https://i.imgur.com/MOOR8tT.png')
scene("game", ({ level, score }) => {
layer(['bg', 'obj', 'ui'], 'obj')
const maps = [
[
' sd sd sd sd sd sd sd sd sd sd ',
' sd sd sd sd sd sd sd sd sd sd ',
' sd sd sd ',
' sd sd sd ',
' sd sd ',
' sd ',
' ',
' sd ',
' sd sd ',
' sd sd sd ',
' sd sd sd sd sd sd sd sd sd sd ',
' sd sd sd sd sd sd sd sd sd sd ',
],
]
const levelCfg = {
width: 48,
height: 48,
's': [sprite('tubo_sinistra'), solid(), 'wall',scale(4)],
'd': [sprite('tubo_destra'), solid(), 'wall', scale(4)],
}
addLevel(maps[level], levelCfg)
//add([sprite('bg'), layer('bg')])
const player = add([
sprite('player'),
scale(2.5),
pos(5, 190),
//body(),
{
// right by default
dir: vec2(1,0),
}
])
player.action(() => {
player.resolve()
})
player.collides('wall', () => {
destroy(player)
})
player.action(() => {
player.move(MOVE_SPEED,0)
})
keyPress('space', () => {
player.jump()
})
})
scene("lose", ({ score }) => {
add([text(score, 32), origin('center'), pos(width()/ 2, height() /2)])
})
start("game", { level: 0, score: 0})
HTML PART:
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Flappy Bird
</title>
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
</head>
<body>
<script src="https://kaboomjs.com/lib/0.5.0/kaboom.js"></script>
<script src="flappy_bird.js"></script>
</body>
</html>
Sorry for this but otherwise I wouldn’t be able to ask the question. ………………………………………………………………………………..
LeafletJS maps deleting on drag
Using LeafletJS and JavaScript………………………………….
I’m having an issue with my map. It’s getting removed when I drag my marker, is there a way to fix it?
function to drag marker and route
// marker and route dragging enable
marker.dragging.enable();
marker.on("dragend", (e) => {
console.log("Marker has been moved!!!");
var lat = e.target.getLatLng().lat;
var lng = e.target.getLatLng().lng;
var pair = {lat: lat, lng: lng};
markers.set(pair, marker);
routes = [];
const tempMarker = []
markers.forEach((v, index) => {
tempMarker.push(v.getLatLng())
})
console.log({tempMarker});
**for (let i in map._layers) {
if (map._layers[i]._path != undefined) {
map.removeControl(map._layers[i]);
try {
markers.removeLayer(map._layers[i]);
} catch (e) {
console.log(e);
}
}
}**
// loop markers and move polyline
tempMarker.forEach((v, index) => {
// const lt = marker.getLatLng();
console.log('loop', v);
if (tempMarker[index + 1]) {
const nPolyline = L.polyline(
[v, tempMarker[index + 1]], {
enableDraggableLines: true,
color: "black",
weight: 5,
opacity: 0.5,
smoothFactor: 1,
}
).addTo(map);
routes.push(nPolyline);
}
})
console.log({map, routes, markers})
});
// function to drag marker and route ends here
This area area below is where it makes my map remove. how can I fix this issue?
**
for (let i in map._layers) {
if (map._layers[i]._path != undefined) {
map.removeControl(map._layers[i]);
try {
markers.removeLayer(map._layers[i]);
} catch (e) {
console.log(e);
}
}
}
**
How to insert a value inside a shadow root? Selenium WebDriver NodeJS
How can i access this shadow root above and insert a value into “Pesquisar” placeholder?
Next.js An update to Image inside a test was not wrapped in act(…)
I created a basic NextJS app using create-next-app then added Jest for testing. However, I am getting the error “An update to Image inside a test was not wrapped in act(…)” in my Jest test. It seems to be something to do with the Image component of NextJS updating after render, but I’m not quite sure what’s the best way to test with it. I’ve included the Jest test and the problematic part of the component here:
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
Powered by{' '}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</main>
</div>
)
}
export default Home
import React from 'react'
import { render, act } from '@testing-library/react'
import { axe } from 'jest-axe'
import Home from '@/pages/index'
it('should demonstrate this matcher`s usage with react testing library', async () => {
const { container } = render(<Home/>)
const results = await axe(container)
expect(results).toHaveNoViolations()
})
The error message also points to code at node_modules/next/client/image.tsx:353:3 being problematic, and looking at the source, that part seems to be a useLayoutEffect hook in the Image component…
Why doesn’t my Tampermonkey script run on some particular websites
I made some scripts to automatically insert the username and password and press the Log in button for me when I visit websites. On some websites, it is as easy as
document.getElementById('username').value='myname'
document.getElementById('loginButton').click()
And when I visit the website, all those actions will be done instantly. However, on some websites, such as https://login.payoneer.com/, the script doesn’t run at all. When I paste the script into the console, it works fine; however, it doesn’t automatically run when the page loads. Can someone suggest a way to make the script work? This is my script:
// ==UserScript==
// @name payoneer
// @namespace http://tampermonkey.net/
// @version 0.1
// @description try to take over the world!
// @author You
// @match https://login.payoneer.com/*
// @icon https://www.google.com/s2/favicons?sz=64&domain=payoneer.com
// @grant none
// @run-at document-start
// ==/UserScript==
(function() {
window.onload = function (){
function replaceValue(selector, value) {
const el = document.querySelector(selector);
if (el) {
el.focus();
el.select();
if (!document.execCommand('insertText', false, value)) {
// Fallback for Firefox: just replace the value
el.value = 'new text';
}
el.dispatchEvent(new Event('change', {bubbles: true})); // usually not needed
}
return el;
}
replaceValue('#username',"[email protected]");
document.getElementsByClassName('text-box__input')[1].setAttribute("id","passworde");
replaceValue('#passworde',"MyPASsword123!")
}
'use strict';
// Your code here...
})();
Creating a custom selection using selection.addRange() at runtime giving unintended results
I am encountering an issue in my application which runs on internet explorer where a delete key action is resulting in selecting the parent element of a zero-width space character instead of the zero-width element itself.
To elaborate on what is going wrong,
The span element which contains the zero width space looks like below:
<span class="buffer start">'u200b'</span>
Now when a delete key action is pressed around this element and when I try to get the selection using window.getSelection at this point, ideally, it was supposed to give me only the text node within the parent span element which is nothing but the zero-width space. Since IE is behaving strangely in some cases giving the entire span element, I tried coming up with a logic as seen below:
var selection = window.getSelection();
if(selection.focusNode && selection.focusNode.nodeName === 'SPAN' && selection.focusNode.children.length === 0 && selection.focusNode.firstChild.textContent === 'u200b')
{
var childNode = selection.focusNode.firstChild;
selection.removeAllRanges();
var range = document.createRange();
range.selectNodeContents(childNode);
selection.addRange(range);
}
Now this is correctly updating the selection variable with the intended result but when I am trying to access the selection.offsetAnchor, it is returning a value of 1, which means that the selection is not ending with the first character. This is again messing up further code flow since ideally it should have returned an offsetAnchor of 0.
I can’t seem to understand why there’s a difference in the offsetAnchor when I am setting the custom Selection when IE is not giving me the right selection. Does anyone have an idea what could be going wrong here?
Thanks in Advance!

