Function call from js script in ejs file tags

Suppose an ejs file for upvoting system:

<% if(clicked(post_id)==1) %>
    // load green button 
<%} else {%>
     // load red button

 <script>
 function clicked(id){
   if(currentUser.upvotes_downvotes===undefined)
       return -1;
   PreClicked = arr.find(clicked => {
        return clicked.postId.equals(id);})
   if(PreClicked === undefined)
    return 0;
   else if(PreClicked.type === "upvote")
     return 1;
   else if(PreClicked.type === "downvote")
     return 2;
     }
   </script>

But I am getting clicked is not defined

Passing array from tickboxes to a button- Jquery

So, I am trying to make id of each row into array and when the checked boxes are ticked, a button will show. From this button, we can have all the selected checkboxes id.
Notes: the checkboxes id actually likes this :

<input type="checkbox" id="chkT{$rows.id}" value="{$rows.id}" style="width: 15px; height: 15px;" class="js-checkbox single-row-checkbox" onchange="toggleTick_Change()" />

This is because, each row is getting it’s data from database, hence the {$rows.id}.
In the snippet, i delete the {$rows.id} just for example.

  1. the console.log is used for me to check whether the id is in array or not.
  2. I have tried the following codes regarding arrays, but the id’s are not in array.
let ids=[]
$(document).ready(function(){
    $('.js-checkbox').change (function() {
        if ($(this).attr('id') === 'chkAll'){
            if ($(this).prop('checked') === true){
                $('.single-row-checkbox').prop('checked', true);
                //ids.push($(this).attr("id")); 
                ids.push('.single-row-checkbox'.id);
                $('#conditional-part').show();
            }else if ($(this).prop('checked') === false){
                $('.single-row-checkbox').prop('checked', false);
                ids.pop($(this).attr("id"));
                //ids.pop(this.id);
                $('#conditional-part').hide();
            }
        } else if ($(this).attr('id') === 'chkT'){
            const checked = $('.single-row-checkbox');
                if (checked.length >= 2) {
                    $('#conditional-part').show();
                    //ids.push(this.id);
                    ids.push($(this).attr("id"));   
                } else {
                    $('#conditional-part').hide();
                    ids.pop($(this).attr("id"));
                }

        }
    });
});


I have achieve to make the selected checkbox into array using this code :

    let arr= [];
    function toggleTick_Change(){   
        var arr = $.map($('.single-row-checkbox:checkbox:checked'),     function(e, i) {
            return +e.value;
        });
        console.log('the checked values are: ' + arr.join(','));
        $('#conditional-part').show();
      
      //bind the event handler to it
          $arr.on('click', function(){
            btnPrintCNT_Click();
        });
    }

    function btnPrintCNT_Click(id){
        console.log('the checked values are: ' + id);   
    }
 #conditional-part{
    display:none;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<span id="conditional-part" >
      <div class="input-group "  role="group" aria-label="..." style="width: 85px; margin-top: 2px; " >
                <span class="input-group-btn">
                        <button id="btnPrintCNT" type="button" class="btn btn-sm btn-primary" style="margin: 2px; width: 100px; margin-left: 20px; float: left;"                        onclick="javascript:btnPrintCNT_Click()">CNT</button>
                </span>
            </div>
    </span>
                
    <input type="checkbox" id="chkT" value="{$rows.id}" style="width: 15px; height: 15px;" class="single-row-checkbox" onchange="toggleTick_Change()" />
    <input type="checkbox" id="chkT" value="{$rows.id}" style="width: 15px; height: 15px;" class="js-checkbox single-row-checkbox" onchange="toggleTick_Change()" />

But now, problem I faced are:

  1. How to call the id in array from ticked checkboxes to the button?
  2. How do I ticked all checkboxes without ticking it one by one?

Any help is highly appreciated. Thank you.

Angular – Apply decimal pipe to an input

I want to apply decimal pipe on an input so the user can see comma separated numbers as he/she types. I have tried the ngx-mask but that only works if you type in the input. When you patch a value to the input it doesn’t transform the value into decimal format.

Como puedo agregar objetos a un mismo item de LocalStorage?

Estoy empezando en JavaScript, tengo en mente crear una pagina de ventas, primero lo haré con local storage antes de meterme con bases de datos. creo que si puedo resolver esto podré hacer lo demás sin problema. Este script es solo para cuando haga el registro de los usuarios en la pagina, pero se guarda la misma información. Ya he intentado de muchas maneras, mi ultima opción ha sido preguntar.

CODIGO-JAVASCRIPT

const users = [], allUsers = []; // CREO LAS LISTAS DE LOS USUARIOS

// CLASE PARA GUARDAR LA INFORMACION DE LOS USUARIOS
class Users {
    constructor(id, nombre, edad, peso) {
        this.id = id;
        this.nombre = nombre;
        this.edad = edad;
        this.peso = peso;
    }
}

// SE PIDEN LOS DATOS DE CADA USUARIO
const id = getRandom();
const nombre = prompt('Nombre del nuevo usuario');
const edad = parseInt(prompt('Edad del nuevo usuario'));
const peso = prompt('Peso del nuevo usuario');
users.push(new Users(id, nombre, edad, peso));

// PREGUNTA SI EXISTE EL ITEM CON LA CLAVE EN EL LOCAL STORAGE
let existingUsers = JSON.parse(localStorage.getItem('allUsers'));
if (existingUsers == null) {
    localStorage.setItem('allUsers', allUsers);
}

// INTENTA ALMACENAR CADA USUARIO EN EL ITEM ALLUSERS DEL LOCAL STORAGE
localStorage.setItem('users', JSON.stringify(users));
allUsers.push(users[0]);
localStorage.setItem('allUsers', JSON.stringify(allUsers))

// ESCRIBE EN EL DOCUMENTO LA INFO DEL USUARIO REGISTRADO
console.log(`ID: ${id}<br>
Nombre: ${nombre}<br>
Edad: ${edad}<br>
Peso: ${peso}<br>`);

// FUNCION QUE DEVUELVE UN NUMERO ALEATORIO GRANDE PARA EL ID
function getRandom() {
    const max = 100000000000, min = 999999999999;
    const id_aleatorio = Math.round(Math.random() * (max - min ) + min);
    return id_aleatorio;
}

How to remove duplicates from array of objects and combine values of that duplicates?

I have array like this, my id and name will be same for multiple objects but organizations values can be different

array= [
  {id: 1, name: "Test1", organizations: 1},
  {id: 1, name: "Test1", organizations: 2},
  {id: 1, name: "Test1", organizations: 3},
  {id: 2, name: "Test2", organizations: 4},
  {id: 2, name: "Test2", organizations: 5},
  {id: 2, name: "Test2", organizations: 6} 
];

I want to convert this to be like this:

expectedArray =  [
  {id: 1, name: "Test1", organizations: [1,2,3]},
  {id: 2, name: "Test2", organizations: [4,5,6]} 
];

Can someone please help

How to drag and drop before or after element using java

I am building a drag and drop website. But I’m facing a problem to drop the element before or after, above or below the other element. I have watched a tutorial about it that’s working but I cannot attach the code to my code as I’m totally new to java. Here is my drag and drop code:

function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
#div1, #div2 {
  float: left;
  width: 200px;
  height: 300px;
  margin: 10px;
  padding: 10px;
  border: 1px solid black;
}
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">

<button  draggable="true" ondragstart="drag(event)" id="drag1">btn1</button>
<button  draggable="true" ondragstart="drag(event)" id="drag2">btn2</button>
<button  draggable="true" ondragstart="drag(event)" id="drag3">btn3</button>
 
</div>

<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>

Answer in javascript please

Remove space in chart.js

I am making line chart using chart js and here I would like to have a line alone without grid lines, axes lines and labels.

I have removed everything using the configurations but I am getting more space at the bottom of the chart.

Also the left side and top of points has been cut (only half circle is visible) and not displayed correctly.

var ctx = document.getElementById('myChart').getContext('2d');

var gradientStroke = ctx.createLinearGradient(500, 0, 100, 0);
gradientStroke.addColorStop(0, '#80b6f4');
gradientStroke.addColorStop(1, '#f49080');

var gradientFill = ctx.createLinearGradient(500, 0, 100, 0);
gradientFill.addColorStop(0, 'rgba(128, 182, 244, 0.6)');
gradientFill.addColorStop(1, 'rgba(244, 144, 128, 0.6)');

var myChart = new Chart(ctx, {
  type: 'line',
  data: {
    labels: ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL'],
    datasets: [
      {
        label: 'Data',
        borderColor: gradientStroke,
        pointBorderColor: gradientStroke,
        pointBackgroundColor: gradientStroke,
        pointHoverBackgroundColor: gradientStroke,
        pointHoverBorderColor: gradientStroke,
        pointBorderWidth: 10,
        pointHoverRadius: 10,
        pointHoverBorderWidth: 1,
        pointRadius: 3,
        fill: false,
        backgroundColor: gradientFill,
        borderWidth: 4,
        data: [100, 120, 150],
      },
    ],
  },
  options: {
    legend: {
      display: false,
    },
    plugins: {
      datalabels: {
        display: false,
      },
    },
    layout: {
      padding: {
        bottom: -20,
      },
    },
    scales: {
      yAxes: [
        {
          ticks: {
            fontColor: 'rgba(0,0,0,0.5)',
            fontStyle: 'bold',
            beginAtZero: true,
            maxTicksLimit: 5,
            display: false,
          },
          gridLines: {
            drawTicks: false,
            display: false,
            tickMarkLength: 0,
          },
          display: false,
        },
      ],
      xAxes: [
        {
          gridLines: {
            zeroLineColor: 'transparent',
            display: false,
            tickMarkLength: 0,
          },
          ticks: {
            fontColor: 'rgba(0,0,0,0.5)',
            fontStyle: 'bold',
            display: false,
          },
          display: false,
        },
      ],
    },
  },
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.js"></script>


<div class="chart-container">
 <canvas id="myChart"></canvas>
</div>

Could you please help me to resolve,

-> Removing of space at the bottom

-> Make the graph to fit in a size so that the left , top edges are visible in proper.

Thanks in advance.

how to add script code for thumb slide in slider for mobile

<script>
var slideIndex = 0;
showSlides();
var slides,dots;

function showSlides() {
    var i;
    slides = document.getElementsByClassName("mySlides");
    dots = document.getElementsByClassName("dot");
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
    }
    slideIndex++;
    if (slideIndex> slides.length) {slideIndex = 1}    
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[slideIndex-1].style.display = "block";  
    dots[slideIndex-1].className += " active";
    setTimeout(showSlides, 6000); // Change image every 6 seconds
}

function plusSlides(position) {
    slideIndex +=position;
    if (slideIndex> slides.length) {slideIndex = 1}
    else if(slideIndex<1){slideIndex = slides.length}
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[slideIndex-1].style.display = "block";  
    dots[slideIndex-1].className += " active";
}

function currentSlide(index) {
    if (index> slides.length) {index = 1}
    else if(index<1){index = slides.length}
    for (i = 0; i < slides.length; i++) {
       slides[i].style.display = "none";  
    }
    for (i = 0; i < dots.length; i++) {
        dots[i].className = dots[i].className.replace(" active", "");
    }
    slides[index-1].style.display = "block";  
    dots[index-1].className += " active";
}
</script>

I have a slider which is scroll with right and left arrow that is working fine for desktop but I need arrow as well as thumb slider in mobile view when someone can slide with thumb in mobile left and right I have added script. thanks in advance.

Does Kendo Grid support cell merge or not?

My Grid has the following structure

 $("#grid").kendoGrid({
   dataSource: {
       data: data,
       type: 'json'
       },
       pageable: true,
       columns: [
           { field: "SubServiceTypeName", title: "Sub Type" },
           { field: "PrepaidMonthName", title: "Gói dịch vụ" },
           { field: "DeviceName", title: "Tên thiết bị" },
           { field: "DeviceStatusName", title: "Tình rạng" },
           { field: "IsDeployName", title: "Triển khai" },
           { field: "PriceStatementName", title: "CL giá" }
       ]             
 });

Result: enter image description here

I want to merge rows with same value of column [PrepaidMonthName] (call as “Gói dịch vụ”). I don’t know if kendo supports merge cells or not yet?
What I expect:

enter image description here

Or is there another solution for me to do this?

Can npm devDependencies be used in production?

One of our products at work is a JS SDK that our clients can install and use with npm install .... I was going through the package.json file and found that a package, socket.io-client was installed as a devDependency. But the SDK is using socket.io for an integral part of its working, and it obviously it’s working for our clients. So, why is it working? Since, going by the documentation, devDependencies should not be installed when using npm install.

Error when attempting to call smart contract with javascript

I am trying to write a piece of javascript that calls a smart contract. The smart contract has been deployed to a local test net with truffle and ganache and the javascript is producing the following error:

Promise { <pending> }
/Users/user/node_modules/web3-core-helpers/lib/errors.js:43
        return new Error(message);
               ^

Error: Invalid JSON RPC response: ""
    at Object.InvalidResponse (/Users/user/node_modules/web3-core-helpers/lib/errors.js:43:16)
    at XMLHttpRequest.request.onreadystatechange (/Users/user/node_modules/web3-providers-http/lib/index.js:95:32)
    at XMLHttpRequestEventTarget.dispatchEvent (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request-event-target.js:34:22)
    at XMLHttpRequest._setReadyState (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:208:14)
    at XMLHttpRequest._onHttpRequestError (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:349:14)
    at ClientRequest.<anonymous> (/Users/user/node_modules/xhr2-cookies/dist/xml-http-request.js:252:61)
    at ClientRequest.emit (node:events:390:28)
    at Socket.socketErrorListener (node:_http_client:442:9)
    at Socket.emit (node:events:390:28)
    at emitErrorNT (node:internal/streams/destroy:164:8)
    at emitErrorCloseNT (node:internal/streams/destroy:129:3)
    at processTicksAndRejections (node:internal/process/task_queues:83:21)

Node.js v17.3.0

Javascript code:

onst Web3 = require('web3');

const web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

const contract_abi = [
   {
      "inputs":[

      ],
      "name":"getName",
      "outputs":[
         {
            "internalType":"string",
            "name":"",
            "type":"string"
         }
      ],
      "stateMutability":"view",
      "type":"function"
   },
   {
      "inputs":[
         {
            "internalType":"string",
            "name":"newName",
            "type":"string"
         }
      ],
      "name":"setName",
      "outputs":[

      ],
      "stateMutability":"nonpayable",
      "type":"function"
   }
]


const contract_address = "0x6C1750bfDD9D1327AE8c5dBD1Af75dc73C138Fd7";
var Contract = new web3.eth.Contract(contract_abi, contract_address);

console.log(Contract.methods.getName().call());

Solidity code:

pragma solidity >=0.4.24;

contract NameContract {

    string private name = "This is working!";

    function getName() public view returns (string memory)
    {
        return name;
    }

    function setName(string memory newName) public
    {
        name = newName;
    }
}

I am not sure if the issue is coming from me not handling the async request properly, the JSON abi being malformed or the smart contract response not being handled correctly.

Any help would be greatly appreciated.

How I can change the format of the numbers on jquery count-to? [duplicate]

Hi and thanks for reading me. I am using a Jquery function to count numbers but I would like to add commas to the numbers (in addition to a prefix), but I can’t find a way to do it so far. I tried using formatter: function (value, options) {return value.toFixed(options.decimals).replace(/B(?=(d{3})+(?!d))/g,","); but it doesn’t work yet. 🙁

My code is the following:

Main.js file:

$('.count-item').each(function(i) {
            $(this).appear(function() {
                var number = $(this).find('.count-to').data('countto');
                $(this).find('.count-to').countTo({from: 0, to: number, speed: 1500, refreshInterval: 10, formatter: function (value, options) {
           return value.toFixed(options.decimals).replace(/B(?=(d{3})+(?!d))/g, ",");
        }
                    
                });
            });
        });

plugins.js file:

(function($) {
    $.fn.countTo = function(options) {
        // merge the default plugin settings with the custom options
        options = $.extend({}, $.fn.countTo.defaults, options || {});

        // how many times to update the value, and how much to increment the value on each update
        var loops = Math.ceil(options.speed / options.refreshInterval),
            increment = (options.to - options.from) / loops;

        return $(this).each(function() {
            var _this = this,
                loopCount = 0,
                value = options.from,
                interval = setInterval(updateTimer, options.refreshInterval);

            function updateTimer() {
                value += increment;
                loopCount++;
                $(_this).html(value.toFixed(options.decimals));

                if (typeof(options.onUpdate) == 'function') {
                    options.onUpdate.call(_this, value);
                }

                if (loopCount >= loops) {
                    clearInterval(interval);
                    value = options.to;

                    if (typeof(options.onComplete) == 'function') {
                        options.onComplete.call(_this, value);
                    }
                }
            }
        });
    };

    $.fn.countTo.defaults = {
        from: 0,  // the number the element should start at
        to: 100,  // the number the element should end at
        speed: 500,  // how long it should take to count between the target numbers
        refreshInterval: 100,  // how often the element should be updated
        decimals: 0,  // the number of decimal places to show
        onUpdate: null,  // callback method for every time the element is updated,
        onComplete: null,  // callback method for when the element finishes updating
        formatter: function (value, options) {
           return value.toFixed(options.decimals).replace(/B(?=(d{3})+(?!d))/g, ",");
        }
    };
})(jQuery);

Index.html file:

<div class="count-item mb-sm-40">
                  <div class="count-icon"><span class="icon-piechart"></span></div>
                  <h3 class="count-to font-alt" data-countto=100></h3>
                  <h5 class="count-title font-serif">Siniestralidad (%)</h5>
                </div>

Anyone know what I could do about it or if there is a solution? I can’t find anything until now

Thanks for the help

I am new to node js and I have some problem with post using postman

I am new to node.js and learning it for quite few days and now I’m stuck with this app.post which is not working for me. If possible please let me know how to do app.update so it might be a big help in my learning process.
Kindly waiting for reply.

const mysql = require('mysql');
const express = require('express');
var app = express();
const bodyparser = require('body-parser');
app.use(bodyparser.urlencoded({extended: false}));
app.use(bodyparser.json());
app.listen(8000);
var mysqlconnection = mysql.createConnection(
    {
        host: 'localhost',
        user: 'Naveen',
        password: '',
        database: 'employeedb',
        multipleStatements: true
    }
);

mysqlconnection.connect((err)=>{
    if(!err)
    console.log("DB connection successfull");
    else
    console.log('DB connection failed n Error : '+ JSON.stringify(err, undefined, 2) );
});
app.post('/employee' ,function (req, res, next) {
    Name = req.query.Name, 
    Empcode = req.query.Empcode,
    Salary = req.query.Salary 
    let sql = "INSERT INTO employee (Name, Empcode, Salary) VALUES (? , ?, ?)";  
    mysqlconnection.query('sql, (Name, Empcode, Salary) ', (err, rows, fields) => {
        if (!err)
            res.send("Insert succeed");
        else
            console.log(err);
        });
    });    
    ```
and then I get these error messages:

**PS C:xampphtdocsfirst app> node index.js DB connection successfull Error: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'sql, (Name, Empcode, Salary)' at line 1
   (C:xampphtdocsfirst appnode_modulesexpresslibrouterindex.js:275:10) {   code: 'ER_PARSE_ERROR',   errno: 1064,   sqlMessage: "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'sql, (Name, Empcode, Salary)' at line 1",   sqlState: '42000',   index: 0,   sql: 'sql, (Name, Empcode, Salary) ' }**

Multiple reference queries with export functions to assign specific badges to Wix members

I’ve got series of automations made in the backend of Wix which I’m trying to cross-reference within an onClick function which will automatically assign member badges to members based on specific criteria from a dataset pulled from Google Sheets API and stored in Wix in the collection “Members”.

This is an export function which is triggered by a button on a custom Admin Dashboard. Once a member joins the site, their email address from PrivateMembersData is cross-referenced with the “Members” to find their “type” (name of the badge to be assigned) and push their memberId to an array. It then runs the assignMembers backend function in Wix which is expecting (badgeId, memberIds). Most members have multiple badges to be assigned, and they are all entered as individual rows in the “Members” collection.

The problem I am having is that it seems to be only assigning certain badges and not others, and specifically getting console errors which are telling me memeberIds is in an invalid format. I’m new to js and navigating Wix’s backend and wondering if I’m missing an obvious step. Please help! Thanks in advance.

import wixData from 'wix-data'
import { assignBadge, removeBadge } from 'backend/badges.jsw';
import { assignMembersBackendFunction } from 'backend/badges';
let Badge_A = "b2e41432-xxx-585a28c34da5"
let Badge_B = "8b77b069-xxx-1b9fc066d370"
let Badge_C = "9759af91-xxx-cdb2a9b32dc0"
let Badge_D = "2e598b2d-xxx-de48ff644c9f"
let Badge_E = "f272734e-xxx-e33443395ae8"

export function assignAllBadgeButton_click() {
    let badge = "";
    let BA = [""]
    let BB = [""]
    let BC = [""]
    let BD = [""]
     wixData.query("Members")
        .find()
        .then((results) => {
            results.items.forEach(item => {
                let type = item.type
                wixData.query("Members/PrivateMembersData")
                    .eq("loginEmail", item.email)
                    .find()
                    .then((result) => {
                        let member = result.items[0]
                        console.log(member)
                        // clearBadges(member)

                        if (type == "Badge A Name") {
                            BA.push(member._id)
                            doSomething(BA, Badge_A)

                        }
                        else if (type == "Badge B Name") {

                            BB.push(member._id)
                            doSomething(BB, Badge_B)

                        }
                        else if (type == "Badge C Name") {
                            BC.push(member._id)
                            doSomething(BC, Badge_C)
                        }
                        else if (type == "Badge D Name") {
                            BD.push(member._id)
                            doSomething(BC, Badge_D)

                        } else {
                            console.log("no match")
                        }

                        doSomething(BA, Badge_A);
                        doSomething(BB, Badge_B);
                        doSomething(BC, Badge_C);
                        doSomething(BD, Badge_D)
                        
                    })
            })

        })

}

export function doSomething(userIDs, badge) {
    let results = userIDs
    for (let i = 0; i < userIDs.length; i++) {

        assignMembersBackendFunction(badge, [results[i]])
            .then((assignedMembers) => {
                console.log(assignedMembers)

                return assignedMembers;
            })

    }

}

export function clearBadges(member) {

    removeBadge(Badge_A, member)
        .then(() => {
            removeBadge(Badge_B, member)
                .then(() => {
                    removeBadge(Badge_C, member)
                        .then(() => {
                            removeBadge(Badge_D, member)
                                .then(() => {
                                   console.log("deleted")
                                        })
                                })
                        })
                })
        })
}

/// IN WIX BACKEND MODULE ///:

import { badges } from 'wix-users-backend';

export function assignBadge(badgeID, userIDs) {
 return badges.assignMembers(badgeID, userIDs);
}

//remove a badge from a list of users
export function removeBadge(badgeID, userIDs) {
 return badges.removeMembers(badgeID, userIDs);
}

export function assignMembersBackendFunction(badgeId, memberIds) {
  return badges.assignMembers(badgeId, memberIds);