Dealing with floating point precision in power function

I am having trouble coming up with a class to deal with floating point precision, specifically the pow program which generates the nth power of a number (the base or exponent can be negative or exist as a decimal). I have viewed others’ explanations and copied a lot of code, however the function still generates results with floating point errors:

class Core{
    to_fraction(decimal, tolerance = 0){
        var skipped = false; 
        if (isNaN(decimal) || isNaN(tolerance)) return; 
        for (var denominator = 1; (decimal * denominator) % 1 != 0; denominator++) if (Math.abs(Math.round(decimal * denominator) / denominator - decimal) < tolerance){skipped = true; break}; 
        if (skipped) return {numerator: Math.round(decimal * denominator), denominator: denominator, difference: Math.round(decimal * denominator) / denominator - decimal};
        if (!skipped) return {numerator: decimal * denominator, denominator: denominator};
    }

    dplaces(a){
        if (a.toString().split(".").length == 1) return 0; 
        return a.toString().split(".")[1].length; 
    }
}


class Correct{
    cf(a, b){
        return Math.pow(10, Math.max(core.dplaces(a), core.dplaces(b))); 
    }

    divide(a, b){
        var _cf = this.cf(a, b); 
        return (a * _cf) / (b * _cf); 
    }

    multiply(a, b){
        var _cf = this.cf(a, b); 
        return (a * _cf) * (b * _cf) / (_cf * _cf); 
    }

    subtract(a, b){
        var _cf = this.cf(a, b); 
        return ((a * _cf) - (b * _cf)) / _cf; 
    }

    add(a, b){
        var _cf = this.cf(a, b); 
        return ((a * _cf) + (b * _cf)) / _cf; 
    }

    pow(a, b){
        var fraction = core.to_fraction(b); 
        
        for (var count = 0, result = 1; count < fraction.numerator; count++) result = this.multiply(result, a); 
        
        result = result ** (1 / fraction.denominator); // Da problems starts here

        return result; 
    }

    factorial(number){
        if (number % 1 || !(Math.abs(number) >= 0)) return NaN; 
        if (number > 170) return Infinity;
        var result = 1;
        while (number > 1) result *= number--;
        return result;
    }
}

const core = new Core(), correct = new Correct(); 

console.log(correct.pow(7.154840569262962e+21, 1 / 5));

It seems that the problem starts on the second filled line of the pow function within the Correct class, however I cannot find or think of a method to avoid or change the stuff on that line.

This is extremely frustrating and rather unfortunate. Please suggest an alternative method (preferably in JavaScript or Node js) to achieve such effects or modify that line. Thank you!

JQuery DataTable Cell InnerHTML Update Issue

Thanks for opening this question and help me!

I am using JQuery DataTable and want to update the InnerHTML in each cell. The reason is that that:

Original data in each DataTable Cell is plain text and hard to read. For example:

[ { "wikidataid": "Q142" }, { "wikidataid": "Q55" }, { "wikidataid": "Q39" }, { "wikidataid": "Q34" }, { "wikidataid": "Q36" }, { "wikidataid": "Q20" } ]

So, I want to create an unordered list so the data could be show in a formatted way instead of a plain text and override the innerHTML of dataTable cells.

This is the code I wrote:

        var table = $('#queryTable').DataTable();
        var data = table.rows().data();
        console.log(data.length);

        //Loop each row
        data.each(function (value, index) {
            //Loop each column
            for(var i=0; i<value.length; i++){
                // only column 2 and 3 are the data we want to format
                if (i != 2 && i != 3){
                    continue;
                }
                var content = JSON.parse(value[i])

                var ul=document.createElement('ul');
                for (var k = 0; k < content.length; ++k) {
                    var li=document.createElement('li');
                    li.setAttribute("class", "list");

                    li.innerHTML = "WikiDataId: " + content[k].wikidataid;   // Use innerHTML to set the text
                    if (content[k].attributes != null) {
                        for (var j = 0; j < content[k].attributes.length; ++j){
                            var ulsub=document.createElement('ul');
                            ulsub.value = content[k].attributes[j].changedtype;
                            var liName=document.createElement('li');
                            liName.innerHTML = content[k].attributes[j].name + ": " + content[k].attributes[j].value;
                            ulsub.appendChild(liName);
                            li.appendChild(ulsub);
                        }
                    }
                    ul.appendChild(li);
                }
                // console.log(index);
                // console.log(i);
                // console.log(ul);
                //table.cell(index, i).data(ul.html()).draw();

                table.cell(index, i).node().innerHTML = null;
                table.cell(index, i).node().appendChild(ul);

                console.log(table.cell(index, i).node());
            };
        });
    });

However, after I run the above code, although the data is formatted into unordered list. But the data in the each row’s cells are not updated correctly. For example, the 1st row’s data contains the 3rd rows data, the 2rd row’s data contains the 5th rows data, the 3rd row’s data contains the 6th rows data and etc.

I am not sure if the way I update inner html is correct. Could anyone help here? Thanks so much!

Are hashes in the names Javascript and CSS files used for integrity checking?

Many websites use hashes in Javacript and CSS file’s name. For example, this page, as of writing, uses a file referred to with URL .../stacks.min.js?v=b0f9a80d741d. Other sites just place a short hash in the file’s name: main.abcd123.js

  • Is this used automated integrity checking? For example, when the browser loads stacks.min.js?v=b0f9a80d741d, does is verify that a hash or digest of this file matches b0f9a....
  • Does this pattern have a name?

How to know if the user is dropping the file on the defined location?

On this application, the user can drag and drop a file on the specified location. Let say here:

<div id="dropZone" style="width: 200px; height: 100px;"></div>

However, we noticed that no matter where the file is drop, the webpage will process it. Here is an example taken online https://jsfiddle.net/oL2akhtz/. There is a place to drop the file, but no matter where you leave it, it will stay. How to know if the user is droping the file in the right place? Or how do you disable the cursor if the user is not droping the file where it should be?

Getting ERR_SSL_PROTOCOL Error when trying to send a post request to my Node.js Server in ReactJs

I am creating a DHL API for checking shipment rates. I have uploaded my Node.js Server using putty and it is running correctly when I enter my IP address and port number.

In development, there are no erros or issues and I get back the response and get the rates back from the form I have set up for my users.

but in Production, when I upload my website to Hostinger I get this error ” Failed to load resource: net::ERR_SSL_PROTOCOL_ERROR”

In production, it sends my post request with HTTPS instead of HTTP. And even when I change the HTTPS to HTTP in the browser I get another error saying “Cannot GET /api/dhl”

Here are some images to help make it more clear:

The Errors.

enter image description here

When my website submits the post request with HTTPS instead of HTTP.

enter image description here

When I manually change the URL from HTTPS to HTTP

enter image description here

What am I doing wrong? Why is this happening and how can I fix it?

Here is my code:

const express = require('express');
const port = 3001
app.post('/api/dhl', (req, res) => {

const accountNum = req.body.accountNum

const fromCountriesCode = req.body.fromCountriesCode
const fromCountriesCapital = req.body.fromCountriesCapital
const fromCity = req.body.fromCity
const fromPostalCode = req.body.fromPostalCode

const toCountriesCode = req.body.toCountriesCode
const toCountriesCapital = req.body.toCountriesCapital
const toCity = req.body.toCity
const toPostalCode = req.body.toPostalCode

const weight = parseInt(req.body.weight)
const plannedShippingDate = req.body.date

const len = "5"
const width = "5"
const height = "5"
const isCustomsDeclarable = 'false' 
const unitOfMeasurement = 'metric'

console.log(weight)
console.log(fromCountriesCode)
console.log(toCountriesCode)

console.log(fromCity)
console.log(toCity)

var options = { method: 'POST',
url: 'https://express.api.dhl.com/mydhlapi/rates',
headers: 
 { 'postman-token': '',
   'cache-control': 'no-cache',
   authorization: 'Basic myauthkey',
   'content-type': 'application/json' },
body: 
 { customerDetails: 
    { shipperDetails: 
       { postalCode: fromPostalCode,
         cityName: fromCity,
         countryCode: fromCountriesCode,
         addressLine1: '0' },
      receiverDetails: 
       { postalCode: toPostalCode,
         cityName: toCity,
         addressLine1: '0',
         countryCode: toCountriesCode }
         },
   accounts: [ { typeCode: 'shipper', number: 'my account number' } ],
   plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//Might need to change later
   unitOfMeasurement: 'metric',
   isCustomsDeclarable: true,
   monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
   requestAllValueAddedServices: false,
   returnStandardProductsOnly: false,
   nextBusinessDay: false,
   packages: [ { weight: weight, dimensions: { length: 5, width: 5, height: 5 } } ] },
json: true };



request(options, function (error, response, body) {
    if (error) throw new Error(error);
    res.send(body)
    console.log(body);
  });
});


//Start the Server
app.listen(port, () => {
  console.log(`Server running at :${port}/`);
});

My Check-Rates File:
const getRateEstimate = () => {

axios.post('http://MY_IP:3001/api/dhl', {

    fromCity,
    fromCountriesCapital,
    fromCountriesCode,
    fromPostalCode,

    toCountriesCapital,
    toCountriesCode,
    toPostalCode,
    toCity,

    weight,

 }).then(response => {

        console.log(response)
        setData(response.data);

 }).catch(e => {

     console.log(e)
 });

}

How did I get 111 npm downloads already?

So 2 days ago I published my first npm package
A simple library to trim and join audio files.
https://www.npmjs.com/package/aviatojs
The weird thing is I already got 111 downloads somehow.
I havent shared this package with anyone
Neither have I documented anything. The readme is literally blank
.
could this be a mistake??
Edit: This might like look like I am trolling or something, but I assure I am genuinely curious about what’s going on. Please dont downvote this question for no reason.

is it possible to custom the splitChunks output file folder when using webpack 5 to package

I am using webpack "webpack": "^5.67.0" splitChunks to package the google chrome extension js and cs file, this is my configuration right now.

optimization: {
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'commons1',
          test: /.(scss)$/,
          chunks: 'all',
          enforce: true
        },
        commons1: {
          name: 'commons1',
          chunks: 'all',
          minChunks: 1,
          test(module,chunks){
            for (const chunk of module.chunksIterable) {
              if (chunk.name && /(popup|content)/.test(chunk.name)) {
                   return true;
              }
            }
            return false;
          }
        },
        commons2: {
          name: 'commons2',
          chunks: 'all',
          minChunks: 1,
          test(module,chunks){
            for (const chunk of module.chunksIterable) {
              if (chunk.name && /(options|commons1)/.test(chunk.name)) {
                   return true;
              }
            }
            return false;
          }
        },
        commons3: {
          name: 'commons3',
          chunks: 'all',
          minChunks: 1,
          test(module,chunks){
            for (const chunk of module.chunksIterable) {
              if (chunk.name && /(bg|commons2)/.test(chunk.name)) {
                   return true;
              }
            }
            return false;
          }
        },
      }
    }
  },

I want to generate different type of file in different dist subfolder, for example, I want the popup.js and popup.css file should be /dist/popup/popup.js and /dist/popup/popup.css. What should I tweak my config to make it work like that? I am search the splitChunks docs but did not found any suggestions. Is it possible to do like that? the output folder structure I want may look like this:

-- dist
---- popup
------ popup.js
------ popup.css
---- bg
---- options

this is the current file structure and look like chaos:

enter image description here

post.frontmatter.title.filter is not a function

I want to filter some posts from data.I try to use this code but it don’t work.It run out post.frontmatter.title.filter is not a function

{posts.map((post, index) => (
 post.frontmatter.title.filter(name=>name.includes('J')).map(filterdtitle=>(
<li>{filterdtitle}</li>
))
))}

I get the data of posts by getStaticProps like this and then I pass the posts to the function.The posts include title.I can get by {post.frontmatter.title},it is working.

 const { data: frontmatter } = matter(markdownWithMeta)

    return {
      slug,
      frontmatter
    }
  })

I want to know that how make it work.Thank you

How to maintain javascript dependencies to solve “MorphSVGPlugin is not defined”?

I used these plugin/libraries/js-files in my project:

<script src="https://use.fontawesome.com/15d0f12843.js"></script>
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
  <script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.2.6/gsap.min.js"></script>
  <!-- main js -->
  <script src="js/main.js"></script>
  <!-- style switcher js -->
  <script src="js/style-switcher.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.19.1/TweenMax.min.js"></script>
  <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/16327/MorphSVGPlugin.min.js"></script>     
  <script src="js/game.js"></script> 

If I remove Gsap 3.2.6 and babel js libraries from code the MorphSVGPlugin works fine. But I can’t use them together. How can I resolve the issue. Also, please keep it in your kind consideration that I am a beginner in Javascripts

How to get a JavaScript number as a string using Node-API

I’m building a Node.js addon using Node-API.

The logic has been simplified as below,

Use pass js array into the addon and get some filtered array as the output.

Inside the addon, the algorithm will skip any empty strings and false values.

Below is the code snipped of the usage. The whole addon available here: https://replit.com/@dinindu/node-api-addon-compact#addon.c

const addon = require("bindings")("addon.node");

const array = ['0', false, '', {a:'1'}, '2', "str"];
console.log(addon.compact(array)); // expected output: ['0', {a:'1'}, '2', "str"]
// addon.c
#include <assert.h>
#include <node_api.h>
#include <stdlib.h>

#define DECLARE_NAPI_METHOD(name, func) 
  { name, 0, func, 0, 0, 0, napi_default, 0 }

#define DECLARE_WITH_STATUS_CHECK(size, name, func)                       
  napi_property_descriptor func##_desc = DECLARE_NAPI_METHOD(name, func); 
  status = napi_define_properties(env, exports, size, &func##_desc);      
  assert(status == napi_ok);

static napi_value compact(napi_env env, napi_callback_info info) {
  size_t argc = 1;
  napi_value args[1];
  napi_get_cb_info(env, info, &argc, args, NULL, NULL);
  
  uint32_t length;
  napi_get_array_length(env, args[0], &length);

  napi_value output_array;
  napi_create_array_with_length(env, NAPI_AUTO_LENGTH, &output_array);

  uint32_t result_index = 0;
  for (size_t i = 0; i < length; i++) {
    napi_value value;
    napi_get_element(env, args[0], i, &value);

    napi_valuetype type;
    napi_typeof(env, value, &type);

    if (type == napi_boolean) {
      bool result;
      napi_get_value_bool(env, value, &result);
      if (result == false) continue;
    }

    char* str_buffer;
    bool str_found = false;
    if (type == napi_string) {
      size_t str_buffer_size;
      napi_get_value_string_utf8(env, value, NULL, 0, &str_buffer_size);

      str_buffer = (char*)calloc(str_buffer_size + 1, sizeof(char));
      size_t str_result;
      napi_get_value_string_utf8(env, value, str_buffer, str_buffer_size, &str_result);

      str_found = true;
      if (*str_buffer == '') {
        free(str_buffer);
        str_found = false;
        continue;
      }
    }

    napi_set_element(env, output_array, result_index, value);
    result_index++;
    if (str_found) free(str_buffer);
  }
  
  return output_array;
}

static napi_value Init(napi_env env, napi_value exports) {
  napi_status status;
  DECLARE_WITH_STATUS_CHECK(1, "compact", compact)
  return exports;
}

NAPI_MODULE(NODE_GYP_MODULE_NAME, Init)

What I don’t understand is, the expected output should contain all values except false and ''. But it seems to skip '0' and '2' as well, which means number characters. I tested it by adding another number after it ('01') and then it works.

Why this is happening? Why C is skipping single character numbers? And how can I get my expected output?

Thanks in advance.

How to deduct value continuously on a for loop

I have an input field encased in a for each loop which causes to replicate them into 8 input fields, now I am using for loop to put values in the said input fields and I’m trying to figure out how to deduct the extra payment row by row (example: I have given the input field a value of 3000 which is replicated x8, if I set a payment of 4000 the dbalance will be 0 then I will deduct the extra 1000 to the mbalance, same with the instance if I set a higher payment, deduct the extra value to the next row… here’s my current code:

<tr>
    <td>Down Payment</td>
    <td><input type="text" class="damount" name="damount" id="damount" style="border: none" value="{{ $down_payment }}"></td>
    <td><input type="text" class="dbalance" name="dbalance" id="dbalance" style="border: none" value="0"></td>
</tr>
@foreach($dates as $d)
<tr>
    <td>{{ $d['dates'] }}</td>
    <td><input type="text" class="dmonthly" name="dmonthly[]" id="dmonthly" style="border: none" value="{{ $monthly }}"></td>
    <td><input type="text" class="mbalance" name="mbalance[]" id="dbalance" style="border: none" value="0"></td>
</tr>
@endforeach

<tr>
    <td>
        <div>Need to pay:</div>
        <input type="text" name="down" id="down" value="{{ $down_payment }}" readonly>
        </div>
    </td>
</tr>
<tr>
    <td>
        <div>Payment:</div>
        <div><input type="text" name="pay" id="pay" /></div>
    </td>
</tr>

function calculate() {
  var due = {{ $due }};
  var monthly = {{ $monthly }};
  var down = parseFloat($('#down').val());
  var payment = parseFloat($('#payment').val());
  var total = (down - payment);
  var deducted = (monthly - total);

  if(total > 0) {
    document.querySelector("#dbalance").value = parseFloat(total.toFixed(2));
    const collection = document.getElementsByClassName("mbalance");
    for (let i = 0; i < collection.length; i++) {
        collection[i].value = parseFloat(monthly.toFixed(2));
    }
  } else {
    document.querySelector("#dbalance").value = 0;
    const collection = document.getElementsByClassName("mbalance");
    for (let i = 0; i < collection.length; i++) {
        collection[i].value = parseFloat(deducted.toFixed(2));
    }
  }
}

Error: Invalid hook call in Apollo useLazyQuery , useMutation, useQuery

As long as the line with useLazyQuery in App.js (code below) is removed, it will display simple “HELLO” message (working well), otherwise, I got the below error message

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app

App.js

import React, { useState } from "react";
import ReactDOM from "react-dom";
import { syncUser as syncRecord } from "./components/util";
import { useLazyQuery } from "@apollo/client";

export default function App(props) {
  console.log("React.version1", React.version);
  console.log("ReactDOM.version1", ReactDOM.version);
  const [syncUser] = useLazyQuery(syncRecord, {}); //CULPRIT LINE
  const [hasToken, setHasToken] = React.useState(false);
  return <div className="App">HELLO</div>;
}

A few things I have checked

  1. React version & React DOM version are same in index.js & App.js i.e. 16.13.1
  2. I don’t think I broke Hooks rule — useState working well in the same sample code App.js
  3. npm ls react returns long tree with multiple react (but other than react at root tree — the rest (part of the library) are using same [email protected] deduped

Apollo Client version

    "@apollo/client": "^3.3.15",
    "@apollo/react-hooks": "^4.0.0",

How do you place the selection of a drop down menu and an input field into an equation?

What am I doing

I have a picture framing calculator which caters to calculating the appropriate matting for someone’s picture framing needs.


How I’m doing it

Here’s the code snippet:

* {
  margin: 0;
  padding: 0;
  font-family: 'Lato', sans-serif;
}

/*Fieldset and legend */

fieldset {
  margin: 2em 0;
  padding: 1em 2em;
  border: solid 1px #ccc;
  border-radius: 6px;
  min-width: P 200px;
}

legend {
  font-size: 1.25em;
  padding: 0 .25em;
  color: #999;
}


/* Labels */

label {
  display: block;
  margin-top: 1em;
}

.checks label {
  margin-top: 0;
}

label:first-of-type {
  margin-top: 0;
}

/* Select */

select {
  padding: .5em;
  border: solid 1px #999;
  background-color: #D3D3D3;
  font-family: 'Lato', sans-serif;
  font-size: .8em;
}

#wff, #hff, #wpf, #hpf {
  margin-left: 1em;
  margin-top: auto;
  margin-bottom: auto;

  }
  
  body {
    background-color: white;
    padding: 2em;
    height: 100%;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: center;
     justify-content: center;
  }

  body > sides {
    background-color: whitesmoke;
    margin: 0 .25em; /* for gap */
    width: 60%;
  }


/* Inputs and textarea */

input {
  padding: .5em;
  border: solid 1px #999;
  background-color: #D3D3D3
}

input[type="number"],
input[type="text"] {
  width: 10em;
  background-color: #D3D3D3
}

textarea {
  min-height: 8em;
  min-width: 100%;
  padding: .5em;
  border: solid 1px #999;
  background-color: #D3D3D3
}

/* radio buttons and checkboxes */

.checks {
  margin-bottom: 1em;
}

.checks p {
  margin-bottom: 0;
}

input[type="checkbox"]+label,
input[type="radio"]+label {
  display: inline-block;
  padding-top: 0;
  margin-top: 0;
}

input[type="radio"] {
  margin-left: 1.5em;
  margin-right: 0;
}

input[type="radio"]:first-of-type {
  margin-left: 0;
}

#height {
  text-align: left;
  margin-top: 250px;
  margin-left: 4px;
}


/* Submit Button */

input[type="button"] {
  padding: .5em 1em;
  border-radius: 6px;
  background-color: #333;
  color: #fff;
  font-family: 'Lato', sans-serif;
  font-size: .8em;
}


/* Large screen rules */

@media screen and (min-width: 430px) {
  legend {
    font-size: 1.75em;
  }
  fieldset {
    width: 40%;
    min-width: 320px;
    margin: auto;
  }
  .checks label {
    display: inline-block;
    padding-top: .5em;
    margin-top: 0;
    margin-right: .5em;
  }
}
<!DOCTYPE html>

<html lang="en">

    <head>
    
        <meta charset="UTF-8">

        <meta name "viewport" content="width=device-width,

        initial-scale=1.0">

        <title>I Was Framed - Calculator</title>



        <link href="https://fonts.googleapis.com/css?family=Lato:300,400,400i,700,900&display=swap" rel="stylesheet">

        <link rel="stylesheet" href="style.css">

    </head>

<body>
    <sides>
        
<section>
    
<form id="frm1" action="form_action.asp">

<fieldset>

<legend>

I Was Framed Calculator

</legend>



<label for="frameWidth">Frame Width:</label><input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="frameWidth" id="wf" required><select name="frameWidth" id="wff">
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option> 
                <option value=".9375">15/16</option>
</select>

<label for="frameHeight">Frame Height:</label><input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="hf" id="hf" required><select name="hff" id="hff" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select>



<label for="pictureWidth">Picture Width:</label><input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="wp" id="wp" required><select name="wpf" id="wpf" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select>

<label for="pictureHeight">Picture Height:</label><input type="number"onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="hp" id="hp" required><select name="hpf" id="hpf" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select><br>

<label for="matOverlap">Mat Overlap:</label><select name="o" id="o" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select>

    <br>


<br>
<input type="button" onclick="calc()" value="Calculate" name="cmdCalc"/>

</fieldset>

</form>

</section>

<script src="https://unpkg.com/[email protected]/index.js"></script>

<script>

function calc()

{

    var wf = document.getElementById('wf').value
    wf = parseInt(wf)

    var wff = document.getElementById('wff').value
    wff = parseInt(wff)
    
    var hf = document.getElementById('hf').value
    hf = parseInt(hf)

    var hff = document.getElementById('hff').value
    hff = parseInt(hff)
    
    var wp = document.getElementById('wp').value
    wp = parseInt(wp)

    var wpf = document.getElementById('wpf').value
    wpf = parseInt(wpf)
    
    var hp = document.getElementById('hp').value
    hp = parseInt(hp)

    var hpf = document.getElementById('hpf').value
    hpf = parseInt(hpf)
    
    var o = document.getElementById('o').value
    o = parseFloat(o)
    
    if (!wf || !hf|| !wp || !hp || !o) {
        alert('Fields are missing!')
        return 
    }


   var width = (1/2)*(hf-hp+o);
   var height = (1/2)*(wf-wp+o);

   document.getElementById('width').innerHTML = new Fraction(width).toString();
   document.getElementById('height').innerHTML = new Fraction(height).toString();

   document.getElementById('rectangle').scrollIntoView({ behavior: 'smooth'})

}

</script>
    </sides>
    <sides>
        
<center>
    <div style="width:400px;height:50px;;border:5px solid #000; margin-top: 20px; margin-bottom: 50px;padding-bottom:75%;background-color:gray" id="rectangle">
        <center>
            <div id="width"></div>
        </center>
    
        <div id="height"></div>
    </div>
</center>
    </sides>
</body>

</html>

Here’s what I have

The current equations are:

  • var width = (1/2)*(hf-hp+o);

  • var height = (1/2)*(wf-wp+o);

My code solves the current calculation without the selection of the drop down menu. This image shows a correct output without changing the equations which doesn’t include a drop down selection on the right hand side of the input:

Current equations solving correctly


The Problem

I am trying to alter my equations to include my input and a selected value combined. I updated the code snippet from another answer which I was instructed combined the two fields. And I updated both equations with how I think it should go, but now receive the error NaN NaN/1. And here is the updated code from that:

* {
  margin: 0;
  padding: 0;
  font-family: 'Lato', sans-serif;
}

/*Fieldset and legend */

fieldset {
  margin: 2em 0;
  padding: 1em 2em;
  border: solid 1px #ccc;
  border-radius: 6px;
  min-width: P 200px;
}

legend {
  font-size: 1.25em;
  padding: 0 .25em;
  color: #999;
}


/* Labels */

label {
  display: block;
  margin-top: 1em;
}

.checks label {
  margin-top: 0;
}

label:first-of-type {
  margin-top: 0;
}

/* Select */

select {
  padding: .5em;
  border: solid 1px #999;
  background-color: #D3D3D3;
  font-family: 'Lato', sans-serif;
  font-size: .8em;
}

#wff, #hff, #wpf, #hpf {
  margin-left: 1em;
  margin-top: auto;
  margin-bottom: auto;

  }
  
  body {
    background-color: white;
    padding: 2em;
    height: 100%;
    display: -webkit-flex;
    display: flex;
    -webkit-justify-content: center;
     justify-content: center;
  }

  body > sides {
    background-color: whitesmoke;
    margin: 0 .25em; /* for gap */
    width: 60%;
  }


/* Inputs and textarea */

input {
  padding: .5em;
  border: solid 1px #999;
  background-color: #D3D3D3
}

input[type="number"],
input[type="text"] {
  width: 10em;
  background-color: #D3D3D3
}

textarea {
  min-height: 8em;
  min-width: 100%;
  padding: .5em;
  border: solid 1px #999;
  background-color: #D3D3D3
}

/* radio buttons and checkboxes */

.checks {
  margin-bottom: 1em;
}

.checks p {
  margin-bottom: 0;
}

input[type="checkbox"]+label,
input[type="radio"]+label {
  display: inline-block;
  padding-top: 0;
  margin-top: 0;
}

input[type="radio"] {
  margin-left: 1.5em;
  margin-right: 0;
}

input[type="radio"]:first-of-type {
  margin-left: 0;
}

#height {
  text-align: left;
  margin-top: 250px;
  margin-left: 4px;
}


/* Submit Button */

input[type="button"] {
  padding: .5em 1em;
  border-radius: 6px;
  background-color: #333;
  color: #fff;
  font-family: 'Lato', sans-serif;
  font-size: .8em;
}


/* Large screen rules */

@media screen and (min-width: 430px) {
  legend {
    font-size: 1.75em;
  }
  fieldset {
    width: 40%;
    min-width: 320px;
    margin: auto;
  }
  .checks label {
    display: inline-block;
    padding-top: .5em;
    margin-top: 0;
    margin-right: .5em;
  }
}
<!DOCTYPE html>

<html lang="en">

    <head>
    
        <meta charset="UTF-8">

        <meta name "viewport" content="width=device-width,

        initial-scale=1.0">

        <title>I Was Framed - Calculator</title>



        <link href="https://fonts.googleapis.com/css?family=Lato:300,400,400i,700,900&display=swap" rel="stylesheet">

        <link rel="stylesheet" href="style.css">

    </head>

<body>
    <sides>
        
<section>
    
<form id="frm1" action="form_action.asp">

<fieldset>

<legend>

I Was Framed Calculator

</legend>



<label for="frameWidth">Frame Width:</label><input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="frameWidth" id="wf" required><select name="frameWidth" id="wff">
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option> 
                <option value=".9375">15/16</option>
</select>

<label for="frameHeight">Frame Height:</label><input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="hf" id="hf" required><select name="hff" id="hff" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select>



<label for="pictureWidth">Picture Width:</label><input type="number" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="wp" id="wp" required><select name="wpf" id="wpf" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select>

<label for="pictureHeight">Picture Height:</label><input type="number"onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" step="any" min="0" name="hp" id="hp" required><select name="hpf" id="hpf" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select><br>

<label for="matOverlap">Mat Overlap:</label><select name="o" id="o" required>
    <option value="none" selected="selected"> -- choose one --</option>
    <option value=".0">0</option>
        <option value=".0625">1/16</option>
            <option value=".0125">1/8</option>
                <option value=".1875">3/16</option>
                <option value=".25">1/4</option>
                <option value=".3125">5/16</option>
                <option value=".375">3/8</option>
                <option value=".4375">7/16</option>
                <option value=".50">1/2</option>
                <option value=".5625">9/16</option>
                <option value=".625">5/8</option>
                <option value=".6875">11/16</option>
                <option value=".75">3/4</option>
                <option value=".8125">3/16</option>
                <option value=".875">7/8</option>
                <option value=".9375">15/16</option>
</select>

    <br>


<br>
<input type="button" onclick="calc()" value="Calculate" name="cmdCalc"/>

</fieldset>

</form>

</section>

<script src="https://unpkg.com/[email protected]/index.js"></script>

<script>

function calc()

{

    var wf = document.getElementById('wf').value
    wf = parseInt(wf)

    var wff = document.getElementById('wff').value
    wff = parseInt(wff)
    
    var hf = document.getElementById('hf').value
    hf = parseInt(hf)

    var hff = document.getElementById('hff').value
    hff = parseInt(hff)
    
    var wp = document.getElementById('wp').value
    wp = parseInt(wp)

    var wpf = document.getElementById('wpf').value
    wpf = parseInt(wpf)
    
    var hp = document.getElementById('hp').value
    hp = parseInt(hp)

    var hpf = document.getElementById('hpf').value
    hpf = parseInt(hpf)
    
    var o = document.getElementById('o').value
    o = parseFloat(o)
    
    if (!wf || !hf|| !wp || !hp || !o) {
        alert('Fields are missing!')
        return 
    }


   var width = (1/2)*(hf+hpf-hp+hpf+o);
   var height = (1/2)*(wf+wff-wp+wpf+o);

   document.getElementById('width').innerHTML = new Fraction(width).toString();
   document.getElementById('height').innerHTML = new Fraction(height).toString();

   document.getElementById('rectangle').scrollIntoView({ behavior: 'smooth'})

}

</script>
    </sides>
    <sides>
        
<center>
    <div style="width:400px;height:50px;;border:5px solid #000; margin-top: 20px; margin-bottom: 50px;padding-bottom:75%;background-color:gray" id="rectangle">
        <center>
            <div id="width"></div>
        </center>
    
        <div id="height"></div>
    </div>
</center>
    </sides>
</body>

</html>

However, this is an image of the result when I attempt the new equations:

Calculator with script changes


What I’ve tried

I’ve tried the following equations:

  1. var width = (1/2)*(hf+hpf-hp+hpf+o); and var height = (1/2)*(wf+wff-wp+wpf+o);
  2. var width = (1/2)*((hf+hpf)-(hp+hpf)+o); and var width = (1/2)*((hf+hpf)-(hp+hpf)+o);

Run a function on multiple html elements having same class name

***Working
When i right click on the chat item then it run a function test_delete(e) for target element and context menu shows and store chat id in variable x.

when we click on delete then it shows the id of target chat.
works fine for now.

Problem
If i click on a chat 10 times or more than 1 time
and then i click on delete from context menu then the delete button function returns chat id per click on chat

but i want it return only single chat id

Example: if i click on chat 10 time but click delete button 1 time then it return chat id of last target chat 10 times
1 want it return chat id only 1 time

if You dont understant my question then run snippet and view console
How can i fix this problem….






<!--Context Menu-->    
 <div class="TestClass" id="m">
       <p  class="innerP0">
           <input id="dummy" type="text" value="">
       <a  class="context-item" id="Tex">Delete</a>
       <a class="context-item" id="EDIT">Edit...</a>
       <a class="context-item" id="forward">Forward</a>
       <a class="context-item" id="copy">Copy</a>
       <a class="context-item" id="copy">Select</a>
      </p>
    </div>
    <p id="dM"></p>




<!--Html Elements of same class name-->

<div class="to123f">
   <div class="from Text_chat" oncontextmenu="return false;">
        <input class="chatId" type="hidden" value="263">
        <span class="chatf_time">2022-01-16 21:32:37</span>
        <p id="message_detail" class="chat_text fromuser">fgdfg</p>
    </div>
</div>
<div class="to123f">
   <div class="from Text_chat" oncontextmenu="return false;">
        <input class="chatId" type="hidden" value="264">
        <span class="chatf_time">2022-01-16 21:32:37</span>
        <p id="message_detail" class="chat_text fromuser">dffdg</p>
    </div>
</div>
<div class="to123f">
   <div class="from Text_chat" oncontextmenu="return false;">
        <input class="chatId" type="hidden" value="266">
        <span class="chatf_time">2022-01-16 21:32:37</span>
        <p id="message_detail" class="chat_text fromuser">
asad
</p>
    </div>
</div>

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

    //CHAT CONTEXT MENU FOR Desktop

    function test_delete(e){
    let menu = document.getElementById('m');
    let mes = document.getElementById('dM');

        menu.style.display = "block";
     y = e.currentTarget;
        let check_user = e.currentTarget.className;
        if (check_user == 'to') {
          //  alert("You Click on " + check_user);
        }
       // console.log(e.currentTarget.className);
        x = y.querySelector('input').value;
         // console.log(e);
          if(e.pageX == undefined){
            var posX = e.changedTouches[0].pageX;
            var posY = e.changedTouches[0].pageY;
          }
          else{
            var posX = e.pageX;
            var posY = e.pageY;
          }
         
        

        var menuWidth = menu.offsetWidth;
        var menuHeight = menu.offsetHeight;
        var totalWidth = window.innerWidth;
        var totalHeight = window.innerHeight;

        if ((totalWidth - posX) < menuWidth) {
            menu.style.left = posX - menuWidth + "px";
            //console.log("ifX = ");
        } else {
            menu.style.left = posX + 5 + "px";
           //  console.log("elseX = ");
        }
        if ((totalHeight - posY) < menuHeight) {
            menu.style.top = posY - menuHeight + "px"
              //   console.log("ifY = ");
        } else {
            menu.style.top = posY + "px";
           //  console.log("elseY = ");
        }
        var contextItem = document.getElementsByClassName('context-item');
        var contextLength = contextItem.length;
        var i= 0;
        for(i;i<contextLength;i++){
            contextItem[i].addEventListener('click', function(){menu.style.display='none';
            
        })
            
        }
        window.onclick = function(e) {
            if(!e.target.matches.menu){
                menu.style.display = "none";
            }
           
          
            
    }
    //console.log(inner);
        menu.querySelector('#Tex').addEventListener("click", function() {
            
            let data = `id=${x}`;
            console.log(data);
        
        });


    }

    //CHAT CONTEXT MENU FOR TOUCH DEVICES
    function mobileContext(){
     var chatBody = document.getElementsByClassName('from');
    // console.log('ChatBody = '+chatBody);
    var chatBodyLength = chatBody.length;
    var i=0;
     var delay = 500;
     var holdStarter = null;
     var holdActive = false;
     for(i;i<chatBodyLength;i++){
        chatBody[i].addEventListener('touchstart' , TouchStart);
        chatBody[i].addEventListener('touchend' , TouchEnd);
        chatBody[i].addEventListener('auxclick' , test_delete);
     }

     

     function TouchStart(){
        holdStarter = setTimeout(function() {
            holdStarter = null;
            holdActive = true;
        }, delay);
     }

     function TouchEnd(e){
        if (holdStarter) {
            clearTimeout(holdStarter);
            // run click-only operation here
            // console.log('Clicked!');
        }else
        if(holdActive == true){
          //  console.log('Hold Active');
            
            holdActive = false;
            test_delete(e);
        }
     }
    }
    mobileContext();


<!-- language: lang-css -->

    .TestClass {
      /*  left: -89px; */
        position: absolute;
        width: 140px;
        
        background: #ffffff;
        z-index: 1000;
        /* border: 1px solid green; */
        box-shadow: 4px 4px 10px -3px #00000024;
        display: ;
        border: 1px solid #dbdee7;
    }

    p.innerP0 a:last-child {
        border: 0;
    }

    p.innerP0 a {
        text-decoration: none;
        color: gray;
        padding: 5px 15px;
        font-size: 11px;
        border:none; 
        cursor: pointer;
        display: flex;
        align-items: center;
        justify-content: space-between;
    }
    p.innerP0 {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        height: 100%;
        padding: 4px 0px !important;
    }

    p.innerP0 a:hover {
        background: #c9c9c9;
    }

    #dM {
        padding: 5px 15px;
        border-radius: 20px;
        background: #4849a1;
        color: #fff;
        font: 300 12px/1 'open sans';
        width: fit-content;
        text-align: center;
        position: fixed;
        left: 0;
        right: 0;
        bottom: -40px;
        margin: auto;
        transition: .5s ease;
    }
    .to123f {
        display: flex;
        justify-content: flex-end;
        position: relative;
    }
    .to123f p {
        padding: 12px 10px;
    }
    .to123f p {
            font-size: 13px;
            -webkit-user-select: none; -webkit-touch-callout: none; -moz-user-select: none; -ms-user-select: none; user-select: none;
            user-select: none;
        }
        .from{
        background:gray;
        margin-bottom:20px;
        }

<!-- language: lang-html -->

    <!--Context Menu-->    
     <div class="TestClass" id="m">
           <p  class="innerP0">
           <a  class="context-item" id="Tex">Delete</a>

           <a class="context-item" id="EDIT">Edit...</a>

           <a class="context-item" id="forward">Forward</a>

           <a class="context-item" id="copy">Copy</a>

           <a class="context-item" id="copy">Select</a>

          </p>

        </div>

        <p id="dM">
</p>

    <!--Html Elements of same class name-->

    <div class="to123f">
       <div class="from Text_chat" oncontextmenu="return false;">

            <input class="chatId" type="hidden" value="263">

            <span class="chatf_time">2022-01-16 21:32:37</span>

            <p id="message_detail" class="chat_text fromuser">fgdfg</p>

        </div>

    </div>

    <div class="to123f">

       <div class="from Text_chat" oncontextmenu="return false;">

            <input class="chatId" type="hidden" value="264">

            <span class="chatf_time">2022-01-16 21:32:37</span>

            <p id="message_detail" class="chat_text fromuser">dffdg</p>

        </div>
    </div>
    <div class="to123f">

       <div class="from Text_chat" oncontextmenu="return false;">

            <input class="chatId" type="hidden" value="266">
            <span class="chatf_time">2022-01-16 21:32:37</span>
            <p id="message_detail" class="chat_text fromuser">
asad
</p>
        </div>
    </div>