What is the best way to send an email for Contact form with angular 12 application (Back end)

I have been struggling for a while trying to find a solution for a back end where the user can provide and email, name and message form angular side and I would send the email with something like firebase functions…

I tried using the SendGrid and nodeMailer but I am unable to send the email from the clients email ex: [email protected]

If you can provide an example that would be great.

Here is what I have been struggling with, I am bale to send it from my emails but not on behalf of the client.

import * as functions from "firebase-functions";
const sgMail = require("@sendgrid/mail");
const nodemailer = require('nodemailer');
const smtpTransport = require('nodemailer-smtp-transport');
const cors = require('cors');
cors({
  origin: "*"
})


exports.emailMessage = functions.https.onCall((data) => {
    sgMail.setApiKey("mykey");

   const msg = {
    to: '[email protected]',
    from: data.sender,
    subject: `${data.name} sent you email`,
    text: data.message,
    html: `<strong>${data.message}</strong>`,
  }
  sgMail
    .send(msg)
    .then(() => {
      console.log('Email sent');
    })
    .catch((error:any) => {
      console.error(error);
    })
    return{"status": "sucess", data: data};
});

exports.nodeEmailMessage = functions.https.onCall((data) => {

  const asccessKey = '[email protected]';
  const secretKey = 'my oassword';

  const transporter = nodemailer.createTransport(smtpTransport({
    host: "smtp-mail.outlook.com",
    secureConnection: false, // TLS requires secureConnection to be false
    port: 587, // port for secure SMTP
    tls: {
       ciphers:'SSLv3'
    },
    auth: {
        user: asccessKey,
        pass: secretKey
    }}));
   transporter.verify(function (error:any, success:any) {
    if (error) {
      console.log(error);
    } else {
      console.log("Server is ready to take our messages");
    }
  });

   const mailOptions = {
    to: asccessKey,
    from: data.sender,
    subject: `${data.name} sent you a new message`,
    text: data.message,
    html: data.message
  };

 transporter.sendMail(mailOptions, function(error:any, info:any){
    if(error){
     console.log(error.message);
    }
  });
  return {"sucsess": data};
});

Configure imports relative to root directory in create-react-library library

I am trying to setup a react component library with create-react-library (which uses rollup under the hood) and port over our application’s existing component library so that we can share it between applications. I am able to create the library, publish to a private git registry, and consume it in other applications. The issue is that I have had to change all of my imports to relative imports which is rather annoying as I am planning on porting over a large amount of components, hocs and utils.

The entry point of the package is the src dir. Say I have a component in src/components/Text.js and a hoc in hoc/auth.js. If I want to import withAuthentication from hoc/auth.js into my Text component, I have to import it like import { withAuthentication } from "../hoc/auth" but I’d like to be able to import with the same paths I have in my existing application so it’s easy to port over components, like import { withAuthentication } from "hoc/auth"

I have tried a lot of config options, jsconfig.json the same as my create-react-app application, manually building my library with rollup rather then using create-react-library so I’d have more config options but to no avail.

Below are the relevant bits from my package.json as well as my jsconfig.json, any help would be greatly appreciated, I am sure I am not the only person who’s had this issue.

Here’s the package.json

{
  "main": "dist/index.js",
  "module": "dist/index.modern.js",
  "source": "src/index.js",
  "files": [
    "dist"
  ],
  "engines": {
    "node": ">=10"
  },
  "scripts": {
    "build": "microbundle-crl --no-compress --format modern,cjs",
    "start": "microbundle-crl watch --no-compress --format modern,cjs",
    "prepare": "run-s build",
    "test": "run-s test:unit test:lint test:build",
    "test:build": "run-s build",
    "test:lint": "eslint .",
    "test:unit": "cross-env CI=1 react-scripts test --env=jsdom",
    "test:watch": "react-scripts test --env=jsdom",
    "predeploy": "cd example && npm install && npm run build",
    "deploy": "gh-pages -d example/build"
  },
  "peerDependencies": {
    "react": "^16.0.0",
    "react-html-parser": "^2.0.2",
    "lodash": "^4.17.19",
    "@material-ui/core": "^4.11.0",
    "react-redux": "^7.1.1",
    "redux": "^4.0.1",
    "redux-localstorage": "^0.4.1",
    "redux-logger": "^3.0.6",
    "redux-thunk": "^2.3.0",
    "react-router-dom": "^5.1.1",
    "react-dom": "^16.13.1",
    "react-scripts": "^3.4.1",
    "react-svg": "^12.0.0",
    "reselect": "^4.0.0"
  },
  "devDependencies": {
    "microbundle-crl": "^0.13.10",
    "babel-eslint": "^10.0.3",
    "cross-env": "^7.0.2",
    "eslint": "^6.8.0",
    "eslint-config-prettier": "^6.7.0",
    "eslint-config-standard": "^14.1.0",
    "eslint-config-standard-react": "^9.2.0",
    "eslint-plugin-import": "^2.18.2",
    "eslint-plugin-node": "^11.0.0",
    "eslint-plugin-prettier": "^3.1.1",
    "eslint-plugin-promise": "^4.2.1",
    "eslint-plugin-react": "^7.17.0",
    "eslint-plugin-standard": "^4.0.1",
    "gh-pages": "^2.2.0",
    "npm-run-all": "^4.1.5",
    "prettier": "^2.0.4"
  },
  "dependencies": {
    "node-sass": "^7.0.0"
  }
}

and here’s the jsconfig:

{
  "compilerOptions": {
    "baseUrl": "src"
  },
  "include": ["src"]
}

angular formgroup touched not working for checkbox

Angular form for checking form is touched not working with checkbox.
I got !newDeviceGroup.touched = true even though the checkbox is changing its value whenI am clicking. Not sure why?

<form [formGroup]="newDeviceGroup" (ngSubmit)="onSubmit()">
  <div class="row">
    <div class="col">
      <label class="chk-container" for="isNewDevice"
        ><span class="chk-label">Device is work</span>

        <input
          type="checkbox"
          id="isNewDevice"
          name="isNewDevice"
          class="isNewDevice"
          [value]="isDeviceWork"
          [checked]="isDeviceWork == true"
          (change)="onCheckChange($event)"
        />
        <span class="checkmark"></span>
      </label>
    </div>
  </div>
<button type="submit" class="btn btn-primary" id="btnSubmit" [disabled]="!newDeviceGroup.touched">
</form>

play opus data that sending over websocket in Javascript

EXAMPLE DATA FROM WEBSOCKET

{
  audioType: 4,
  whisperTarget: 0,
  sender: 979,
  sequence: 4500,
  lastFrame: false,
  opusData: <Buffer 70 b6 cc 2f 80 c7 79 b7 e0 0c 03 77 fa 51 89 bf 11 69 f0 89 05 cf 33 cc d4 ac e9 37 36 62 fc d8 62 70 eb aa 7d 1f f4 d0 72>,
  decodedData: <Buffer 6f fd 9b fd ee fd 97 fe 2f ff 44 ff 93 ff 28 01 58 03 3e 04 5a 04 48 05 ae 06 1a 08 09 09 75 09 ee 0a 3d 0d 90 0e 9b 0e 0a 0f aa 10 ce 11 e9 11 10 12 ... 910 more bytes>
}

opusData or decodedData PARSING TO JSON

{"type":"Buffer","data":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,1,0,0,0,0,0,0,0,255,255,0,0,1,0,1,0,0,0,255,255,253,255,1,0,4,0,0,0,253,255,254,255,255,255,3,0,4,0,253,255,250,255,255,255,7,0,5,0,248,255,246,255,253,255,248,255,241,255,232,255,224,255,229,255,236,255,238,255,230,255,224,255,238,255,241,255,228]}

My code from server

client.on('voiceData', (voice) => {
  mqtt.publish('icss/stream/play', voice.opusData)
})

My code from client


var node = new BufferQueueNode({
   audioContext: this.visualize.context
})
node.connect(this.visualize.context.destination)
node.write(new Uint8Array(bufferDataFromServer))

if im use new Uint8Array() there are no error. But there are no sound from speaker.
if without new Uint8Array() console from browser showing Unsupported Array Type

How to play opusData or decodedData above in javascript ?
Thank you

I want to modify all elements with the same query

I want to modify all elements that use the same query via a function. (The function is not changed.)

r is read, w is write, and a is write appended to existing content. When using this as get(query).r , .w , .a , I want to make all elements corresponding.

For example, if the class of 3 p tags is html, if you write get(“.html”).w(“hello”) in js, all tags with the class of 3 html should be changed to ‘hello’.

function get(id){
   if (id) {
      if (window === this) {
         return new get(id);
      }
      var query = document.querySelectorAll(id)
      for(var i = 0; i < query.length; i++) {
         this.e = query[i];
         return this;
      }
   } else {
      return "getError : The attribute and value of a tag such as id or class specified by get does not exist. ";
   }
  }
get.prototype = {
   r: function () {
      return this.e.innerText;
   },
   w: function (writing) {
      return this.e.innerText = writing;
   },
   a: function (writing) {
      return this.e.innerText = this.e.innerText += writing;
   }
};
<a href="#" class="test">js</a>
<p href="#" class="test">html</p>
<a href="#" class="test">test</a>
<script>
   get(".test").w("hello")
</script>

How to pass or transfer data from jQuery table into text form or field

In here I’m trying to pass a selected row of data from jQuery table into a text form.

The data source of the jQuery table is from google sheet table.

Once all the data is been displayed in the jQuery table, users able to click on the specific row of data so that the data can be transfer or pass into html text form.

Example: Click on the jQuery table of specific row of data, Supplier Name pass into HTML form Supplier Name text field.

Web Apps

Google Sheet

I’m using click event to trigger CSS animation, why wouldn’t the animation run again when clicked again?

I’m new to web dev, I’m trying to get a better understanding on DOM.

The purpose of my code is to give an element some animation when a click event is triggered. Here’s what I tried:

HTML:

<svg id="svg" width="300" height="300"></svg>
<button id="button">button</button>

CSS:

    svg {
            background-color: lightcyan;
    }

    @keyframes svg-color {
            0% {
                background-color: lightcyan;
            }
            50% {
                background-color: skyblue;
            }
            100% {
                background-color: steelblue;
            }
    }

JS:

    const svg = document.getElementById('svg');
    const button = document.getElementById('button');

    button.onclick = function (){
        svg.style.animation = 'svg-color 5s linear 1 1s';
    }

It works on the first click event. But when I click the button again, the animation won’t run again.

Is this issue due to DOM or the fact that I have set animation-iteration-count as 1 on CSS?

And if I set animation-iteration-count as infinite, is there a way to make the animation goes back to its start state and replay again on click event?

What is the best way to generate a random number based on 3 different probabilities

I am after some help trying to get my head around the logic needed to generate a random number based on 3 different probabilities.

My example is this:
I have an array of objects. Upon each cycle, this array can change in size (some objects added, some removed). Each object has a property called Priority which is set to either High, Medium or Low.

I need an algorithm to pick a random object from the array but based on the Priority. So objects with a High priority will have a higher probability of getting picked than objects with a Low priority.

I took this approach, manually creating an IndexArray and adding the index multiple times based on the priority each cycle and then picking a random index. So, for example:

switch( campaign.Priority ) {
    

    // For high priority campaigns, probability is 6 out of 10
    case 'High':
        for( let i = 0; i < 6; i++ ) {
    
            randomCampaignArray.push( idx );       

        }
        break;   


    // For medium priority campaigns, probability is 3 out of 10
    case 'Medium':
        for( let i = 0; i < 3; i++ ) {     

            randomCampaignArray.push( idx );
        
        }
        break;   


    // For low priority campaigns, probability is 1 out of 10
    case 'Low':
        for( let i = 0; i < 1; i++ ) {        

            randomCampaignArray.push( idx );
        
        }
        break;    


}
    

// Determine a random index from the campaign array
let index = Math.floor( Math.random() * randomCampaignArray.length );
    

// Get a handle to that indexed campaign
_campaign = campaigns[randomCampaignArray[index]];

But then I am left with an Array that looks like [1,1,1,1,1,1,2,2,2,3,3,3,4] which then requires the random value to always be in the low range.

Is there a better and more practical approach to this?

How do I get my code to accept user input and store it in the variable so they can search locations? [duplicate]

So, I am making an application that will allow users to search by city, state code, and country code to find the weather in that area using the OpenWeather API key.

I already stored my API key like so, in the JavaScript file (key is hidden, I’m not sure if it is sensitive material. Better safe than sorry!):

// The stored API key for the Weather Application
var APIKey = "********************************";

So now all I need to do is figure out how to get my code to accept user input to search by city, state code, and country code.

I started by putting in a form where you can type in text, but how do I get the code to take that text and store it in these variables on the .js file?

var city;
var stateCode;
var countryCode;

Here is what my HTML Document looks like so far:

<!DOCTYPE html>
<html>
    <body>
        <nav class="navbar navbar-light bg-light">
            <form class="form-inline">
              <input class="form-control mr-sm-2" type="text" placeholder="Country">
              <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
            </form>
          </nav>

    </body>
</html>

I am not really familiar with JavaScript, but I am determined to get this to work.

Button to clear input value

I am trying to make a button (id=”delete”) that will clear any text entered in my field (id=”input”), I have made a function and button, however after pressing the button nothing happens. Can’t find the issue, the console also doesn’t give any errors. Will be thankful for your assistance.

HTML:

    <span contenteditable="true" ><p id="input"></p></span>
    <button  id="delete">Delete Data</button>

JS:

        const trigger = 
        document.getElementById("delete");
        trigger.value = '';

Thanks!

Cannot call vm on an empty VueWrapper using Vue Test Utils and Jest

I’m trying to write a very basic test to see if a component is mounting properly with the props I provide it. From all the examples I’ve seen this test should run successfully. When I run the test I get an error from vue-test-utils: Cannot call vm on an empty VueWrapper.

Another developer on my team is able to run this test successfully. I have tried deleting my node_modules, completely uninstalling and reinstalling vue-cli, npm, and node.

The test spec file

// To run a Dealer specific test use the following script:
// npm run test:unit -t components/VehicleIdentificationYMMTO.spec

import { shallowMount } from '@vue/test-utils'
import { Vehicle } from '@/entities/vehicle'
import { Dealer } from '@/entities/dealer'
import VehicleIdentificationYMMTO from '@/components/VehicleIdentificationYMMTO'

const createWrapper = ({ propsData }) => {
  return shallowMount(VehicleIdentificationYMMTO, {
    propsData,
  })
}

describe('Testing component with props', () => {
  let wrapper
  let propsData = {
    vehicle: new Vehicle({
      year: '2010',
      make: 'Mazda',
      model: 'Mazda3 Sedan',
      trim: '',
      option: '',
      vin: '',
    }),
    dealer: new Dealer({}),
  }

  beforeAll(() => {
    wrapper = createWrapper({ propsData })
  })

  it('is year stored properly', () => {
    const vehicleContainer = wrapper.findComponent(VehicleIdentificationYMMTO)
    expect(vehicleContainer.vm.vehicle.year).toBe('2010')
  })
})

A screenshot of the error
enter image description here

Here is the shape of the wrapper from console.log

    VueWrapper {
      isDisabled: [Function (anonymous)],
      wrapperElement: HTMLDivElement {},
      __app: <ref *1> {
        _uid: 0,
        _component: {
          name: 'VTU_ROOT',
          render: [Function: render],
          __props: [Array],
          __emits: null
        },
        _props: null,
        _container: HTMLDivElement { _vnode: [Object], __vue_app__: [Circular *1] },
        _context: {
          app: [Circular *1],
          config: [Object],
          mixins: [Array],
          components: [Object],
          directives: {},
          provides: [Object: null prototype] {},
          reload: [Function (anonymous)]
        },
        version: '3.0.11',
        config: [Getter/Setter],
        use: [Function: use],
        mixin: [Function: mixin],
        component: [Function: component],
        directive: [Function: directive],
        mount: [Function (anonymous)],
        unmount: [Function: unmount],
        provide: [Function: provide]
      },
      rootVM: {},
      componentVM: {
        vehicle: [Getter/Setter],
        dealer: [Getter/Setter],
        focusSelect: [Function: bound focusSelect],
        isValidList: [Function: bound isValidList],
        confirmVehicle: [Function: bound confirmVehicle],
        year: [Getter/Setter],
        make: [Getter/Setter],
        model: [Getter/Setter],
        trim: [Getter/Setter],
        option: [Getter/Setter],
        makesList: [Getter/Setter],
        modelsList: [Getter/Setter],
        trimsList: [Getter/Setter],
        optionsList: [Getter/Setter],
        makesLoading: [Getter/Setter],
        modelsLoading: [Getter/Setter],
        trimsLoading: [Getter/Setter],
        optionsLoading: [Getter/Setter],
        loadingMessage: [Getter/Setter],
        defaultMake: [Getter/Setter],
        yearsList: [Getter/Setter],
        confirmButtonDisabled: [Getter/Setter],
        hasOwnProperty: [Function (anonymous)]
      },
      __setProps: [Function: setProps]
    }

I’m out of ideas, any help would be greatly appreciated!

Can’t index items within array

Okay, I have been struggling with this for hours but I still can’t figure this out so if anyone has the solution, thank you!!!

In my code below, I am fetching data from my API (which then fetches data from the Google Places API Nearby Search. Now the API returns a list of about 20 different locations. For each location, I’ve created an object containing the data only I want. Then, I simply push this data to the business array.

(The fetch is in a loop because the Google API only allows you to search for one type of building (cinema, bookstore, bowling_alley, etc…) at a time so I’ve put the fetch in a loop to loop over all of the different types of buildings I want data of)

Now, my issue is that if I try to get the first business of the businesses array businesses[0], it returns undefined. However, what I find even stranger is if I log the businesses array to the console, it displays all the of the business. I have no idea why this is happening so if anyone knows, please do tell and I’ll be very grateful.

getNearbyPlaces = (latitude, longitude, radius, types) => {
  const businesses = [];
  types.forEach(async (type) => {
    await fetch(`${url}/google/places/nearbysearch?lat=${latitude}&lng=${longitude}&rad=${radius}&type=${type}`, {
      method: 'GET',
      body: null
    }).then(response => {
      if (response.ok) {
        return response.json();
      }
      throw new Error('ERROR: Google-Api Nearby Places - response not okay');
    }, networkError => console.log(networkError.message)
    ).then(jsonResponse => {
      if (jsonResponse.results) {
        jsonResponse.results.forEach(result => (
          [...businesses].push({
            id: result.place_id,
            name: result.name,
            address: result.vicinity,
            categories: result.types,
            rating: result.rating,
            reviewCount: result.user_ratings_total
          })
        ))
      }
    });
  });
  console.log(businesses); // logs the list of bsuiness
  console.log(businesses[0]); // logs undefined 
}

Below is the image displayed to the console for when I log the businesses array and businesses[0] (Data has been blocked out for privacy reasons)

Image of what is displayed in the console after execution

Add Third Select Drop Down and Auto Populate Based on Selection

I have made a request form for my group to make it easier for them to request for help desk. At the moment I have two dropdowns – I have the main request dropdown when the user selects from the first dropdown selection it goes to the second dropdown selection for the user to select. I want to add the third dropdown so when the user selects from the second dropdown it opens more selection in the third dropdown based on what category the user has selected for the Second dropdown.

How can i add third select option and then show the input for the selection

$(function() {
    // on page load wrap all select-2 options in span so they cannot be selected without specifying select-1
    $('#select-2 option:not([selected])').wrap('<span/>');
});
// when select-1 is changed, hide all options that do not have the class corresponding to the value of select-1
$('#select-1').change(function() {
    $('#select-2 span > option').unwrap();
    console.log($('#select-1'));
    $('#select-2 option:not(.' + $('#select-1').val() + ', [selected])').wrap('<span/>');
    //console.log($('#select-2').val());
});

$('#select-2').trigger('change');


$(document).ready(function() {
    $("#otherFieldGroupNewacc").hide();
    $("#otherFieldGroupMod").hide();
    $("#otherFieldGroupRes").hide();
    $("#otherFieldGroupRem").hide()
});

//----------------------------------Second Dropdown----------------------------------------------//
$(function() {
    $("#select-2").change(function() {
        if ($(this).val() == "AS400 New Account") {                                 //AS400 New Account //
            $("#otherFieldGroupNewacc").show();
            $('#otherFieldGroupNewacc').attr('required','');
        } else {
            $("#otherFieldGroupNewacc").hide();
            $('#otherFieldGroupNewacc').removeAttr('required');
        }

        if ($(this).val() == "Modify Account") {                                    //AS400 Modify Account //
            $("#otherFieldGroupMod").show();
        } else {
            $("#otherFieldGroupMod").hide();
        }

        if ($(this).val() == "Reset Password") {                                     //AS400 Reinstate Account //
            $("#otherFieldGroupRes").show();
        } else {
            $("#otherFieldGroupRes").hide();
        }

        if ($(this).val() == "Remove Password") {                                     //AS400 Remove Account //
            $("#otherFieldGroupRem").show();
        } else {
            $("#otherFieldGroupRem").hide();
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group">
                    <label>Request Type</label>
                    <select id="select-1" name="select-1" class="form-control w-100" required>
                        <option selected value="">--Select an option--</option>
                        <option value="AS400">AS400</option>                                     <!-- "option-1" -->
                        <option value="EETV">EETV</option>                                       <!-- "option-2" -->
                        <option value="Outlook">Outlook</option>                                 <!-- "option-3" -->
                        <option value="Windows">Windows</option>                                 <!-- "option-4" -->

                    </select>
                    <br/>
                    <label>Choose a Sub-Category</label>
                    <select id="select-2" name="select-2" class="form-control w-100" required>
                        <option selected value="">--Select an option--</option>
                        <option value="AS400 New Account" class="AS400">New Account</option>                  <!-- "option-1a" -->
                        <option value="Modify Account" class="EETV">Modify Account</option>                        <!-- "option-1b" -->
                        <option value="Reset Password" class="Outlook">Reset Password</option>                        <!-- "option-1c" -->
                        <option value="Remove Password" class="Windows">Remove Account</option>                       <!-- "option-1d" -->
                    </select>
                </div>
                <hr>
                <!--AS400 New Account-->
                <div class="form-group" id="otherFieldGroupNewacc">
                    <h2>AS400 New Account</h2><hr>
                    <div class="row">
                            <div class="col-6">
                                <label for="userRequestor">Full Name</label>
                                <input type="text" class="form-control w-100" id="userRequestor" name="userRequestor" placeholder="Type Here..." >
                            </div>
                            <br><br>
                        <div class="col-6">
                            <label for="userTM">Beneficiary (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userTM" name="userTM"placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userEmployee">Employee ID</label>
                            <input type="text" class="form-control w-100" id="userEmployee" name="userEmployee" placeholder="Type Here...">
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="selectJob">New Job Category</label>
                            <select id="selectJob" name="selectJob" class="form-control w-100" placeholder="*Click in box for Job Category List*">
                                <option disabled selected value="">Select an option</option>
                                <option value="NO CHANGE">NO CHANGE</option>
                                <option value="ADMCLK = Admin Clerk">ADMCLK = Admin Clerk</option>
                                <option value="ADMCLK+ = Admin Clerk w/ Manual Book">ADMCLK+ = Admin Clerk w/ Manual Book</option>
                                <option value="ADMMGR = Admin MGR w/ Manual Book">ADMMGR = Admin MGR w/ Manual Book</option>

                            </select>
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="userNewAS400">New AS400 ID</label>
                            <input type="text" class="form-control w-100" id="userNewAS400" name="userNewAS400" placeholder="Type Here...">
                        </div>
                    </div>
                </div>
                <!--Modify AS400 Account-->
                <div class="form-group" id="otherFieldGroupMod">
                    <h2>AS400 Modify Account</h2><hr>
                    <div class="row">
                        <div class="col-6">
                            <label for="userRequestorMod">Requester (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userRequestorMod" name="userRequestorMod"placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userTMMod">Beneficiary (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userTMMod" name="userTMMod" placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userEmployeeMod">Employee ID</label>
                            <input type="text" class="form-control w-100" id="userEmployeeMod" name="userEmployeeMod" placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userAS400Mod">AS400 ID</label>
                            <input type="text" class="form-control w-100" id="userAS400Mod" name="userAS400Mod" placeholder="Type Here...">
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="selectJobsMod">New Job Category</label>
                            <select id="selectJobsMod" name="selectJobsMod" class="form-control w-100" placeholder="*Click in box for Job Category List*">
                                <option disabled selected value="">Select an option</option>
                                <option value="NO CHANGE">NO CHANGE</option>
                                <option value="ADMCLK = Admin Clerk">ADMCLK = Admin Clerk</option>
                                <option value="ADMCLK+ = Admin Clerk w/ Manual Book">ADMCLK+ = Admin Clerk w/ Manual Book</option>
                                <option value="ADMMGR = Admin MGR w/ Manual Book">ADMMGR = Admin MGR w/ Manual Book</option>
                                <option value="DCM = DC Manager">DCM = DC Manager</option>
                                <option value="FM IN = Inbound Funtion Manager">FM IN = Inbound Funtion Manager</option>
                            </select>
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="userNewAS400Mod">New AS400 ID&emsp;<strong>***Leave Blank If No Change***</strong></label>
                            <input type="text" class="form-control w-100" id="userNewAS400Mod" name="userNewAS400Mod" placeholder="Type Here...">
                        </div>
                    </div>
                </div>
                <!--Reinstate AS400 Account-->
                <div class="form-group" id="otherFieldGroupRes">
                    <h2>AS400 Reinstate Password</h2><hr>
                    <div class="row">
                        <div class="col-6">
                            <label for="userRequestorRe">Requester (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userRequestorRe" name="userRequestorRe"placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userTMRe">Beneficiary (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userTMRe" name="userTMRe" placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userEmployeeRe">Employee ID</label>
                            <input type="text" class="form-control w-100" id="userEmployeeRe" name="userEmployeeRe" placeholder="Type Here...">
                        </div>
                        <br><br>
                        <div class="col-6">
                            <label for="userAS400Re">AS400 ID</label>
                            <input type="text" class="form-control w-100" id="userAS400Re" name="userAS400Re" placeholder="Type Here...">
                        </div>
                    </div>
                </div>
                <!--Remove AS400 Account-->
                <div class="form-group" id="otherFieldGroupRem">
                    <h2>AS400 Remove Account</h2><hr>
                    <div class="row">
                        <div class="col-6">
                            <label for="userRequestorRes">Requester (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userRequestorRes" name="userRequestorRes"placeholder="Type Here...">
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="userTMRes">Terminated TM (Full Name)</label>
                            <input type="text" class="form-control w-100" id="userTMRes" name="userTMRes" placeholder="Type Here...">
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="userEmployeeRes">Employee ID</label>
                            <input type="text" class="form-control w-100" id="userEmployeeRes" name="userEmployeeRes" placeholder="Type Here...">
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="userAS400Res">AS400 ID</label>
                            <input type="text" class="form-control w-100" id="userAS400Res" name="userAS400Res" placeholder="Type Here...">
                        </div>
                        <br>
                        <div class="col-6">
                            <label for="hideInputRes">Reason</label>
                            <input type="text" class="form-control w-100" id="hideInputRes" name="hideInputRes" title="Example: Fired, Retired, Leave of Absence, etc..." placeholder="Type Here...">
                        </div>
                    </div>
                </div>

TypeScript generic function, unexpected behavior when generic is a class

class Class {
}
const f0 = <T extends typeof Class> (c:T): T => {
  return c
}
const call0 = f0 (Class) //ok

const f1 = <T extends typeof Class> (c:T): T => {
  const a = new c()
  return a //TS2322: Type 'Class' is not assignable to type 'T'.   'T' could be instantiated with an arbitrary type which could be unrelated to 'Class'.
}
const call1 = f1 (Class)

const f2 = <T extends typeof Class> (c:T):InstanceType<T> => {
  const a = new c()
  return a //TS2322: Type 'Class' is not assignable to type 'InstanceType '.
}
const call2 = f1 (Class)

The argument is typed as T, so why isn’t that acceptable for the return type?

Problem To Stop Click Event Function On Mousedown Event

Hello everyone and dear stackoverflow’s users.

I have the code below, to handle two different events. A Normal Left Click & Holding Down Left Click :

  • When users do a normal click, the number add up to one.
  • When users hold down the left click, the number will adding up while user holding down the mouse and it stops on mouse up.

Also in both events, I send the result number by AJAX and save it on database.

$(document).ready(function() {
    // Normal Click Event
    $('.counter').click(function() {
        var GetNumber = parseInt($(this).text());
        $(this).text(GetNumber + 1);
        
        console.log('Left Click Done!');
        
        // AJAX
        // ...
    });
    
    
    // Hold Click Event
    var ClickStatus = false;
    
    $('.counter').mousedown(function(){
        var Element = $(this);
        var GetNumber = parseInt(Element.text());
        ClickStatus = true;
        
        window.TimeOut = setInterval(function(){
            Element.text(GetNumber++);
        }, 300);

        return false;
    });
    $('.counter').on('mouseup mouseout',function(){
        if (ClickStatus){
            clearInterval(window.TimeOut);
            
            console.log('Hold Left Click Done!');
            
            // AJAX
            // ...
            
            ClickStatus = false;
            return false;
        }
    });
});
    .counter {
        width: 50px;
        height: 50px;
        background-color: #1000ff;
        border-radius: 5px;
        border: 0;
        text-align: center;
        color: #ffffff;
        font-size: 24px;
    }
    .counter:hover {
        opacity: 0.7;
        cursor: pointer;
    }
    p {
        font-family: tahoma;
        font-size: 12px;
        margin-top: 20px;
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="counter" title="Left Click / Hold Left Click">1</button>
<p>Click On Above Button, Or Hold Left Click To See The Result.</p>

The problem is that both events are firing together! I don’t want it, I need to trigger just one of them at time, which means I need to run the events separately.
Also I have tried some solutions like “return false“, “e.stopPropagation()“, “e.stopImmediatePropagation()“, “e.preventDefault()” & …, read the same topics on the forum (like this, or this) but unfortunately none of them worked for me and I couldn’t find something helpful about it. I’m so confused and have no idea guys.

Kindly please help me to fix this, give me your ideas. In advance many thanks for your helpful helps. <3