jQuery val() not working in my code with strange behavior

I know there are many questions related to this and I wouldn’t post this unless I had exhausted all posts and information I could possible find. I have tried to approach this from many many different angles to make sure I am not doing something wrong but I can not find it.

to trouble shoot, I have tried the following:

  • check to see if there is more than one of the same ID of the field I am trying to get the val() from
  • getting the child element’s of the wrapper id
  • renaming
  • adding the code in-line

Nothing works and nothing seems incorrect.

When I add a hard-coded string to the variable I am outputting, I see the string, but not the value of the input field.

I have been at this for two full days and I am stumped. Any hints or possible direction I should be looking at would be great.

I am using the same concept as in this code in many other places on the site and they all work fine.

<script>
$(document).ready(function() {  
$(document).on("click", '.addTaskNote', function() {

var uniquevalue = $(this).data('uniquevalue');
    
    console.log(uniquevalue);

var inputext = $("#" + uniquevalue).val();

   console.log(inputext);

});

});
</script>
<cfset makeUnique = createUUID()>
<div id="div#makeUnique#">
    <!--- short task note to add. --->
    <input type="text" id="#makeUnique#">
    <button class="addTaskNote" data-uniquevalue="#makeUnique#">UPDATE</button>
</div>

I know the function is triggered because the uniquevalue variable is logged to the console but the inputext variable is empty.

When I add a value attribute to the input field I still get an empty value.

<input type="text" id="#makeUnique#" value=""> returns empty

When I add a value to the value attribute, the console prints that value, but not any additional text I input.

<input type="text" id="#makeUnique#" value="hello"> returns ‘hello’ but when I type ‘there’ after ‘hello’ in the input field in the browser and click, it still only returns ‘hello’

Both the Javascript and the page code are part of a larger code file. When I create a separate file with this functionality it behaves as expected.

This I believe is where there might be an issue. I have looked for duplicate IDs, I have hardcoded the parameters and values to make sure there are no duplicates but this does not run as expected inside my code.

I believe this code is correct but there is a larger issue that I am not seeing and I don’t know where to begin looking. Any help or suggestions would be appreciated.

How to Increase/Decrease Counter when button is clicked while factoring the value of a dropdown

I have a counter which increases/decreases with +1 when a button is clicked.

The buttons are

  1. Adds Value
<button onClick="onClick()" type="button">ADD MORE</button>
  1. Subtracts From Total Value
<button onClick="onUnClick()" type="button">X</button>

Then the value in H6 changes

<h6 class="askclient">How Many? <a id="clicks">1</a></h6>

My Javascript Code

<script>
    var clicks = 1;
function onClick() {
  clicks += 1;
  document.getElementById("clicks").innerHTML  = clicks;
};
function onUnClick() {
  clicks -= 1;
  document.getElementById("clicks").innerHTML = clicks;
};
</script>

I need to modify it to also add/subtract the value of a select dropdown to the counter so that the total now factors in the text of the dropdown.
The dropdown:

<select id="ddlViewBy"  name="repetition[]">
   <option value="1">None</option>
   <option value="2">1</option>
   <option value="3">2</option>
   <option value="4">3</option>
   <option value="5">4</option>
</select>

Web Chat – Writing and fetching new messages from database

I’m trying to create a web chat where clients (identified by client number) can talk to one of 4 departments in a company.

I want to use a table named Chat in my SQL database, like this:

[ Chat ]

| Client    | Department   | Tx | Rx | Message     | Date       | Time  |
| 000000000 | department_1 | 0  | 1  | bla bla bla | dd-mm-yyyy | 00:00 |
| 000000000 | department_1 | 1  | 0  | bla bla bla | dd-mm-yyyy | 23:59 |
| 000000000 | department_2 | 0  | 1  | bla bla bla | dd-mm-yyyy | 00:00 |
| 000000000 | department_2 | 1  | 0  | bla bla bla | dd-mm-yyyy | 23:59 |
| 000000000 | department_3 | 0  | 1  | bla bla bla | dd-mm-yyyy | 00:00 |
| 000000000 | department_3 | 1  | 0  | bla bla bla | dd-mm-yyyy | 23:59 |
| 000000000 | department_4 | 0  | 1  | bla bla bla | dd-mm-yyyy | 00:00 |
| 000000000 | department_4 | 1  | 0  | bla bla bla | dd-mm-yyyy | 23:59 |

This is what I did so far on HTML:

<div id="chat">
  <div id="messages">
    <div class="spacer"></div>
    <div class="rx_message">
      <p>example of a received message</p>
    </div>
    <div class="spacer"></div>
    <div class="tx_message">
       <p>example of a transmited message</p>
    </div>
  </div>
  <form id="send_messages">
    <input type="text" id="send_messages_text" placeholder="Aa" name="message" required/>
    <input type="submit" id="send_messages_submit" onclick="sendMessages()" value="Send"/>
  </form>
</div>

And this is what I did so far on Javacript:

function sendMessages() {
  let messages = document.getElementById('messages');
  let textInput = document.getElementById('send_messages_text');
  if (textInput.value.length === 0) {
    event.preventDefault();
  } else {
    document.getElementById('send_messages').addEventListener('submit', function(e) { e.preventDefault(); });
    let spacer = document.createElement('span');
    let sendMessage = document.createElement('div');
    spacer.className = 'spacer';
    sendMessage.className = 'tx_message';
    messages.appendChild(spacer);
    messages.appendChild(sendMessage);
    sendMessage.innerHTML = textInput.value;
    textInput.value = '';
    messages.scrollTop = messages.scrollHeight;
    messages.animate({scrollTop: messages.scrollHeight});
  }
}

Right now it’s only validating if textInput lenght is equal to 0, and if condition is true it’s not sending anything, but what I need it to check if it’s really an “empty” string or not (ex: a string with only spaces).

It’s also printing the send messages into the chat window (that scrolls down after submiting to show the new message), but I need it to be able to write this into my database when a client sends a new message.

Also, I need it to periodically fetch new messages from database, so I’ve set a timer like this:

setInterval(function(){
  receivedMessages()
}, 5000); // 5 seconds

But I need some help so I can retrieve the new received messages from database and load them into the chat window!

Can anyone help me out please?

Make slideshow/animation with multiple images

i know that there are question similar to this one, but my goal is different.

I have an array of Sceneobjects like this:

 const scene = {
      Id: Math.floor(Math.random() * 10000),
      JsonObj: canvas.getJsonObj(),
      image: this.editor?.export.toImage(),
      duration: 1000,
    };

And am using a library PikasoJS that alows me to export/import an image of a html div.

I put each image of div in scene object, and i want to display all these images in array scenes one by one automatically, and duration of scene is specified in duration field.

How can i implement something like this, i tried working with setInterval but it didn’t work as i espected:

 const playScene = () => {
    const cpScenes = [...scenes];
    let i = 0;
    for(let i = 0;i < cpScenes.length;i++) {
      setTimeout(() => {
        let image = cpScenes[i].image;
        console.log("am runnig");
        this.editor.loadImage(image);
      }, cpScenes[i].duration);
    }
    clearTimeout();
  };

The way am thinking is that setTimeout should block execution of for loop and then executes it’s code after specified time. But from what i noticed i was wrong.

This is my first time working with react and js.

ES6 Modules : Importing a module in an Angular component

I have an ES6 module where I am exporting a library. I want to be able to use this module in an angular component. I cannot have the library files locally within my Angular app, neither can I publish the library as an npm package.

Can I host the module in a dev server, and use the server url to import the module in my Angular component?

I tried things like

component.ts

import * as lib from "...url";

or adding this in index.html

<script src = "..url"/>

Neither of them have worked. Can anyone help me with this?

How can I .filter only unique strings in my array?

I am having a recurring issue with arrays of strings I bring in from a spreadsheet. I want to filter a these arrays of strings for unique values and then fill options in a dropdown for a form.

I have tried multiple solutions, but for some reason none of them works.

function filterContainerDropdown(){

var containerFilterHelper =  inventory.filter(obj => obj.playerid == filterID)
    
  var containerOptions = containerFilterHelper.map(row => ({

      container: row.container,
     
    }));

    const unique = (x, i, a) => a.indexOf(x) == i;
     
    var uniqueContainers = containerOptions.filter(unique);

     console.log('')
     console.log('++++++++uniqueContainers+++++++++++')
     console.table(uniqueContainers); 

    for(var i = 0; i < containerOptions.length; i++) {

      setContainer[setContainer.length] = new Option(containerOptions[i].container,containerOptions[i].container)
        
    }

  }

I have tried solutions online galore. They work with other data. My data is a list of short strings.

EDIT: Are there well known issues with filtering strings for unique values?

EDIT2: The data I am giving it:

0   'Backpack'
1   'Backpack'
2   'Backpack'
3   'Backpack'
4   'Backpack'
5   'Backpack'
6   'Backpack'
7   'Backpack'
8   'Backpack'
9   'Backpack'
10  'Backpack'
11  'Backpack'
12  'Backpack'
13  'Backpack'
14  'Biltong'
15  'Biltong'
16  'Biltong'
17  'Biltong'
18  'Holding or Wearing'
19  'Holding or Wearing'
20  'Holding or Wearing'
21  'Holding or Wearing'
22  'Holding or Wearing'
23  'Holding or Wearing'
24  'Holding or Wearing'
25  'Holding or Wearing'
26  'Holding or Wearing'
27  'Holding or Wearing'
28  'Holding or Wearing'
29  'Holding or Wearing'
30  'Holding or Wearing'
31  'Holding or Wearing'
32  'Holding or Wearing'
33  'Holding or Wearing'
34  'Holding or Wearing'
35  'Holding or Wearing'
36  'Holding or Wearing'
37  'Holding or Wearing'
38  'Holding or Wearing'
39  'Holding or Wearing'
40  'Holding or Wearing'
41  'Location'
42  'Location'
43  'Location'
44  'Location'
45  'Location'
46  'Saddle Bag BL'
47  'Saddle Bag FL'
48  'Saddle Bag FR'
49  ''
50  ''
51  ''
52  ''
53  ''
54  ''
55  ''
56  ''
57  ''
58  ''
59  ''
60  ''
61  ''
62  ''
63  ''
64  ''

The data I want out:

 0  'Backpack'   
 1  'Biltong'   
 2  'Holding or Wearing'      
 3  'Location'        
 4  'Saddle Bag BL'
 5  'Saddle Bag FL'
 6  'Saddle Bag FR'
 7  ''

What is context.done doing in AWS Lambda?

I am working through an AWS guide for Cognito.

The Lambda function calls context.done() with two parameters, null and event.

I am trying to understand what the null parameter is and what context.done is doing with the event being passed in to it.

exports.handler = (event, context) => {
  if (event.request.session.length === 1 && 
    event.request.session[0].challengeName === 'SRP_A') {
    event.response.issueTokens = false;
    event.response.failAuthentication = false;
    event.response.challengeName = 'CUSTOM_CHALLENGE';
  } else if (
    event.request.session.length === 2 &&
    event.request.session[1].challengeName === 'CUSTOM_CHALLENGE' &&
    event.request.session[1].challengeResult === true
  ) {
    event.response.issueTokens = true;
    event.response.failAuthentication = false;
  } else {
    event.response.issueTokens = false;
    event.response.failAuthentication = true;
  }
  context.done(null, event);
};

I have console logged the context object, but I still don’t understand what it’s doing.

2022-05-04T22:16:59.591Z    4c2609e6-69d7-4bd9-a25c-8527b7c6653a    INFO    {
  callbackWaitsForEmptyEventLoop: [Getter/Setter],
  succeed: [Function (anonymous)],
  fail: [Function (anonymous)],
  done: [Function (anonymous)],
  functionVersion: '$LATEST',
  functionName: 'cognito-define-auth-challenge',
  memoryLimitInMB: '128',
  logGroupName: '/aws/lambda/cognito-define-auth-challenge',
  logStreamName: '2022/05/04/[$LATEST]280e88c6f58545f8bc6e5d177c13cc5b',
  clientContext: undefined,
  identity: undefined,
  invokedFunctionArn: 'arn:aws:lambda:us-east-1:268280247265:function:cognito-define-auth-challenge',
  awsRequestId: '4c2609e6-69d7-4bd9-a25c-8527b7c6653a',
  getRemainingTimeInMillis: [Function: getRemainingTimeInMillis]
}

Phaser 3 Player using WASD is stronger

I have 2 players (one using WASD and another using arrow keys). When they push each other, Player 1 (WASD) is stronger than the other player (arrow keys) even though the velocity is the same.

if (keyA.isDown) {
    this.player1.setVelocityX(-this.playerSpeed);
} else if (keyD.isDown) {
    this.player1.setVelocityX(this.playerSpeed);
} else {
    this.player1.setVelocityX(0);
}

if (keyW.isDown) {
    this.player1.setVelocityY(-this.playerSpeed);
} else if (keyS.isDown) {
    this.player1.setVelocityY(this.playerSpeed);
} else {
    this.player1.setVelocityY(0);
}

if (cursors.left.isDown) {
    this.player.setVelocityX(-this.playerSpeed);
} else if (cursors.right.isDown) {
    this.player.setVelocityX(this.playerSpeed);
} else {
    this.player.setVelocityX(0);
}

if (cursors.up.isDown) {
    this.player.setVelocityY(-this.playerSpeed);
} else if (cursors.down.isDown) {
    this.player.setVelocityY(this.playerSpeed);
} else {
    this.player.setVelocityY(0);
}

Deleting Wasabi CDN Bucket 204 Error Not Deleting

So I’m trying to programmatically delete Wasabi CDN buckets. My request is sending back 204 and showing success but nothing is being moved/deleted. I’m using node/javascript to do this and have been stuck for a few hours, hoping for some insight.

Here is my function that is supposed to delete the bucket.

import expressAsyncHandler from 'express-async-handler'
import User from '../../models/User.js'
import axios from 'axios'
import aws4 from 'aws4'

/**
 * @desc:   THIS is going to be a testing function that will be added into admin delete user and all related docs.
 * @route:  DELETE
 * @access: Private - Admin Route for when deleting user will delete the CDN username bucket aswell
 * @goalHere: The goal of this function is to delete the user bucket from CDN. So that if we d
 * @comment: This is a testing function that will be added into deleteVideo.js. Unless we just await this function in deleteVideo.js.
 */

export const deleteUserBucket = expressAsyncHandler(async (req, res, next) => {
  try {
    const user = await User.findOne({ username: req.user.username })
    const username = user.username

    let request = {
      host: process.env.CDN_HOST,
      method: 'DELETE',
      url: `https://s3.wasabisys.com/truthcasting/${username}?force_delete=true`,
      path: `/truthcasting/${username}?force_delete=true`,
      headers: {
        'Content-Type': 'application/json',
      },
      service: 's3',
      region: 'us-east-1',
      maxContentLength: Infinity,
      maxBodyLength: Infinity,
    }

    let signedRequest = aws4.sign(request, {
      accessKeyId: process.env.CDN_KEY,
      secretAccessKey: process.env.CDN_SECRET,
    })

    //delete the Host and Content-Length headers
    delete signedRequest.headers.Host
    delete signedRequest.headers['Content-Length']

    const response = await axios(signedRequest)
    console.log(response.data)
    console.log('successfully deleted user bucket', response.status)

    return res.status(200).json({
      message: `Successfully deleted user bucket`,
    })
  } catch (error) {
    console.log(error)

    return res.status(500).json({
      message: `Problem with deleting user bucket`,
    })
  }
})

export default deleteUserBucket

When I send the http DELETE request in POSTMAN to {{dev}}api/admin/deleteuserbucket it then gives me a response of 204 ok and this is the response.

{
    "message": "Successfully deleted user bucket"
}

I then go to my Wasabi CDN Buckets to check if it is deleted, in this case it’s goodstock and it’s still there. Feel like I’m missing something dumb here. Any help would be appreciated! Thank you for taking the time.`

`

Why am I still getting MongoExpiredSessionError even though I’m parsing the json in my azure function?

With regards to my Azure function, I cannot for the life of me figure out why I’m getting MongoExpiredSessionError: Cannot use a session that has ended error when trying to do an extremely simple insertion. I’ve tried JSON.parse(result); and JSON.stringify(result); but still getting the same error.

I’ve also tried removing the finally block, tried adding await in front of collection() but still getting the same error. I’ve pretty much done all the I can that I’ve found on the web to troubleshoot but to no avail.

What am I doing wrong?

Here’s my code:

const mongo = require('mongodb');
const MongoClient = require('mongodb').MongoClient;
const uri = "myUri"

module.exports = async function (context, req) {
    const client = await MongoClient.connect(uri, {useNewUrlParser:true}).catch(err => {context.log(err); });

    let result = null;
    let callerEntityProfile = req.body.CallerEntityProfile;
    let packIdInput = callerEntityProfile.Entity.PackIdInput;
    let userId = callerEntityProfile.Entity.UserID;

    try {
        const db = await client.db("myDB");
        let collection = await db.collection("myCollection");
        let query = { userId : userId };
        result = await collection.findOne(query);

        let insertPack = {
          "PackId" : packIdInput
        };

        result.packsOwned.push(insertPack);

        JSON.parse(result);

        collection.insertOne(result, function(err, r) {
          console.log('inside insertOne')
          console.log(err); // this is where it's showing the error message
        });

    }
    catch (err) {
        context.log(err);
    }
    finally {
        client.close();
    }

   
}

how to check if a password contains an integer and return an object with a boolean representation of that value

Trying to create a function that checks a password for integers and then return an object which will store a boolean representing whether the password contains an integer, and then destructure the boolean out of the function, but I keep getting this problem…

enter image description here

function checkForInteger(password) {
  const arrayOfIntegers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  let intBoolean = {};
  arrayOfIntegers.forEach((int) => {
    if (password.includes(int)) {
      intBoolean = { integerIsPresent: password.includes(int) };
    } else {
      intBoolean = { integerIsPresent: password.includes(int) };
    }
  });
  return intBoolean;
}
checkForInteger("3gufr"); //returns {integerIsPresent:false}

How to do a const when conditionally set? [duplicate]

In the following:

class _Set extends Set {
    add(...args) { 
        for (const x of args) {
            this.add(x)
        }
        return this;
    }
    static getArrayFromInput(text) {
        let arr = [];
        if (text.includes(',')) {
            arr = text.split(',').map(x => x.trim());
        } else {
            arr = [text,];
        }
        return arr;
    }
}

I would prefer to use const instead of let on the arr variable. However, because const does not allow re-assignment I can’t just replace the const. What would be the suggested way to write this then? My thoughts were either to (1) just use let; (2) use .add instead of = to populate the data-structure; or (3) if possible, cast to const (sounds like a C thing, probably not possible in javascript?).

updating state correctly oncompleted query from apollo

so im trying to update an state for each individual case

{buyer.map((x) => {
        return <IdentificationCard id={x.id} />;
     })}

(inside identificationCard component)
const [uploadFile, { data, error }] = useMutation(UPLOAD_ALL_DOCUMENTS, {
  onCompleted({ uploadFile }) {
        const cardFrontDownloadLink = uploadFile.contract.buyer.documents.id_anverse_download_link;
        const cardBackDownloadLink = uploadFile.contract.buyer.documentss.id_reverse_download_link;   
        setFormValues({
           ...formValues,
           buyerData: {
              ...formValues.buyerData,
              buyer: buyer.map((x) => {
                 return x.id == id
                    ? {
                         ...x,
                         idCardFront: cardFrontDownloadLink ? cardFrontDownloadLink : '' ,
                         idCardBack: cardBackDownloadLink ? cardBackDownloadLink : ''
                      }
                    : x
              })
           }
        });
  },
  onError({ imgError }) {
     notification.error({
        message: 'Error',
        description: 'try loading your ID again or check your internet connection'
     });
  }

});

for example, When i drop an image onto the idCardFront, this query returns a link, and then i update the buyer object key with the link as its new value, however heres is my problem, after updating that first state, i try to do the same with the idCardBack on the second mapped IdentificationCard component, and it updates de idCardBack with the new value but also updates the idCardFront with the previous value saved in the previos identificationCard component
enter image description here

im assuming that when i update the state, given that the onCompleted function is being called again after each upload, the map checks the current value and updates the second object, but im not sure how to get out of the function while storing each link on its corresponding key, any help will be much appreciated