I want to implement “save as mhtml” flag of chrome to simply download mhtml of a webpage on button click. Please help me.
Category: javascript
Category Added in a WPeMatico Campaign
Given an array of positive integers arr, return the sum of all possible odd-length subarrays of arr (javascript)
Im lost, don’t know what to do, I tried doing a nested loop and incrementing j (nested inside i) by a value of 2, starting from j=1, and then i=0 i++, so my idea was to slice the array first one item at a time, the 3 elemetes (so all the elements from index 0 to index 2, then from 1 to 3, then 2 to 4) but dont know how. This is a problem from the let code web page, and the hint said “You can brute force – try every (i,j) pair, and if the length is odd, go through and add the sum to the answer.”
Using the DOM to get variables to run in an external javascript file
I have a javascript file that is used in multiple different html documents, and I need to run a function on all the javascript files using variables contained in the html tag. For example, this would be my javascript files glob.js
(function () {
runOnVariables(variablesFromHTML);
}();
function runOnVariables(myVariable){
//here I would write the code I need to run on the variables
}
Then, I have an html file with
<!DOCTYPE html>
<html lang="en">
<head>
<title>Sample File</title>
<script src="glob.js" async>
</head>
<body>
<script type="text/javascript">
var myVariable = "sample variable";
</script>
</body>
</html>
I cannot edit the html file and want to be able to use the external script to get access to the variables and run the function on those variables. Is there a way to do this using the DOM?
I tried editing the script tag in the external javascript file using the DOM, but it doesn’t run after its edited using the script, so it doesn’t work. (see code below):
var test = document.getElementsByTagName('script');
var indList = [];
for(var i=0; i<test.length; i++){
if(test[i]["textContent"].includes("myVariable")){
indList.push(i);
}
}
for(var k=0; k<indList.length; k++){
let text = test[indList[k]]["textContent"];
test[indList[k]]["textContent"] = text.replace(/myVariable(d))/g, '$&nrunOnVariables($&)');
//I know this regex might be wrong, but it
//works with the actual code that I can't share here;
//the regex is not important for this question
console.log(test[indList[k]]["textContent"]);
}
I’m hoping I can somehow access the variables in the external script so I don’t need to “edit” the html file, even dynamically. Is there a way to use these variables within the external script without editing the html file?
Typescript: More efficient ways to assign properties to an Interface?
I assign the properties of an interface CountersData as seen below. I use a flattenObject to extract the most nested key and value data from responseDeploymentData (as detailed One liner to flatten nested object)
This was is a clunky, so is there a more efficient/simplistic way to do this? See code below:
interface CountersData {
count_targets?: number;
count_targets_excluded?: number;
count_targets_pending?: number;
count_targets_in_progress?: number;
count_targets_completed?: number;
count_targets_failed?: number;
}
// later in code
let targetData: any = flattenObject(responseDeploymentData);
countersData.count_targets = targetData.count_targets;
countersData.count_targets_excluded = targetData.count_targets_excluded;
countersData.count_targets_pending = targetData.count_targets_pending;
countersData.count_targets_in_progress = targetData.count_targets_in_progress;
countersData.count_targets_completed = targetData.count_targets_completed;
countersData.count_targets_failed = targetData.count_targets_failed;
After appending new radio input to dropdown menu, the new radio button is stuck checked
I have a dynamic table that allows a user to view details on images they’ve uploaded. This includes the ability to either create a new album (and move upload to that album) or move an upload to another album they’ve previously created.
I’ve done this using radio buttons inside a dropdown menu with a text box where each time a new album is created, a corresponding label and input element is appended to the dropdown list.
The issue is that when a freshly created album is appended, only the first upload move is possible. After that, the message shows that upload is already in said album (when it’s not).
Here is the order of events:
- Create new album. Upload is moved to new album.
- Label and input elements for the new album are appended to the dropdown radio list.
- Attempt to move another upload to this new album fails. Alert displays: Upload is already in album.
<script>
$(document).ready(function() {
var csrfName = "<?= csrf_token(); ?>";
var csrfHash = "<?= csrf_hash(); ?>";
$(document).on('change', 'input[name=album_radio]', function() {
var album = $('.album-radio:checked').val();
var viewkey = $(this).data("viewkey");
$.ajax({
type: "POST",
url: "<?= base_url(); ?>/users/members/manage_uploads",
dataType: "JSON",
data: {
[csrfName]: csrfHash,
"album_name": album,
"viewkey": viewkey,
},
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
success: function(data) {
var res = data;
// Update CSRF hash
csrfName = res.csrfName;
csrfHash = res.csrfHash;
// display album name in table
$('#'+viewkey).html(res.album_name);
// Add new album name
alert(res.message);
}
});
});
$(document).on('click', '.new-album-button', function() {
var viewkey = $(this).data("viewkey");
var newAlbum = $('#text'+viewkey).val();
$.ajax({
type: "POST",
url: "<?= base_url(); ?>/users/members/manage_uploads",
dataType: "JSON",
data: {
[csrfName]: csrfHash,
"album_name": newAlbum,
"viewkey": viewkey,
},
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
success: function(data) {
var res = data;
// Update CSRF hash
csrfName = res.csrfName;
csrfHash = res.csrfHash;
// display new album name in table
$('#'+viewkey).html(res.album_name);
// display new album name in dropdown
var label, input, span;
label = document.createElement('label');
input = document.createElement('input');
span = document.createElement('span');
label.setAttribute('class', 'album-select');
label.setAttribute('id', 'radio'+res.album_name);
input.setAttribute('type', 'radio');
input.setAttribute('name', 'album_radio');
input.setAttribute('class', 'album-radio');
input.setAttribute('value', res.album_name);
input.setAttribute('data-viewkey', viewkey);
input.setAttribute('checked', 'checked');
span.setAttribute('class', 'checkmark');
label.appendChild(input);
label.appendChild(span);
label.innerHTML += res.album_name+' <i class="fa-solid fa-xmark "></i>';
$('.new-album-select').after(label);
input.removeAttribute('checked');
alert(res.message);
}
});
});
$('.fa-xmark').on('click', function() {
var matches = document.querySelectorAll('[id^=radio]');
});
});
</script>
And here is my html:
<td class='upload-album'>
<div class='album-dropdown'>
<span id ='<?= esc($row->viewkey); ?>'>
<?= esc($row->album_name); ?>
</span>
<div class='album-dropbtn' title='Move to Album'>
<i class="fa-solid fa-square-caret-down" ></i>
</div>
<div class='album-dropdown-content'>
<label class='album-select new-album-select'>New Album
<input type='radio' name='new_album_radio' value='' class='new-album-radio' data-viewkey='<?= $row->viewkey; ?>'/>
<span class='checkmark'></span>
<input type='text' name='new_album' id='text<?= esc($row-> viewkey); ?>' class='new-album-text'/>
<button class='new-album-button' data-viewkey=<?= esc($row->viewkey);?>>Create</button>
</label>
<?php if (! empty($albums)) {
foreach ($albums as $album) { ?>
<label class='album-select'><?= esc($album->album_name); ?>
<i class="fa-solid fa-xmark"></i>
<input type='radio' name='album_radio' value='<?= $album->album_name; ?>' class='album-radio' data-viewkey='<?= $row->viewkey; ?>'/>
<span class='checkmark'></span>
</label>
<?php }} ?>
</div>
</div>
</td>
Javascript stops working when a link is clicked
I have been trying to create a facebook clone app using rails 7. I have used javascript to render some fronted features. At first nothing seems amiss but when I click on a link on the page to redirect to some other view the javascript stops working. I believe that this might be due to the script being loaded before the DOM. What seemed to work was to reload the page and then everything worked as expected. I thus tried using window.location.reload() command in javascript which worked but then as I added more links the task became too tedious and also if I wished to redirect to another page the function redirected me to the same page. So is there a way to implement all the javascript features effectively without having to reload the page.
app/javascript/application.js
// Configure your import map in config/importmap.rb. Read more: https://github.com/rails/importmap-rails
import "@hotwired/turbo-rails"
import "controllers"
function home(){
let link = document.querySelector(".title-container")
if (link!=null){
link.addEventListener("click", function(){
var location = window.location.origin
window.location.assign(location)
// console.log(window.location)
window.localStorage.setItem("activeBtn", "#index")
// window.location.reload()
})
}
// let begin_session = document.querySelector(".actions")
// console.log(begin_session)
// if (begin_session != null)
// {
// begin_session.addEventListener("click", function(){
// // var location = window.location.origin + "/"
// window.location.assign(location)
// console.log(location)
// window.localStorage.setItem("activeBtn", "#index")
// // window.location.reload()
// })
// }
// console.log(window.location)
}
function refresh(){
let links = document.querySelector("a")
console.log(links)
for(let i=0; i<links.length ; i++ )
{
links[i].addEventListener("click", function(){
console.log(this)
window.location.reload()
})
}
}
function PageTransition(){
const sectBtns = document.querySelectorAll(".page-control")
// console.log(sectBtns)
let flag = true
var activeBtn = localStorage.getItem("activeBtn")
// console.log(document.querySelector(activeBtn))
if (document.querySelector(activeBtn) != null){
document.querySelector(activeBtn).className += " active"
}
for (let i=0; i<sectBtns.length; i++){
if (sectBtns[i].className.includes("active")){
flag = false
break
}
}
if (flag)
{
if (document.querySelector("#home") != null)
document.querySelector("#home").className += " active"
}
for (let i = 0; i < sectBtns.length; i++){
sectBtns[i].addEventListener("click", function(){
// console.log(this)
let currentBtn = document.querySelectorAll(".active");
// currentBtn[0].className = currentBtn[0].className.replace("active", "")
// this.className += " active"
var id = "#"+this.id
localStorage.setItem("activeBtn", id)
console.log(localStorage.getItem("activeBtn"))
console.log(window.location)
var location = window.location.origin + localStorage.getItem("activeBtn").replace("#","/")
window.location.assign(location)
// refresh()
})
}
}
function profileMenu(){
const profileBtn = document.querySelector(".profile")
const posts = document.querySelector(".posts")
// const navbar = document.querySelector(".navbar")
const menu = document.querySelector(".profile-menu")
if (profileBtn!= null){
profileBtn.addEventListener("click", function(){
if (menu.style.display === "none"){
menu.style.display = "block";
}else{
menu.style.display = "none"
}
})
if (posts != null){
posts.addEventListener("click", function(){
if (menu.style.display === "block")
menu.style.display = "none"
})
}
}
}
// function like(){
// const btn = document.querySelectorAll(".like-btn")
// for (let i=0; i< btn.length; i++){
// let current_btn = btn[i]
// current_btn.addEventListener("click", function(){
// if (current_btn.className.includes("liked"))
// current_btn.className = current_btn.className.replace("liked", "")
// else
// current_btn.className += " liked"
// })
// }
// }
function new_post(){
const bar = document.querySelector(".post-creator")
if (bar != null){
const poster = document.querySelector(".new-post")
const homepage = document.querySelector(".homepage")
const body = document.querySelector("body")
const close = document.querySelector(".close")
bar.addEventListener("click", function(){
if (poster.style.display === "none"){
poster.style.display = "block"
console.log(poster.style.display)
homepage.style.opacity = "0.5"
poster.style.opacity = "1"
var btn = document.querySelector('.submit')
console.log(btn)
btn.addEventListener("click", function(){
window.location.reload()
})
}
else{
poster.style.display = "none"
homepage.style.opacity = "1"
}
})
// homepage.addEventListener("click", function(){
// if (poster.style.display === "block")
// poster.style.display = "none"
// })
close.addEventListener("click", function(){
if (poster.style.display === "block"){
poster.style.display = "none"
homepage.style.opacity = "1"
window.location.reload()
}
})
}
}
switch (document.readyState){
case "interactive":
PageTransition()
profileMenu()
// like()
new_post()
home()
// refresh()
console.log("hi")
break;
}
Cannot read property ‘name’ of undefined in a request
Why might req.user be undefined ? How do I figure that out??
app.get("/", (req, res) => {
// home page
res.render("index.ejs", { name: req.user.name });
});
I use passport with a database to login. When I login, I redirect to this index.ejs which simply prints “Hi name” and the error is shown.
Password is used like so:
const passport = require("passport");
const initializePassport = require("./passport-config");
initializePassport(
passport,
(email) => {
const DataBase = require("./db");
const db = new DataBase();
try {
let userFound = db.findUserByEmail(email);
db.close();
return userFound;
} catch (e) {
console.log(`Error while logging in: ${e}`);
db.close();
return null;
}
}
);
app.use(passport.initialize());
app.use(passport.session());
app.post(
"/login",
passport.authenticate("local", {
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true,
})
);
Passport is configured like so:
const LocalStrategy = require("passport-local").Strategy;
function initialize(passport) {
const authenticateUser = async (email, password, done) => {
try {
const DataBase = require("./db");
const db = new DataBase();
const user = await db.findUserByEmail(email);
db.close();
if (user == null) {
return done(user, false, {
message: "No email",
});
}
try {
if (await bcrypt.compare(password,user.password)) {
return done(null, user);
} else {
return done(null, false, { message: "Pass error" });
}
} catch (e) {
return done(e);
}
} catch (e) {
console.log(`Error: ${e}`);
done(e, false);
}
};
passport.use(
new LocalStrategy({ usernameField: "email" }, authenticateUser)
);
passport.serializeUser((user, done) => done(null, user.ID));
passport.deserializeUser(
(id, done) =>
async function () {
const DataBase = require("./db");
const db = new DataBase();
const user = await db.findUserById(id);
db.close();
return done(null, user.firstName);
}
);
}
./db file, DataBase class useful methods (findUserByID() is the same except instead of email there’s ID):
findUserByEmail(email) {
return new Promise((resolve, reject) => {
const sql = `SELECT * FROM Users WHERE email = ?`;
db.get(sql, [email], (err, row) => {
if (err) return reject("Error: " + err.message);
resolve(row);
});
});
}
Synchronous POST array items with axios
in VueJs I have an array of objects (dynamic number of items) that I need to POST to an REST endpoint ensuring that order of array is respected also on ‘arrival’ on backend.
Iterating arrays with a forEach items calling an axios post leads in unpredictable order on BE due the async operations.
What is the best practice to send each item, wait the response and then send the next.
I also created an array of promise but I don’t really understand how to chain each other…
Any help appreciated.
Thanks in advance
express js routing and Phusion Passenger: internal server errors
I am new to express/node and apologize in advance for my inexperience/ignorance. I have written an express app that runs perfectly on my local system. Our hosting service uses Phusion Passenger and my app is having all sorts of routing issues now. At first I got the “Cannot GET” URL problem, but research allowed me to figure out what might be the problem with the routing.
After adding my app name, ‘scoreapp,’ to the route, I can get to the home page, but all other routes fail and also the code cannot find the css files. It does, however, find the views and other supporting files. Seems it is just the routes that are at issue. I have tried multiple solutions… taking the appname out of the router in app.js and putting it in the individual routes… Nothing seems to work.
The app fails with an internal server error, doesn’t write in the log. Just dies. I am at a loss as to how to even try to troubleshoot. Any assistance is welcomed or even documentation that uses more than the very simplest case of having all routes in app.js.
All of the documentation I can find uses only app.js, but my code uses routers.
The following is an excerpt from the structure of my app:
/bin
/node_modules
/public
/routes (express routes)
/auth.js
/competition.js
/competitors.js
...
/services (access the mysql db)
/auth.js
/common.js
/competition.js
...
/views (all the html code as ejs files)
/auth-login.ejs
...
/competition-mainPage.ejs
...
/competitors-manage.ejs
...
app.js
config.js (db pooling and access)
package.json
package-lock.json
README.md
The following code, from my app.js, shows the addition of the app name to the route path:
//excerpt from app.js
...
var indexRouter = require('./routes/index');
var judgesRouter = require('./routes/judges');
var divisionsRouter = require('./routes/divisions');
var competitorsRouter = require('./routes/competitors');
var entriesRouter = require('./routes/entries');
var competitionRouter = require('./routes/competition');
var scoresRouter = require('./routes/scores');
var authRouter = require('./routes/auth');
var messageRouter = require('./routes/message');
...
app.use('/scoreapp', indexRouter);
app.use('/scoreapp/auth', authRouter);
app.use('/scoreapp/judges', judgesRouter);
app.use('/scoreapp/divisions', divisionsRouter);
app.use('/scoreapp/competitors', competitorsRouter);
app.use('/scoreapp/entries', entriesRouter);
app.use('/scoreapp/competition', competitionRouter);
app.use('/scoreapp/scores', scoresRouter);
app.use('/scoreapp/message', messageRouter);
...
Access to the root of my app (/scoreapp) works fine. It finds the route in index.js, but it cannot find any other route. The following is the /routes/index.js file:
//index.js
const express = require('express');
const router = express.Router();
const common = require('../services/common');
//* display login page //
router.get('/', function(req, res, next){
//check login status
//if (!common.checkSession(req.cookies)) {
// res.redirect('/scoreapp/auth/login');
//}
res.render('competition-mainPage', {title: 'KMP Competitions'});
return;
})
module.exports = router;
At the moment I have commented out the redirect to the login page, as the app cannot find it on my hosting server. However, it finds the view, ‘competition-mainPage’, just fine.
The following is an excerpt from auth.js, where it should find /auth/login:
//excerpt from auth.js
const express = require('express');
const router = express.Router();
const { check, validationResult } = require('express-validator');
const common = require('../services/common');
const auth = require('../services/auth');
//display login page
router.get('/login', async function(req, res, next){
try{
res.render('auth-login', {title: 'Login'});
} catch(err) {
console.error(`Error while displaying login screen`, err.message);
next(err);
}
})
router.get('/logout', async function(req, res, next){
try{
res.render('auth-logout', {title: 'Logout'});
} catch(err) {
console.error(`Error while displaying logout screen `, err.message);
next(err);
}
})
...
Handle Data Selection in multiple tables
So, I am building a web application using Vue and element plus tables. In it the user can upload multiple tables select data (handled by @selection-change) and create graph of that data (using v-network-graph).
<el-table v-for="(tab,index) in r" :data="tab" :key="index" border style="width: 100%" height="500" @selection-change="handleSelectionChange" @header-click="contextmenu">
<el-table-column type="selection" width="55"/>
<el-table-column fixed align="center" v-for="col in x[index]" :prop="col.field" :label="col.field" :key="col.field">
<template #header="scope" >
<el-menu
:default-active="activeIndex"
class="el-menu-demo"
mode="horizontal"
@select="handleSelect">
<el-sub-menu index="1">
<template #title>{{col.field}}</template>
<el-menu-item index="Source" @click="handleSource(scope.column.property)">Source</el-menu-item>
<el-menu-item index="Target" @click="handleTarget(scope.column.property)">Target</el-menu-item>
<el-menu-item index="Using" @click="handleUsing(scope.column.property)">Using</el-menu-item>
<el-sub-menu index="Property">
<template #title>Property</template>
<el-menu-item index="Property_target" @click="handlePropertyTarget(scope.column.property)">Target</el-menu-item>
<el-menu-item index="Property_target" @click="handlePropertySource(scope.column.property)">Source</el-menu-item>
</el-sub-menu>
</el-sub-menu>
</el-menu>
</template>
</el-table-column>
<el-table-column>
<template #header>
<el-input v-model="searchQuery" size="small" placeholder="Type to search" />
</template>
<template #default="scope">
<el-button size="small" type="danger" @click="handleDelete(scope.$index,index)">Delete</el-button>
<!--<el-button type="primary" @click="handleEditRow(scope.$index)">Edit</el-button>-->
</template>
</el-table-column>
</el-table>
I am stuck on how I can handle the selection of data in these tables.
To be specific, when a user selects a row element plus tables have an event which adds that selected row to an array
selected row
array made by element plus table
Now when I select a row in another table
row selected in another table
new array made by element plus
Now since element plus makes different arrays for different table, I thought of pushing the data selected into a different array, which can store the data selected from both tables Array that stores combined data.
handleSelectionChange(val){ //WHAT LOGIC CAN I USE
console.log(val)
for(let i=0;i<val.length;i++){
if (Object.values(this.selected_data).includes(val[i])==false){
this.selected_data[Object.keys(this.selected_data).length] = val[i]
}
}
console.log(this.selected_data)
}
Now when I remove a selected row from a table the element plus array removes it from the array that it creates, but how can I remove it from the array that I created so that when a user removes a row and creates the graph again that removed row shouldn’t come up in the graph.
Row unselected
array updated by element plus and my array
I have been stuck on this problem for a few days. I’ll be grateful if anyone can give me a hint of the logic I should use or if someone has experience in this can let me know how I can tackle this problem.
Removing Sign in object of object in Javascript
I will take a response from mongodb and i just to manipulate some information init
and return as an response
I just want to remove Skating object {} sign and return it without manipulate data in Skating object
So anyone can please help me how can I do this stuff ..
Thanks in Advance
{
"_id": "62c6fff00031fd54e7ba10c7",
"name": "dsikljf",
"email": "[email protected]",
"Phone": 6458694,
"address": "kljk",
"height": "12",
"weight": "23",
"game": "Skating",
"bloodgroup": "A",
"payment": "unpaid",
"Password": "$2a$12$VOTCt5cZ4BfA6psXVlEW/OXD0flCXw4YfACe2M7CViRm2eMTtML.C",
"image": "18b9d104-520d-4673-be53-a40746e2623b-1657208816428.jpg",
"DOB": "2022-07-13",
"position": "technical_ability",
"Skating": {
"technical_ability": [
{
"STARTING": 1,
"TURNING": 1,
"CROSSING_LEGS": 1,
"LAP_OVERLAPPING": 1,
"BENDING": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d0"
}
],
"physical_awarness": [
{
"ENDURANCE": 1,
"SPEED": 1,
"AGILITY": 1,
"STRENGTH": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d1"
}
],
"personality_trait": [
{
"DRIVE": 1,
"AGGRESIVENESS": 1,
"DETERMINATION": 1,
"RESPONSIBILITY": 1,
"LEADERSHIP": 1,
"SELF_CONFIDENCE": 1,
"MENTAL_TOUGHNESS": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d2"
}
],
"tactical_awarness": [
{
"IN_OFFENSE": 1,
"IN_DEFENCE": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d3"
}
]
},
"Tokens": [],
"__v": 0
}
I Want to remove Skating Object sign …
{
"_id": "62c6fff00031fd54e7ba10c7",
"name": "dsikljf",
"email": "[email protected]",
"Phone": 6458694,
"address": "kljk",
"height": "12",
"weight": "23",
"game": "Skating",
"bloodgroup": "A",
"payment": "unpaid",
"Password": "$2a$12$VOTCt5cZ4BfA6psXVlEW/OXD0flCXw4YfACe2M7CViRm2eMTtML.C",
"image": "18b9d104-520d-4673-be53-a40746e2623b-1657208816428.jpg",
"DOB": "2022-07-13",
"position": "technical_ability",
"technical_ability": [
{
"STARTING": 1,
"TURNING": 1,
"CROSSING_LEGS": 1,
"LAP_OVERLAPPING": 1,
"BENDING": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d0"
}
],
"physical_awarness": [
{
"ENDURANCE": 1,
"SPEED": 1,
"AGILITY": 1,
"STRENGTH": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d1"
}
],
"personality_trait": [
{
"DRIVE": 1,
"AGGRESIVENESS": 1,
"DETERMINATION": 1,
"RESPONSIBILITY": 1,
"LEADERSHIP": 1,
"SELF_CONFIDENCE": 1,
"MENTAL_TOUGHNESS": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d2"
}
],
"tactical_awarness": [
{
"IN_OFFENSE": 1,
"IN_DEFENCE": 1,
"date": "7/7/2022",
"_id": "62c6fff00031fd54e7ba10d3"
}
]
,
"Tokens": [],
"__v": 0
}
LIKE THIS
issues with calling a function on el-pagination
using element ui component el-pagination i am trying to add the code to detect the enter and space for the pagination
but here
addKeyEvent() {
document.querySelectorAll('ul.el-pager li.number').forEach((element, index) => {
element.addEventListener('keyup', function (e) {
if (e.key == 'Enter' || e.key == 'Space') {
console.log(e.key);
console.log(element.innerHTML);
console.log(this.$parent);
this.$parent.handleCurrentChange(element.innerHTML);
}
})
});
}
i am unable to call the method, if i just console this, all i i get is the li element on which the pagination is linked. how can i call the method to pass pagination and make it work
also i am calling this function on the watch which this.addKeyEvent();
What is true about polymorphism? *
I have this question on a test, but I don’t know the answer 🙁
What is true about polymorphism?
1 – it is a class whose operations can also be applied to values of some other class
2 – it is the provision of multiple interfaces to entities of different types
3 – it is the packing of data and functions into a single component
4 – it is a mechanism for code reuse and to allow independent extensions of the original software via public classes and interfaces
React Typescript – Working with multiple checkboxes in a list
I have a usecase where I need to work with multiple checkboxes in a list
Only one check box can be selected at a time
Eg. If I toogle on Checkbox 1 and then click on Checkbox 2 – then I need to toogle off Checkbox 1 as I toogle on Checkbox 2
Below is my code
const ProductList = (props: InterdentalBrushProps) => {
const [isChecked, setIsChecked] = useState(false);
const { onEmit, brush_size, color_name, color_hex } = props;
const handleClick = () => {
setIsChecked(current => !current);
onEmit({
isChecked,
onEmit,
});
};
useEffect(() => {
console.log('isChecked is: ', isChecked);
}, [isChecked]);
return (
<List component="div" disablePadding>
<ListItemButton className="product-outline" onClick={handleClick}>
<CircleIcon sx={{ color: color_hex }} />
<ListItemText sx={{ ml: 2 }} primary={brush_size} />
<ListItemText sx={{ ml: -15 }} primary={color_name} />
<Checkbox
icon={<CircleIcon sx={{ color: '#ffffff' }} />}
checkedIcon={<CheckCircleIcon />}
checked={isChecked}
color="primary"
onChange={e => setIsChecked(e.target.checked)}
/>
</ListItemButton>
</List>
);
};
export default ProductList;
Please help me fix this
Thank you
How to sort documents by a subdocument field in mongoose
I have seen quite a number of solutions here, but none of them seems to be working for me.
I am populating a orderModel with the user, which is just another model (userModel), Now I want to sort the orderModel based on a property from the userModel. To be specific rankAmount. rankAmount is just a property in user that is a number type
This is what I have tried based on what I know and what I have seen here
let orders: any = await OrderModel.find({...query})
.populate({path:"user",options:{sort:{'user.rankAmount': "desc"}}})
let orders: any = await OrderModel.find({...query})
.populate("user")
.sort({"user.rankAmount":"desc"})
orderModel.aggregate([
{$sort:{"user.rankAmount":1}}])
I am not to good with aggregrate but this are the few things I have tried doing, but none is working. Thank you
