CSV download with jQuery ajax

How can I trigger a csv file download from the ajax jQuery method?

$.ajax({
    url: 'reports/generateCSV',
    method: 'GET',
    data: {report_id: id},
    success: function(data) {
        // what goes here to trigger download?
    {,
    error: function(xhr, status, error) {
       console.error('Error fetching report: ', error);
    },
});

Here is the last bit of my Laravel controller method that streams the csv:

// ...
return response()->streamDownload(function() use ($data) {

     $output = fopen('php://output', 'w');
     foreach($data as $row) {
         fputcsv($output, $row);
     }
     fclose($output);
}, $filename, $headers);

I don’t want to use an href with the full url because I need to fetch the correct csv file depending on what id is selected in a dropdown.
Instead, I’d like to send a GET request which includes the report_id.
Thanks

javascript find value by key in nested object

I am trying to make a function for recursive searching an object by key and valule.
I can’t figure out how to this and tried different examples.
Can anyone help me out?

I have this object:

var menuObj = {
    "mainmenu": [
        {
            "id" : 72,
            "menu_id" :1 ,
            "parent_id" : 0,
            "href" : "{"routeName":"post-page","routeParams":{"slug":"algemene-voorwaarden"}}",
            "permission" : null,
            "hierarchie" : 0,
            "blank" : 0,
            "status" : "published",
            "label" : "Algemene Voorwaarden",
            "children":[]
        },
        {
            "id" : 73,
            "menu_id" : 1,
            "parent_id" : 0,
            "href" : "{"routeName":"post-page","routeParams":{"slug":"privacy"}}",
            "permission" : null,
            "hierarchie" : 1,
            "blank" : 0,
            "status" : "published",
            "label" : "Privacy",
            "children" : [
                {
                    "id" : 101,
                    "menu_id" : 1,
                    "parent_id" : 73,
                    "href" : "{"routeName":"blog"}",
                    "permission" : null,
                    "hierarchie" : 2,
                    "blank" : 0,
                    "status" : "published",
                    "label" : "blog",
                    "children" : [
                        {
                            "id" : 102,
                            "menu_id" : 1,
                            "parent_id" : 101,
                            "href" : "{"routeName":"blog","routeParams":{"category_slug":"categorie-2"}}",
                            "permission" : null,
                            "hierarchie" : 3,
                            "blank" : 0,
                            "status" : "published",
                            "label" : "Categorie 2",
                            "children" : []
                        }
                    ]
                }
            ]
        }
    ]
};

Let say I need something like this:

fnFindKeyValuePair(obj, key, value) {
    // return true/false/null/undefined or found obj
}

Search examples:

fnFindKeyValuePair(menuObj['mainmenu'], 'href', "{"routeName":"blog"}")

Expected result: return true-ish or:

{
    "id" : 101,
    "menu_id" : 1,
    "parent_id" : 73,
    "href" : "{"routeName":"blog"}",
    "permission" : null,
    "hierarchie" : 2,
    "blank" : 0,
    "status" : "published",
    "label" : "blog",
    "children" : [
        {
            "id" : 102,
            "menu_id" : 1,
            "parent_id" : 101,
            "href" : "{"routeName":"blog","routeParams":{"category_slug":"categorie-2"}}",
            "permission" : null,
            "hierarchie" : 3,
            "blank" : 0,
            "status" : "published",
            "label" : "Categorie 2",
            "children" : []
        }
    ]
}

I want the id linked to the button to be deleted from the database

I want to delete the data linked to the relevant id when the trash can is pressed.
i tried to give id to thrash but cant make it up.

<?php

require_once 'connection.php';
require_once 'count.php';  


if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo '<tr>';
        echo '<th scope="row">' . $row["id"] . '</th>';
        echo '<td><img src="' . $row["image_url"] . '" class="user-photo" alt="' . $row["name"] . ' Photo">' . $row["name"] . '</td>';
        echo '<td>' . $row["date"] . '</td>';
        echo '<td>' . $row["role"] . '</td>';
        echo '<td><i class="fa-solid fa-circle" style="color: ' . $row["status_color"] . ';"> </i> ' . $row["status"] . '</td>';
        echo '<td>
                <button>
                    <i class="fa-solid fa-pen" style="color: #0a0a0a;"></i>
                </button>
                <button class="deleteBtn" data-id="<?php echo $row["id"];">
                    <i class="fa-solid fa-trash" style="color: #48b180;"></i>
                </button>
            </td>';
    echo '</tr>';
    }
} else {
    echo "<tr><td colspan='6'>0 sonuç</td></tr>";
}
$conn->close();
?>
<?php
require_once 'connection.php'; 

function urunSilme($id) {
    global $conn; 

    $id = mysqli_real_escape_string($conn, $id);
    $sql = "DELETE FROM formbilgileri WHERE id='$id'";

    if (mysqli_query($conn, $sql)) {
        echo "Veri başarıyla silindi";
    } else {
        echo "Silme işlemi başarısız: " . mysqli_error($conn);
    }
}

if (isset($_GET['id']) && $_GET['id'] !== '') {
    urunSilme($_GET['id']);
} else {
    echo "Geçersiz ID değeri";
}
?>
function deleteRow(id) {
    if (confirm("Bu satırı silmek istediğinizden emin misiniz?")) {
        window.location.href = "delete.php?id=" + id; // Silme işlemini gerçekleştirecek olan PHP dosyanızın adını ve yolunu buraya yazınız
    }
}

I want to delete the data linked to the relevant id when the trash can is pressed.

How to perform SQL query MSSQL server using node.js

I’m using Node.js v21.7.1 and mssql (https://patriksimek.cz) v10.0.2, in my code:

var mssql = require("mssql"), mssqlPool;

Both mysql and mssqlPool are declared outside of any functions and are global to the source file. My connection function:

/**
 * Function:    mssqlConnect
 * Parameters:  cbRoutine, called on successful connection
 *              objParams, array of parameters to pass to cbRoutine
 */
function mssqlConnect(cbRoutine, objParams) {
    try{
        if ( !(mssql && mssql.ConnectionPool) ) {
            throw("Cannot create mssql pool!");
        }
        const objConfig = {database:"TheDBname"
                          ,password:"TheDBpassword"
                           ,options:{encrypt:false
                     ,trustServerCertificate:true}
                              ,pool:{max:1000
                                    ,min:0
                      ,idleTimeoutMillis:30000}
                            ,server:"TheServer"
                              ,user:"TheUser"};
        var pool = mssqlPool;
        if ( pool == undefined ) {
            pool = new mssql.ConnectionPool(objConfig);
        }
        if ( pool ) {
            pool.connect().then(function(pool) {
                if ( cbRoutine ) {
                   var resp = {db:pool
                           ,state:"connected"};
                   cbRoutine({}, resp, objParams);
                }
            });
        }
        mssqlPool = pool;
    } catch(ex) {
        eh.msg({file:cstrThisFile
             ,method:"mssqlConnect"
                 ,ex:ex});
    }
};

All the “The…” strings above have been replaced for sensitivity reasons.

In my code when I want to perform a query I’ve written:

if ( typeof objPool == "object"
  && typeof objPool['state'] == "string"
         && objPool['state'] == "connected"
  && typeof mssql == "object"
  && typeof mssql['Request'] == "function" ) {
    var request = new mssql['Request'](objPool);
    request.query(cstrSQL, cbResults);
}

This results in:

C:wwwnode_modulesmssqllibbaserequest.js:424
    if (this.stream == null && this.parent) this.stream = this.parent.config.stream

TypeError: Cannot read properties of undefined (reading `stream`)
    at Request.query (C:wwwnode_modulesmssqllibbaserequest.js:424:79)
    at C:wwwscriptsdbman.js:229:41
    at C:wwwserver.js:193:20

Can anyone help me with this?

Pass newly defined props to a (functional) component passed as props

Let’s say I have a parent component like the following :

<ParentComponent
    contentComponent={
      <GenericContent
        content={<FormContent
          title="Content Title"
          formComponent={<ChildComponent />}
        />}
      />
    }
/>

Now, in my FormContent component, I would like to pass props to my formComponent which in this example is a ChildComponent but can actually be another component.
However I know that the props I want to pass are always expected in the formComponent component.

const FormContent = ({
  title,
  formComponent,
}: FormContentPropsType) => (
  <>
    <Formik
      enableReinitialize
      validateOnChange={false}
      initialValues={{
        ...formData,
      }}
      validationSchema={SandboxFormValidationSchema}
      onSubmit={sendForm}
    >
      {({
        values,
        setValues,
        errors,
        setErrors,
        handleSubmit,
      }) => (
        <Form>
        {/* Here I would like to use formComponent with the following props :
            formData={values}
            setFormData={setValues}
            formErrors={errors}
            setFormErrors={setErrors}
            handleSubmit={handleSubmit}
        */}
        </Form>
      )}
    </Formik>
  </>

How could I achieve this ?

Wasm data not rendering on html canvas

I made a wasm/js application that should display a array of colors on a html canvas, but nothing is displaying. heres the c code:

void print(int val);

int screen[57600];


int* get_screen(){
        print(1);
        return &screen[0];
}

html:

<html>
    <body>
        <script>
            var importObject = {env: {print: function(arg){
                console.log(arg)
            },
            }}

            const canvas = document.createElement('canvas');
            canvas.width = 360;
            canvas.height = 180;
            document.body.appendChild(canvas);
            const ctx = canvas.getContext('2d');
            
            
            WebAssembly.instantiateStreaming(fetch('fizzbuzz.wasm'), importObject).then((obj) => {
                var offset = obj.instance.exports.get_screen()
                var display = new Uint32Array(obj.instance.exports.memory.buffer, offset, 57600)
                requestAnimationFrame(function(){
                    for (let i = 0; i < display.length; i++) {
                        const uint32 = display[i];
                        
                        // Extract individual bytes (RGBA components)
                        const r = (uint32 >> 24) & 0xFF;
                        const g = (uint32 >> 16) & 0xFF;
                        const b = (uint32 >> 8) & 0xFF;
                        const a = uint32 & 0xFF;

                        // Render pixel onto the canvas
                        const x = i % 360;
                        const y = Math.floor(i / 360);
                        ctx.fillStyle = `rgba(${r},${g},${b},${a})`;
                        ctx.fillRect(x, y, 1, 1);
                    }
                    
                    requestAnimationFrame(arguments.callee)
                })
                
            })
            

            
        </script>
    </body>
</html>

the Makefile:

display.wasm: display.c
    clang --target=wasm32 -emit-llvm -c -S display.c
    llc -march=wasm32 -filetype=obj display.ll
    wasm-ld --export-all --allow-undefined --no-entry -o display.wasm display.o
    wasm2wat display.wasm > display.wat #just for debugging

run_wasm: display.wasm
    python3 -m http.server --bind 127.0.0.1

clean:
    rm -rf display.wasm

there are no errors in the console and no reason(in my opinion) that it shouldn’t work.

i tried(in the c code) to check for value changes from the js and infact the js can change the values(it also works the other way around)

Deconstruct Array into function paramets [duplicate]

How to deconstruct array into function parameters.

For example

let arr=['abc','efc',2,6.5];
let functioncall=(to,from,amount,interest)=>{
return true
}

functioncall(arr)

Something like this?

Function parameter length will be dynamic

It does not decontruct array like this, so I am figuring out the solution.

Msgraph user Invite custom email template

all im trying to figure out is if its possible to make a email template for the msgraph api.
im inviting users to my azure and that sends them a email but its not a very pleasing email.

  public async sendUserInvite(body: {email: [email protected]}) {
    await this.client.api('/invitations').post({
      invitedUserEmailAddress: body.email,
      inviteRedirectUrl: `http://localhost:3000/`,
      sendInvitationMessage: true
    })
  }

this is the api that sends a invite email to the user.
i have searched the whole web but couldnt find anything so hope to get some answers here 😛

Trigger for Start of File Upload

I want to add a JS listener to a shiny app, that gets triggered when a file-upload starts (not when the fileupload is clicked, not when the reactive value in shiny changes, which happens after the file has uploaded, but instead I want it to be triggered when the file is selected from the file menu and “Open” is clicked and the upload actually starts).

The background is, I want to tell the user how long a file-upload (from their computer to my shiny app) took in total.
For this I want to create a JS eventlistener that sets a reactive value to the current time so that I can take the difference later on when the upload has finished.

Note for this example I use alert(1) to figure out when the code is executed, I will use Shiny.setInputValue(id, value); later on.

MWE

library(shiny)

ui <- fluidPage(
  tags$head(tags$script(r"(
    $(document).on("shiny:inputchanged", function(event) {
      if (event.name === "file") {
        alert("shiny:inputchanged file: trigger too late (same as observeEvent(...))!");
      }
    });
  )")),
  fileInput("file", "Upload File") |> 
    tagAppendAttributes(onclick = "alert('onclick file: trigger too early and duplicated?!');")
)

server <- function(input, output, session) {
  observeEvent(input$file, {
    showNotification("File has been uploaded: Trigger too late")
  })
}

shinyApp(ui, server)

Failed Attempts

I played around adding an onclick attribute to the fileInput but this fires before the upload begins (eg when the user needs a long time to select the file to be uploaded, the timing would be off). (fileInput("file", "File") |> tagAppendAttributes(onclick = "alert(1)"))

Also not working, I added JS code that listens to inputchanged, but this fires after the upload is completed.

$(document).on('shiny:inputchanged', function(event) {
  if (event.name === 'file') {
    alert(1);
    console.log('#file has changed');
  }
});

React E-commerce App: Issue with Fetching Product Information Using IDs from Database

Im facing a problem in my React e-commerce app . I need to get “Products ID’s” from a specific user in the DB and after that I need to fetch information from each product ID I have fetched before .Im already have sucess in the first step of receiving the Products ID and storing in the “const resultProductsArray” . Now when I want to “map” this array to fetch the information for each ID my “fetch code” is not running . Im receiving correctly the console.log(‘testing loop’,item ) with the rigth information,but not receiving the console.log(‘resultFetch’,resp). Im not receiving even the console.log from the catch(error) in the map function
Can someone explain the problem and the best way to approach solutions in react ? =)


import EachProductSaved from "./eachProductSaved";
import { Heading, Pane } from "evergreen-ui";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import {faHeart} from '@fortawesome/free-solid-svg-icons'
import axios from "axios";
import { useEffect } from "react";

const MyLikedProducts = () => {
  // const [arrayWishList,setArrayWishList] = useState([])

  useEffect(() => {
   getMySavedProducts()
  },[])

  const getMySavedProducts = async () => {
    try {
      const userId = localStorage.getItem('USER_ID');
      const resp = await axios.get(`http://localhost:3001/getUserData/${userId}`);
      console.log('result',resp)
      const resultProductsArray = resp.data.wishesList;
      console.log('resultProductsArray',resultProductsArray)

      resultProductsArray.map(async (item) => {
        try {
        console.log('testing loop',item)
        const resp = await axios.get(`http://localhost:3001/getProductById/${item}`)
       
        console.log('resultFetch',resp);
      }
      catch(error) {
      console.log('ERROR IN GetDataFromEachProduct FUNCTION')

      }});
      
    }

    catch(error) {
      console.log('ERROR IN GETMYSAVED PRODUCTS FUNCTION',error)
    }
  }



  
  
  

 

  return (
    <Pane
      display="flex"
      flexDirection='column'
      width="65vw"
      flexWrap="wrap"
      marginTop="10vh"
      justifyContent="space-between"
      marginLeft='17vw'
      padding={40}
      borderRadius={8}
      background="white"
      boxShadow="0 1px 4px rgba(0, 0, 0, 0.1)"
    >
        <Pane display='flex'
        alignSelf='center'>
            <FontAwesomeIcon icon={faHeart} size='2x' style={{color:'green'}} />
        <Heading className="my-wishes">Lista de Desejos</Heading>
        </Pane>
      <EachProductSaved productName={"Cesto Cozimneto A Vapor Inox"} />

      <EachProductSaved productName={"Faca Chef Profissional Silicone"} />

      <EachProductSaved productName={"Escorredor de Alimentos em Inox"} />
    </Pane>
  );
};

export default MyLikedProducts;

Vue Draggable Elements Revert Back to Original Position After Drag and Drop

I’m using vuedraggable in a Vue 3 project to allow reordering of elements within an expansion panel. The elements can be dragged and dropped to a new position within the panel, but they revert back to their original positions when released. I suspect that the underlying list used by vuedraggable isn’t being updated when the elements are moved, which causes them to reset to their original positions. Here is the relevant part of my code:

<v-expansion-panels>
  <v-expansion-panel v-for="feature in groupedFeatures" :key="feature.type">
    <v-expansion-panel-title>
      <div>{{ translateFeatureType(feature.type) }}</div>
    </v-expansion-panel-title>
    <v-expansion-panel-text>
      <draggable v-model="feature.details" group="featureGroup" item-key="model_name">
        <template #item="{element, index}">
          <div :key="element.model_name">
            <p><strong>Model:</strong> {{ element.model_name }}</p>
            <p>{{ element.value }}</p>
          </div>
        </template>
      </draggable>
    </v-expansion-panel-text>
  </v-expansion-panel>
</v-expansion-panels>

My imports:

import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';
import draggable from 'vuedraggable';

const route = useRoute();
const features = ref([]);
const messages = ref([]);

The onMounted Function:

onMounted(async () => {
    const threadData = await fetchEmailThreads(route.params.id);
  if (threadData) {
    features.value = threadData.features;
    messages.value = threadData.messages;
  }

And the groupedFeatures Function

const groupedFeatures = computed(() => {
  const featureMap = new Map();
  features.value.forEach(f => {
    if (!featureMap.has(f.type)) {
      featureMap.set(f.type, { type: f.type, details: [] });
    }
    featureMap.get(f.type).details.push({ model_name: f.model_name, value: f.value });
  });
  return Array.from(featureMap.values());
});

This is what the data provided by the server looks like:

{
  "chat_id": 1,
  "features": [
    {
      "model_name": "Vicuna-13B",
      "type": "abstract_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Vicuna-13B",
      "type": "generated_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Vicuna-13B",
      "type": "generated_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Vicuna-13B",
      "type": "order_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Solaris-13B",
      "type": "abstract_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Solaris-13B",
      "type": "generated_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Solaris-13B",
      "type": "generated_feature",
      "value": "---Feature Content---"
    },
    {
      "model_name": "Solaris-13B",
      "type": "order_feature",
      "value": "---Feature Content---"
    }
  ],
  "inst_id": 0,
  "messages": [
    {
      "content": "Message Content...",
      "message_id": 1,
      "sender": "sender1",
      "timestamp": "2022-11-08T14:15:00"
    },
    {
      "content": "Message Content...",
      "message_id": 2,
      "sender": "sender2",
      "timestamp": "2022-11-09T15:45:00"
    }
  ],
  "subject": "Topic"
}

What changes do I need to make so that the elements in the actual list get updated accordingly, and the elements stay in their new positions after being moved?

QR Code Generator Not Working as Expected

I am trying to create a QR Code generator that changes every minute. I have created the following code, but am receiving some errors, and just need some help with that final push to get this done.

<script>
import { useQRCode } from '@vueuse/integrations/useQRCode'
import { ref } from 'vue'

const custID = ref('[email protected]')
let getNow = Date.now()

export default {
  name: 'QRCode Generator',
  data() {
    return {
      text: `${custID.value}?${getNow.value}`
    }
  },
  created() {
    setInterval(this.setQR, 3000)
  },
  methods: {
    getQR() {
      useQRCode(this.text)
    },
    setQR() {
      ;(getNow.value = Date.now()), this.getQR() // Vue Plugin did this, no idea why?
    }
  }
}
</script>

<template>
  <input id="text" v-model="text" type="text" />
  <img :src="this.getQR()" alt="QR Code" />
</template>

<style scoped></style>

Currently I get Uncaught TypeError: Cannot create property 'value' on number for the getNow variable, and the QR Code doesn’t actually display, probably because I am calling it wrong, and some of the data is missing.

The way it is supposed to work is that custID is generated from customer data, so that will be dynamic (more than likely an email address), however the getNow is just a timestamp I am using to modify the data being fed to the BarCode Generator, to change it on a minute by minute basis. However the current interval is set to 3 seconds so I can see it working without the wait…

The two custID and getNow value are combined in the text variable and passed to the QRCode generator to change what is displayed, I separate them with a ?.

I’ve tried a few suggestions from StackOverflow, Google and VueSchool, but no luck.

I have been looking at this for quite a while now, and just need some help tweaking the last piece into place.

Extending Docker image not running on AWS Fargate

I’m trying to run CubeJS on AWS Fargate, if I use the image cubejs/cube:v0.33.33 directly on in a JSON file on Fargate it runs fine, but I need to extend that image so I can include configuration files for my CubeJS instance, here is my docker file:

FROM cubejs/cube:v0.33.33
FROM --platform=linux/amd64 node:lts-alpine
COPY . .
RUN apk update && apk add py-pip
RUN npm install

I run a build on the above and then push it, in AWS Fargate I use that newly pushed repo in the Fargate Json File, but when deploying nothing runs, what am I missing?

Issues with Dynamically Calculating Kinematics in JavaScript using Backend calculations

I am developing a kinematics calculator in JavaScript that sends user input to a server, processes the calculations, and then updates the HTML input fields with the results. The calculator works correctly until any other input is added after an initial calculation.

The calculator is dynamic, so it achieves the calculation through a backend .py file which feeds the frontend with the data. Although the whole computation is simple enough to do in the frontend, I am trying to build up a more complex set of calculators that use server side computations.

Sorry to do this, but here is the entire JS code that is related (I have removed much of the code in regards to significant figures, units etc – but this runs the whole frontend):

`document.addEventListener(‘DOMContentLoaded’, function() {
console.log(‘Document loaded’);

var displacementInput = document.getElementById('inputS');
var initialVelocityInput = document.getElementById('inputU');
var finalVelocityInput = document.getElementById('inputV');
var accelerationInput = document.getElementById('inputA');
var timeInput = document.getElementById('inputT');
var unitSelectors = document.querySelectorAll('.form-select');
var sigFigCheckbox = document.getElementById('sigFigCheckbox');
var clearButton = document.getElementById('clearButton');
var calculatedFields = [];  // Array to track calculated fields

function handleInputChange() {
    console.log('Input changed');
    logInputValues();
    attemptCalculation();
}

function logInputValues() {
    console.log('Current input values:',
        `Displacement: ${displacementInput.value}`,
        `Initial Velocity: ${initialVelocityInput.value}`,
        `Final Velocity: ${finalVelocityInput.value}`,
        `Acceleration: ${accelerationInput.value}`,
        `Time: ${timeInput.value}`);
}

function attemptCalculation() {
    const userInputs = {
        displacement: displacementInput.value.trim(),
        initialVelocity: initialVelocityInput.value.trim(),
        finalVelocity: finalVelocityInput.value.trim(),
        acceleration: accelerationInput.value.trim(),
        time: timeInput.value.trim()
    };

    const data = {
        userInputs: userInputs,
        use_significant_figures: sigFigCheckbox.checked
    };

    console.log('Sending data to server:', data);
    sendRequest(data);
}

function sendRequest(data) {
    console.log('Request data:', JSON.stringify(data));
    fetch('/kinematics-calculator/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        console.log('Processed response data:', data);
        updateInputFields(data);
    })
    .catch(error => console.error('Error:', error));
}

function updateInputFields(response) {
console.log('Updating input fields with response:', response);

// Define a mapping from response field names to input IDs
const fieldToInputId = {
    displacement: 'inputS',
    initialVelocity: 'inputU',
    finalVelocity: 'inputV',
    acceleration: 'inputA',
    time: 'inputT'
};

// Process calculated fields
response.calculatedFields?.forEach(field => {
    const inputId = fieldToInputId[field];
    const inputElement = document.getElementById(inputId);
    if (inputElement) {
        inputElement.value = response[field];
        inputElement.disabled = true; // Lock the calculated field
        console.log(`Updated and locked ${field} (id: ${inputId}) with value ${response[field]}`);
    }
});

// Update other fields
Object.entries(response).forEach(([field, value]) => {
    if (field !== 'calculatedFields' && value !== undefined) {
        const inputId = fieldToInputId[field];
        const inputElement = document.getElementById(inputId);
        if (inputElement && !inputElement.disabled) {
            inputElement.value = value;
            console.log(`Updated ${field} (id: ${inputId}) with value ${value}`);
        }
    }
});
}

function clearInputs() {
    console.log('Clearing inputs');
    [displacementInput, initialVelocityInput, finalVelocityInput, accelerationInput, timeInput].forEach(input => {
        input.value = '';
        input.disabled = false;
    });
    calculatedFields = [];
}

[displacementInput, initialVelocityInput, finalVelocityInput, accelerationInput, timeInput].forEach(input => {
    input.addEventListener('input', handleInputChange);
});

unitSelectors.forEach(selector => {
    selector.addEventListener('change', handleInputChange);
});

sigFigCheckbox.addEventListener('change', handleInputChange);
clearButton.addEventListener('click', clearInputs);

});
`

Currently if I do a computation, let’s say s (displacement) = 110, u (initial velocity) = 0 and t (time) = 5.21 then the backend calculates the remaining two variables, final velocity (v) and acceleration (a).

The inputs all have their “SUVAT” letter attached, eg, inputS, inputU, inputV, inputA, and inputT.

The frontend then sends this data to the HTML to display – and any updates from the user should update the backend to recalculate and then the frontend to display again.

In this case, the user adds the s = 110, u = 0 and then begins to add the t = 5[.21] and as the user inputs the 5, the calculation can be sent forward. The user then proceeds to add the decimal place. But currently, when I do that, the cursor shifts left of the “5” and no decimal place exists. The user continues to add the “21” thinking it is after the decimal place, and instead gets “215” in the inputT variable.

What’s more, the backend has stopped calculating completely.

I’ve run through AI and it’s just circular, this is as far as I have got.

The input of s = 110, u = 0 and then begins to add the t = 5[.21]

Should display:
inputV = 44.0
inputA = 8.8

Then when the user has inputted the “.” after the 5, this should not change anything, but the backend should suggest it is recieving 5.0. Then when the user inputs the “2” after the decimal place the display should update to:
inputV = 42.30769….
inputA = 8.13609….

Then finally, the user will input the “1” after the 5.2 and this should output:
inputV = 42.22648….
inputA = 8.10489….

Instead, the calculation stops after the “5” has been added.