Validate form before Stripe pop up/payment modal appears

I’m trying to validate my form before the stripe payment modal appears, but the modal appears before the form can be validated. I’m using jquery validation plugin for my validation. I’ve tried adding the Stripe integration code in the submitHandler function, but still no luck. Below is what I currently have for my code:

HTML

<!-- google & apple pay btn -->
<div id="payment-request-button" class="btn__link btn__link--fullwidth-mob btn__link--paypal-flex btn__link--marginLeft-0">
   <%--A Stripe Element will be inserted here--%>
</div>

<!--  google & apple validation btn -->
<input id="paymentRequestButtonValidation" class="btn__link btn__link--fullwidth-mob btn__link--secondary btn__submit" type="submit" value="G Pay Validation">

JS

    var btnSubmitId = '';

    //-- get the id of the btn submit
    $('.btn__submit').click(function(event) {
        btnSubmitId = event.target.id;
    });

    // ----------------------------- STRIPE INTEGRATION  ----------------------------- //
    let searchParams = new URLSearchParams(window.location.search);
    var urlAmount = searchParams.get('Amount');
    var urlAmountNum = parseFloat(urlAmount);
    var donationAmount = urlAmountNum * 100;
    var clientSecret = "<%= clientSecret %>";
    var stripe = Stripe(stripeCredentials);
    var paymentRequest = stripe.paymentRequest({
        country: 'GB',
        currency: 'gbp',
        total: {
            label: 'Test payment',
            amount: donationAmount
        },
        requestPayerName: true,
        requestPayerEmail: true,
    });
    var elements = stripe.elements();
    var prButton = elements.create('paymentRequestButton', {
        paymentRequest: paymentRequest,
    });
    
    // Check the availability of the Payment Request API first.
    paymentRequest.canMakePayment().then(function(result) {
        if (result) {
            // if available mount/create the button
            prButton.mount('#payment-request-button');
        } else {
            // if NOT available hide the button and console log it
            document.getElementById('payment-request-button').style.display = 'none';
            console.log('ERROR - btn not available & can't be mounted');
        }
    });

    paymentRequest.on('paymentmethod', function(ev) {
        // Confirm the PaymentIntent without handling potential next actions (yet).
        stripe.confirmCardPayment(
            clientSecret,
            {payment_method: ev.paymentMethod.id},
            {handleActions: false}

        ).then(function(confirmResult) {
            if (confirmResult.error) {
                // Report to the browser that the payment failed, prompting it to
                // re-show the payment interface, or show an error message and close
                // the payment interface.
                ev.complete('fail');
            } else {
                // Report to the browser that the confirmation was successful, prompting
                // it to close the browser payment method collection interface.
                ev.complete('success');
                // Check if the PaymentIntent requires any actions and if so let Stripe.js
                // handle the flow. If using an API version older than "2019-02-11"
                // instead check for: `paymentIntent.status === "requires_source_action"`.
                if (confirmResult.paymentIntent.status === "requires_action") {
                    // Let Stripe.js handle the rest of the payment flow.
                    stripe.confirmCardPayment(clientSecret).then(function(result) {
                        if (result.error) {
                            // The payment failed -- ask your customer for a new payment method.
                        } else {
                            // The payment has succeeded.
                        }
                    });
                } else {
                    // The payment has succeeded.
                }
            }
        });

        prButton.on('click', function(ev) {

            // get the current amount from the #donationValue inout field
            paymentRequest.update({
                total: {
                    label: 'Test payment',
                    amount: $("#donationValue").val()*100,
                },
            });
        })
    });

    // -- single form validation
    $('#singleForm').validate({
        rules: {
            donationValue: {
                required: true,
                number: true,
                twoDecimal: true
            },

            donationtype: {
                required: true
            },

            firstname: {
                required: true
            },

            lastname: {
                required: true
            },

            email: {
                required: true
            },

            addressSearch: {
                required: true
            },

            address1: {
                required: true
            },

            postcode: {
                required: function(e) {
                    return $(e).closest('form').find('#country').val() == 'United Kingdom';
                }
            },

            town: {
                required: true
            },

            country: {
                required: true
            },

            mobile: {
                required: '#receiveSMS:checked' 
            }
        },

        messages: {
            donationValue: {
                required: 'Please enter your donation amount.',
                number: 'Please enter a valid donation amount.'
            },
            donationtype: 'Please select one of the options for Gift Aid.',
            firstname: 'Please enter a valid first name.',
            lastname: 'Please enter a valid last name.',
            email: 'Please enter a valid email address.',
            addressSearch: 'Please enter a valid postcode, street name or address.',
            address1: 'Please enter a valid address.',
            postcode: 'Please enter a valid postcode.',
            town: 'Please enter a valid town/city.',
            country: 'Please select a valid country.',
            mobile: 'Please enter your mobile phone number above'
        },

        highlight: function(element) {
            $(element).parent().find('span').addClass('error__text--icon');
            $(element).parent().find('input').addClass('form__input--error');
            $(element).parent().find('select').addClass('form__input--error');

            if ( element.id == 'dtOwnDonation' ) {
                $(element).parent().find('span').removeClass('error__text--icon');
            }
        },

        unhighlight: function(element) {
            $(element).parent().find('span').removeClass('error__text--icon');
            $(element).parent().find('input').removeClass('form__input--error');
            $(element).parent().find('select').removeClass('form__input--error');
        },

        submitHandler: function() {
            if ( btnSubmitId == 'singleBtnValidation' ) {

                $('#singleBtn').click();
                console.log('debit/credit card form - validation successful');

            } else if ( btnSubmitId == 'paymentRequestButtonValidation' ) {

                console.log('paymentRequestButtonValidation - validation successful');

                
            }
        }  
    });

Thanks in advance!

multiple filtering using typescript

I have an array of complex objects which I need to filter based on multiple conditions

var myList= [
  {
    "UserId": 1,
    "UserDetails": {
      "Department": [
        {
          "Name": "dept1"
        }
      ],
      "Projects": [
        {
          "Name": "Project1"
        },
        {
          "Name": "Project2"
        }
      ]
    }
  },
  {
    "UserId": 2,
    "UserDetails": {
      "Department": [
        {
          "Name": "dept2"
        }
      ],
      "Projects": [
        {
          "Name": "Project3"
        },
        {
          "Name": "Project4"
        }
      ]
    }
  },
  {
    "UserId": 3,
    "UserDetails": {
      "Department": [
        {
          "Name": "dept3"
        }
      ],
      "Projects": [
        {
          "Name": "Project5"
        },
        {
          "Name": "Project6"
        }
      ]
    }
  }
]

I want to filter on two conditions either Department–>Name is “dept3″ or there exist a project with Name->”Project3”

var filteredElements=this.myList.filter((x)=>x.UserDetails.filter((y)=>y.Department... ??

How can I write code to filter on these two conditions?

If Date is Less Than Current Date by 15mins then do something

I have been trying to work on something with dates and I was wondering how to check if it is less than 30mins or 15mins difference then should call a function.

let btnCheck = document.querySelector('button');
let result = document.querySeletor('h1');

let current = new Date();
let date = new Date('01/01/2021');

btnCheck.addEventListener('click', () => {
let ms1 = current.getTime();
let ms2 = date.getTime();

result.innerText = ms2 < ms1;
});

So far it results in a true or false but I wanted to add something if the current date is less than the date by 15mis or 30 mins show a button.
Thank you in advance! Much appreciated!

Support a link within InnerText [duplicate]

I’m trying to get the message that’s being rendered by this function to have the link part clickable. (highlighted it with asterisks)
Right now it’s just acting like a string.
I’ve tried adding anchor tags but to no avail.

  function onSuccess(uploadedImgUrl) {
    const encodedUploadedImgUrl = encodeURIComponent(uploadedImgUrl);
    document.querySelector(
      '.user-msg'
    )**.innerText = `Your photo is available here:
     ${uploadedImgUrl}`;**

    document.querySelector('.share-container').innerText = `
        <a class="btn" href="https://www.facebook.com/sharer/sharer.php?u=${encodedUploadedImgUrl}&t=${encodedUploadedImgUrl}" title="Share on Facebook" target="_blank" onclick="window.open('https://www.facebook.com/sharer/sharer.php?u=${uploadedImgUrl}&t=${uploadedImgUrl}'); return false;">
           Share   
        </a>`;
  }
  doUploadImg(imgDataUrl, onSuccess);
}

Would appreciate any kind of help!

How to get current time in hh:mm:ss format using moment in React JS

I want to calculate the time between hours and moments. with example:

export const DataCoba: React.FC = () => {
const format = "hh:mm:ss";
  return (
    <div>
      {moment(format).isBetween(
        moment("21:00:00", format),
        moment("23:00:00", format)
      )
        ? "Between"
        : "NOOO"}
    </div>
  );
};

from the script above what I want is to get the current time, but only in hh:mm:ss format only.
for example: moment('23:00:00', hh:mm:ss).

moment(format) is showing invalid date. Is there a way to do it?

Wait for a query in MongoDB

I have this async method written in Typescript to query, with the nodejs driver, a MongoDB; the compiler indicates that the “await” before “myConnectedClient” has no effect on the type of this expression; I’m confused: is the call to the aggregate() asynchronous? So, I have to wait, or not?
Thanks.

async findQuery<T>(
    collection: string,
    findParams: Query<T>,
    sort: Sort<T>,
    myConnectedClient: MongoClient
  ) {
    const firstResult = await myConnectedClient // the compiler indicates await is useless
      .db("ZZZ_TEST_ALL")
      .collection("my_collection_01")
      .aggregate<string>([{ $project: { _id: 0, name: 1 } }]);
    firstResult.forEach((field) => {
      console.log(`Field: ${field}`);
    });
  }

How to make a swipe on mobile via iframe

Tell me please. Owl carousel is displayed on my website page via an iframe, as I understand this may be the main reason why the slider itself does not scroll on the mobile phone if I swipe it. The buttons and arrows work, the swipe does not. “touchDrag: true” Doesn’t help.

Can’t understand how this “continue” function in loop is working?

I hope YOU guys are doing good
I am learning Javascript
I got to know about “continue” which we can use in loop for iteration.
But here is what i can’t get

First have a look at the code:

let k= 1

do{
    if(k===9){
        k++;
        continue;
    }
    console.log(k+1);
    k++;
}while(k<15);

When in console.log is (k+1)then, 9 is printed and 10 is missed.
Can’t get why?

But when this code is used

let k= 1

do{
    if(k===9){
        k++;
        continue;
    }
    console.log(k);
    k++;
}while(k<15);

When in console.log is (k)then, 9 is not printed and 10 is printed.

Can’t understand the logic behind when simple (k) is used and when (k+1) is used?

Thanks

Javascript languages [closed]

Before I ask our question, I want to say that I just want to enter the field of programming
I want to ask my question to the whole developers.

(Is a JavaScript programming language Is it efficient in the field of Android programming or not?
If it works, please explain more.)

{Thanks}

findFirst does not working with 3 filters on Prisma

I’m having this problem when I want to check if I have at least one record with the parameters. With 2 filters it works fine, but with 3 it’s not working.

await prismaClient.t_endereco
                .findFirst({
                    where: {
                        logradouro, (string)
                        bairro, (string)
                        numero, (number)
                    },
                })

the condition to update the record is not having another identical.

i tried to use AND too:

await prismaClient.t_endereco
                .findFirst({
                    where: {
                        AND:[
                              {logradouro}, 
                              {bairro}, 
                              {numero},  
                            ]
                        
                    },
                })

same issue.

someone to help me with this?

Cannot get data out of composable to fetch firebase data

I have a composable in vue that uploads data to firebase storage. It works, but I cannot get the data out of the composable. I think it has something to do with a return or where I’m defining terms?

The code below is built around the documentation available for firebase Storage (https://firebase.google.com/docs/storage/web/upload-files).

useStorage.js

import { ref } from "vue";
import { projectStorage } from "../firebase/config";
import {
  uploadBytesResumable,
  getDownloadURL,
  ref as storageRef,
} from "@firebase/storage";

const useStorage = () => {
  const error = ref(null);
  const url = ref(null);
  const filePath = ref(null);

  const uploadImage = async (file) => {
    filePath.value = `images/${file.name}`;

    const storageReference = storageRef(projectStorage, 
 filePath.value);

    const uploadTask = 
 uploadBytesResumable(storageReference, file);

    await uploadTask.on(
      "state_changed",
      (snapshot) => {
        const progress =
          (snapshot.bytesTransferred / snapshot.totalBytes) 
 * 100;
        console.log("Upload is " + progress + "% done");
      },
      (err) => {
        console.log(err);
        error.value = err.message;
      },
      () => {
 
        
 getDownloadURL(uploadTask.snapshot.ref).then((downloadURL) 
 => {
          console.log("File available at", downloadURL);
          url.value = downloadURL;
          console.log(url.value); <--HAS CORRECT VALUE
          return url.value; <--DOESNT DO ANYTHING
        });
      }
    );
    console.log(url.value);
  };

   return { url, filePath, error, uploadImage }; <--URL IS 
NOT RETURNING OUT OF THIS COMPOSABLE
};

export default useStorage;

Vuetify : place title/subtitle next to icon in a card

enter image description here

I have a card component, and I’m trying to place my title, subtitle at the right of my icon.It some how kept going down to the next line. I’m new to Vuetify.

<template>
    <v-container fluid class="my-5">
        <v-row>
            <v-flex col-xs-12>
                <v-card elevation="2" class="pa-5">
                    <v-flex xs3>
                        <v-btn text color="black">
                            <v-icon left large class="mr-5">{{ icon }}</v-icon>
                        </v-btn>
                    </v-flex>
                    <v-flex xs9>
                        <v-card-title>
                            {{ title }}
                        </v-card-title>

                        <v-card-subtitle> {{ subtitle }} </v-card-subtitle>
                    </v-flex>
                </v-card>
            </v-flex>
        </v-row>
    </v-container>
</template>
<script>
export default {
    name: 'MainPanel',
    props: {
        icon: String,
        title: String,
        subtitle: String
    }
}
</script>
<style></style>

Please let me know how can I achive that.

How to pass props from one Component to another component with onClick() event in React.js

Quick Help Needed! I have Two React components Vendors and VendorsList. In Vendors.js Component i have asset.asset_name text rendered in table format. What I want is, When I click on I asset.asset_name, I wanted to pass it’s value from Vendors component to VendorsList component. How could I do this?

Here is code for Two Components

Vendors.js

import React, { useEffect, useState } from "react";
import { axios } from "axios";

const Vendors = () => {
  const [data, setData] = useState({});
  const baseURL =
    "http://127.0.0.1:8000/api/business_process/business-impact/bussiness-assets-detail";

  useEffect(() => {
    axios
      .get(baseURL)
      .then((response) => {
        setData(response.data);
      })
      .then(
        (response) => {},
        (err) => {
          alert("No Data To Show");
        }
      )
      .catch((err) => {
        return false;
      });
  }, []);
  const DisplayData = data.business_assets?.map((asset) => {
    return (
      <tr>
        <td>{asset.business_assets}</td>
        <td onClick={() => alert(asset.asset_name)}>{asset.asset_name}</td>
      </tr>
    );
  });
  return <div></div>;
};

export default Vendors;

**I tried to pass the value here but I ended up alerting the asset.asset_name text.

const DisplayData = data.business_assets?.map((asset) => {
        return (
          <tr>
            <td>{asset.business_assets}</td>
            <td onClick={() => alert(asset.asset_name)}>{asset.asset_name}</td>
          </tr>
        );
      });

Here is VendorsList.js

    import React from "react";
const VendorsList = ({ asset_name}) => {
  const foo = "test" + asset_name;
  return (
    <div>
      <h1>{foo}</h1>
    </div>
  );
};

export default VendorsList;

I need asset.asset_name value to be passed to VendorsList when I click on asset.asset_name value from Vendors component

How to do a web program with displaying continuously updating data without refreshing? [closed]

I’m trying to make a web-based program that could dynamically display some data transmitted from python. The simple structure I imagined is like this.

  1. Python // collect and process data from Twitter (maybe collect data every ten mins)
  2. Transmission // transmit data from python to Html & display by Javascript (every ten mins)
  3. Html & Javascript // display data and update information without refreshing

My question is:
I have figured out a way to achieve step1, but I don’t know how to transmit data from python to Javascript. What framework I should try? What file format should I use? What is the easiest approach?

Would anyone help point me in the right direction? Any example or keyword would be really helpful. Thank you much! Haotian