jQuery Change click function to mouse over on desktop and click on mobile

The menu I’m working on should wrap overflowing menu items into a dropdown list similar to the one in this link (How to wrap overflowing menu items into dropdown list to create a responsive navigation menu?). However, I need assistance switching the click function on desktop computers to mouseover, and the default click function on mobile devices. If a user clicks anywhere outside of the dropdown’s button on a mobile device, it should automatically close. How’s that possible?

Codepen:
https://codepen.io/bootstrap007/pen/GRPMdgm

var h = 30;
var val = 0;

$('.click').click(function() {
  if ($('ul').hasClass('show')) {
    $('ul').removeClass('show');
    $('ul li.menu-item').removeClass('drop')
    return;
  }
  val = 0;
  $('ul li.menu-item').each(function() {
    var of = $(this).offset().top - $('ul').offset().top;
    if ( of > 20) {
      $(this).addClass('drop');
      $(this).css('top', 'calc(100% + ' + val + 'px)');
      val += h;
    }
    $('ul').addClass('show');
  })
})

React configuration with Virtualbox live update

I have react in VM that looking for build directory and it is accessible on http://dev.test.co/.
I’m developing the react and npm run start live update the browser, but it is availble on localhost:3000.

If I want to watch changes on VM I need to build react, it will be sync with shared storage to VM, and then changes on VM http://dev.test.co/ affected.
how can I setup to have live update on VM to prevent Build React App each time for any changes ?

How to replace variable in string in react

I have string

const message = "component="${component.name}" and id=${id}";

I have data

const data = {"id": 101, "component": { "name": "Shiv" }};

How to parse this string message, so that “${component.name}” is replaced by “Shiv” and “id” with 100,

I tried using handlebars.js but it is not compatible with my react setup

Can svg blobs contain hrefs?

I am building a website that displays content from a server (text, images, html, pdf, etc..). As the client does not know ahead of time what the content type is, it downloads the content, checks the content type, creates a blob url, and then renders it using the blob url in the src attribute. This saves having to download the content twice (once to check content type, another when the browser renders the content from src).

Some of the images are svg files that have hrefs to other files on the server. These hrefs do not work when the svg is src’ed by blob url. The hrefs work perfectly fine when src’ed by the normal url.

For example, if you had the following svg available at https://examplehost.com/sample.svg

<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <image href="https://upload.wikimedia.org/wikipedia/en/a/a9/Example.jpg" width="100%" height="100%"/>
</svg>

You could easily embed the svg on your webpage using the url in the src attribute

<img src="https://examplehost.com/sample.svg">

If, however, you convert the svg to a blob first

var response = await fetch("https://examplehost.com/sample.svg");
var blob = await response.blob();  
const blobUrl = URL.createObjectURL(blob);

The href embedded in the svg will not work

<img src="blobUrl_goes_here">

JSFiddle here

why does my javascript code is not working in HTML block editor of wordpress

I have been trying to run this code for two hours and have always got the same error, i.e., no output but when i preview it before publishing is all good and working fine. I am using the generate theme plugin for my wordpress site i have provided the code below.

code:

<!DOCTYPE html>
<html>
<head>
    <title>Average Grade Calculator</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
            margin: 0;
            padding: 0;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        #inputForm {
            max-width: 400px;
            margin: 0 auto;
            padding: 20px;
            background-color: #fff;
            box-shadow: 0 0 20px rgba(0, 0, 0, 0.2);
            border-radius: 10px;
            border: 2px solid #333;
        }

        table {
            width: 100%;
            margin-bottom: 10px;
            border-collapse: collapse;
        }

        th, td {
            padding: 10px;
            text-align: center;
        }

        th {
            background-color: #333;
            color: #fff;
        }

        input[type="number"] {
            width: 100%;
            padding: 8px;
            border: 1px solid #ccc;
            border-radius: 4px;
        }

        button {
            display: block;
            margin: 0 auto;
            background-color: #333;
            color: #fff;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
        }

        button:hover {
            background-color: #555;
        }

        #resultBox {
            border: 2px solid #333;
            padding: 10px;
            text-align: center;
            margin-top: 20px;
            border-radius: 5px;
        }
    </style>
</head>
<body>
    <h1>Average Grade Calculator</h1>

    <form id="inputForm">
        <table>
            <tr>
                <th>Grade</th>
                <th>Weight</th>
            </tr>
            <!-- Input fields for grade and weight -->
            <tr>
                <td><input type="number" id="grade1" step="0.01" placeholder="Assignment Grade"></td>
                <td><input type="number" id="weight1" placeholder="Assignment Weight"></td>
            </tr>
        </table>
        <button type="button" onclick="addInputRow()">Add Row</button>
        <button type="button" onclick="calculateAverageGrade()">Calculate</button>
    </form>

    <div id="resultBox">
        <p id="result"></p>
    </div>

    <script>
        let rowCount = 1;

        function addInputRow() {
            rowCount++;
            const table = document.querySelector('table');
            const newRow = table.insertRow(-1);

            const gradeCell = newRow.insertCell(0);
            gradeCell.innerHTML = `<input type="number" id="grade${rowCount}" step="0.01" placeholder="Assignment Grade">`;

            const weightCell = newRow.insertCell(1);
            weightCell.innerHTML = `<input type="number" id="weight${rowCount}" placeholder="Assignment Weight">`;
        }

        function calculateAverageGrade() {
            // Initialize variables to store the sum of (Grade * Weight) and the sum of weights.
            let sumGradeWeight = 0;
            let sumWeights = 0;

            // Loop through each grade and weight input and calculate the sums.
            for (let i = 1; i <= rowCount; i++) {
                const grade = parseFloat(document.getElementById(`grade${i}`).value);
                const weight = parseFloat(document.getElementById(`weight${i}`).value);

                // Check if the grade and weight are valid numbers.
                if (!isNaN(grade) && !isNaN(weight)) {
                    sumGradeWeight += grade * weight;
                    sumWeights += weight;
                }
            }

            // Calculate the average grade.
            if (sumWeights !== 0) {
                const averageGrade = sumGradeWeight / sumWeights;

                // Display the result.
                document.getElementById("result").innerHTML = `Average Grade: ${averageGrade.toFixed(2)}`;
            } else {
                // Handle the case where the sum of weights is zero.
                document.getElementById("result").innerHTML = "Please enter valid grade and weight values.";
            }
        }
    </script>
</body>
</html>

I want someone to solve my query immediately, please.

Building a connect 4 game, but I’m having trouble figuring out how to remove the classes that represent users moves on reset

I am building a connect 4 game using JavaScript, right now users can play the game as expected and the program checks for the winner and stops the game once player 1 or player 2 wins the game.
This part of the game seems to be working as expected: there are two players, represented by two different colors (in this case red and yellow) and the game goes from one color to another.
My issue is with restarting the game. I have a restart button, which resets the timer, but I can’t figure out how to remove the red and yellow pieces from the game board.

More specifically, I think my issue is that I can’t figure out how to remove a class from a div I created inside a function.

I created each tile inside the function I used to set up the game board:

function setGame() {
    board = [];
    currColumns = [5, 5, 5, 5, 5, 5, 5]
    
    for (let r = 0; r < rows; r++) {
        let row = []
        for (let c = 0; c < columns; c++) {
            row.push(' ');
            let tile = document.createElement('div');
            tile.id = r.toString() + '-' + c.toString()
            tile.classList.add('tile');
            tile.addEventListener('click', setPiece);
            document.getElementById('board').append(tile);
            console.log(tile)
        }
        board.push(row)
    }
}

Then I used tile again to identify each individual tile and add the red or yellow color when the user clicks the board

function setPiece() {
    // if there is a winner, the function does nothing so pieces cannot be set
    if (gameOver) {
        return;
    }

    let coords = this.id.split('-');
    let r = parseInt(coords[0]);
    let c = parseInt(coords[1]);

    r = currColumns[c];
    if (r < 0) {
        return
    }

    board[r][c] = currentPlayer;
    let tile = document.getElementById(r.toString() + '-' + c.toString());
    // console.log(tile)
    if (currentPlayer == playerRed) {
        tile.classList.add('red-piece')
        clearInterval(intervalID)
        currentPlayer = playerYellow
    } else {
        tile.classList.add('yellow-piece')
        currentPlayer = playerRed
    }
    // setInterval(setTimer, 1000);

    r -= 1;
    // console.log(r)
    currColumns[c] = r;

    checkWinner()
}

Once a winner is found, the click event that allows users to add pieces is removed.
I have a restart button that will restart the timer and allow users to add pieces to the board, but what I can’t figure out is how to remove the pieces from the board. I know that my board is made up of tiles, and that the filled in tiles have either a class of ‘red-piece’ or ‘yellow-piece’ but I can’t figure out how to remove them.

Maintaining Selection State in KendoGrid Across Page Transitions

In kendoGrid, when the page loads, Assuming I already have the selected productID. So, when the grid is loaded and the data is bound, it selects the corresponding row.

The problem arises when I uncheck the product ID on the first page, then navigate to the second page to check the data. Upon returning to the first page, I notice that the previously unchecked product ID has become checked again.

I want the grid to fetch and display only the IDs that I have actively selected, ensuring that my selections persist across different pages and actions. Appreciate your help..

DEMO IN DOJO

$("#grid").kendoGrid({
  dataBound: function(e){
    var grid = this;
    var rows = grid.items();
    $(rows).each(function(e) {
      var row = this;
      var dataItem = grid.dataItem(row);
      if (selectedProductIDs.includes(dataItem.ProductID)) {
        grid.select(row);
      }                    
    });
  },
  dataSource: dataSourceTEST,
  pageable: true,
  persistSelection: true,
  sortable: true,
  change: function(e) {
    console.log("The selected product ids are: [" + this.selectedKeyNames().join(", ") + "]");
  },
  columns: [{
    selectable: true,
    width: "50px"
  },
            {
              field: "ProductName",
              title: "Product Name"
            },
            {
              field: "UnitPrice",
              title: "Unit Price",
              format: "{0:c}"
            },
            {
              field: "UnitsInStock",
              title: "Units In Stock"
            },
            {
              field: "Discontinued"
            }
           ]
});

How to sort the columns values in ag-grid

I have displayed a set of data in the ag-grid, and the data is of complex type, i.e. values are displayed in the grid using custom cell renderer. I have given the options “sortable = true” but still columns are not getting sorted, even I am not able to get value in comparator() function.

Please help me with sorting the column values.

const sampleRowData = [
    {
        "field_name": "<some_value>",
        "field_value": "tgb34378eee847334894",
        "original_field_value": "tgb34378eee847334894",
        "_id": "1",
        "_img_id": "300",
    },
    {
        "field_name": "<some_value_1>",
        "field_value": "tgb34378eee847334895",
        "original_field_value": "tgb34378eee847334895",
        "_id": "2",
        "_img_id": "310",
    },
]

I want to sort the column values.

Find the null value inside dynamic array list and get the value of this parent

My “spreads” have dynamic array number inside (different numbers per events). Each of the arrays have this alt_line_id: null. I want to get which array object does have this value null value and then display the “home & away” values to my html.

My example array:

"events": [
    "periods": {
        "num_0": {
            "line_id": 2250607026,
            "number": 0,
            "cutoff": "2023-09-18T23:15:00Z",
            "period_status": 1,
            "money_line": {
                "home": 2.5,
                "draw": null,
                "away": 1.598
            },
            "spreads": {
                "3.0": {
                    "hdp": 3.0,
                    "alt_line_id": null,
                    "home": 2.0,
                    "away": 1.909,
                    "max": 30000.0
                },
                "5.5": {
                    "hdp": 5.5,
                    "alt_line_id": 36582376056,
                    "home": 1.625,
                    "away": 2.39,
                    "max": 30000.0
                },
                "5.0": {
                    "hdp": 5.0,
                    "alt_line_id": 36582376059,
                    "home": 1.662,
                    "away": 2.32,
                    "max": 30000.0
                },
                "4.5": {
                    "hdp": 4.5,
                    "alt_line_id": 36582376062,
                    "home": 1.694,
                    "away": 2.26,
                    "max": 30000.0
                },
                "4.0": {
                    "hdp": 4.0,
                    "alt_line_id": 36582376064,
                    "home": 1.746,
                    "away": 2.19,
                    "max": 30000.0
                },
            },
        },
    },
]

In my array above, the “spreads” object have dynamic list of array and for example “3.0” is the one that have "alt_line_id": null. Once it found, I want to get the name of this object so that I can get the “home” & “away” by using calling it like this: obj.events[i].periods.num_0.spreads['**my dynamic array here**'].home

Here’s my code

var xhr = new XMLHttpRequest();
xhr.open("GET", "odds.json", true);
xhr.getResponseHeader("Content-type", "application/json");
xhr.withCredentials = true;

xhr.onload = function() {
    const obj = JSON.parse(this.responseText);

    var out = "";
    for (let i = 0; i < 1; i++) {

        out += '<tr>'
                + '<td class="home_team">'+ obj.events[i].home +'</td>'
                + '<td class="home_moneyline">'+ obj.events[i].periods.num_0.money_line.home +'</td>'
                + '<td class="home_spreads">'+ obj.events[i].periods.num_0.spreads['my dynamic array here'].home +'</td>'
                + '<td class="home_totals">'+  +'</td>'
                + '<td class="home_totalgame">'
                    + '<div>Over <span class="htg_over">'+ obj.events[i].periods.num_0.team_total.home.over +'</span></div>'
                    + '<div>Under <span class="htg_under">'+ obj.events[i].periods.num_0.team_total.home.under +'</span></div>'
                + '</td>'
            + '</tr>'
            + '<tr>'
                + '<td class="away_team">'+ obj.events[i].away +'</td>'
                + '<td class="away_moneyline">'+ obj.events[i].periods.num_0.money_line.away +'</td>'
                + '<td class="away_spreads">'+ obj.events[i].periods.num_0.spreads['my dynamic array here'].away +'</td>'
                + '<td class="away_totals">'+  +'</td>'
                + '<td class="away_totalgame">'
                    + '<div>Over <span class="atg_over">'+ obj.events[i].periods.num_0.team_total.away.over +'</span></div>'
                    + '<div>Under <span class="atg_under">'+ obj.events[i].periods.num_0.team_total.away.under +'</span></div>'
                + '</td>'
            + '</tr>';
    }
    document.getElementById("odds-list").innerHTML = out;
}

Как заставить все ссылки открыться в новой вкладке? код на php [closed]

Помогите пожалуйста.Есть код посиковой системы на рhp,

    <div class="mainResultsSection">
        <?php
        if($type == "sites") 
        {
            $resultsProvider = new SiteResultsProvider($con);
            $pageSize = 20;
        }
        else if($type == "images")
        {
            $resultsProvider = new ImageResultsProvider($con);
            $pageSize = 30;
        }

        $numResults = $resultsProvider->getNumResults($term);

        echo "<p class='resultsCount'>$numResults results found</p>";
        echo $resultsProvider->getResultsHtml($page, $pageSize, $term);
        ?>
             

    </div>

не знаю как заставить выдачу открываться в новой вкладке.а мне это очень важно.

все что я нашла совсем не об этом

How to Correctly Format Y-Axis Data in ECharts Line Graph with React/Typescript/Javascript for Specific Decimal and Digit Grouping

Question:

I am working on a React project where I am using ECharts to display a line graph with time-series data. My data consists of two lines that represent different calculations related to income (“ingreso”) in USD and ARS (Argentinian Pesos).

Here’s a snippet of my code that’s relevant to the issue:

    // Function for Line 1
    const cuantoDolarValiaElSueldo = (ingresos: ExtendedIngresosRow[]) => {
      return ingresos.map((entry) => {
        let amountInUSD;
        if (entry.currency === "ARS") {
          amountInUSD = entry.cantidad / (entry.adolarblueenesemomento ?? 1);
          console.log(
            `Converted ${entry.cantidad} ARS to ${amountInUSD} USD using rate ${entry.adolarblueenesemomento}`
          );
        } else {
          amountInUSD = entry.cantidad; // Already in USD
          console.log(`Amount already in USD: ${amountInUSD}`);
        }
        const formattedAmount = amountInUSD.toLocaleString("de-DE", {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        });
        console.log(`Formatted amount: ${formattedAmount}`);
        return [entry.timestamp_with_time_zone, formattedAmount];
      });
    };

    // Function for Line 2
    const cuantoValeElDolarEnSueldoAhora = (
      ingresos: ExtendedIngresosRow[],
      currentRate: number
    ) => {
      return ingresos.map((entry) => {
        let amountInUSD;
        if (entry.currency === "ARS") {
          amountInUSD = entry.cantidad * currentRate;
          console.log(
            `Converted ${entry.cantidad} ARS to ${amountInUSD} USD using current rate ${currentRate}`
          );
        } else {
          amountInUSD = entry.cantidad; // Already in USD
          console.log(`Amount already in USD: ${amountInUSD}`);
        }
        const formattedAmount = amountInUSD.toLocaleString("de-DE", {
          minimumFractionDigits: 2,
          maximumFractionDigits: 2,
        });
        console.log(`Formatted amount: ${formattedAmount}`);
        return [entry.timestamp_with_time_zone, formattedAmount];
      });
    };

    const PuntosCuantoDolarValiaElSueldo = cuantoDolarValiaElSueldo(
      fetchedIngresosDelMes
    );
    const PuntosCuantoValeElDolarEnSueldoAhora = cuantoValeElDolarEnSueldoAhora(
      fetchedIngresosDelMes,
      currentBlueDollarRate
    );

    let myChart = echarts.getInstanceByDom(chartRef.current);

    if (!myChart) {
      myChart = echarts.init(chartRef.current, "dark");
    }

    const seriesList: echarts.SeriesOption[] = [
      {
        type: "line",
        name: "Cuánto valía el sueldo en dólares",
        data: PuntosCuantoDolarValiaElSueldo,
        encode: {
          x: 0,
          y: 1,
        },
      },
      {
        type: "line",
        name: "Cuánto vale el sueldo en dólares ahora",
        data: PuntosCuantoValeElDolarEnSueldoAhora,
        encode: {
          x: 0,
          y: 1,
        },
      },
    ];

    const option: EChartsOption = {
      animationDuration: 10000,
      title: {
        text: "Ingresos en pesos que se devaluaron",
      },
      tooltip: {
        order: "valueDesc",
        trigger: "axis",
      },
      xAxis: {
        type: "time",
        nameLocation: "middle",
      },
      yAxis: {
        name: "Lo que acumulaste",
      },
      grid: {
        right: 140,
      },
      series: seriesList,
    };

    myChart.setOption(option);
  }, [fetchedIngresosDelMes, isLoading]);

Problem:

I am facing three issues:

  1. Formatting: I am trying to change the format of the y-axis values to use “commas” for decimals and “dots” for digit grouping. I’ve used toLocaleString with the “de-DE” locale, but the graph is not rendering the y-axis correctly.

  2. Graph Rendering: The x-axis, title, and description of the graph are visible, but the y-axis and the data points (dots) are not rendering. I suspect it might be related to the data formatting.

  3. Y-Axis and Dots: Despite the x-axis and other elements rendering correctly, the y-axis and the dots representing the data points are not being displayed.

What I’ve Tried:

I’ve added console logs to debug the data and formatting, but I am still unable to identify the issue.

Question:

How can I correctly format the y-axis data to use “commas” for decimals and “dots” for digit grouping, and ensure that the graph, y-axis, and data points (dots) render correctly?

why to use ng-idle lib to detect user idle time, if we can write our own code in js to detect the user inactivity using key and mouse events

I am able to detect the user idle time using simple mouse and key event.as below.

@HostListener('window:keydown', ['$event'])
@HostListener('window:mousedown', ['$event'])
@HostListener('window:mousewheel', ['$event'])
refreshUserState() {`enter code here`
 clearTimeout(this.userActivity);
 this.setTimeout();
}

is this will cause any performance issue and advantage of using ng-idle over this approach?

HTML5CSS3JavaScript Image Editing – Once image is edited, what file type downloads to browser for save as JPG or PNG

It’s been years since I did anything like this, so I’m rusty. My impression is that when the image that is loaded, edited, and saved as JPG or PNG or Base64, everything is done by the browser (for example, there is no PHP or other backend code). Thus, there should be nothing effecting my traffic limit (regardless of the image size) since everything is done locally.

Simple question: Am I correct?

Thank you

Can google apps script handle Braintree (Paypal) transactions as a back end server?

I have a client end payment form that i cannot figure out how to use Google Apps Script and Braintree to process a payment successfully. I am trying to have a modal show up when the user submits the form, have it say “processing, please wait….” for a couple of seconds while the modal sends the form data to google apps script and waits for a response. Once the modal gets a response, it will show the appropriate response with an OK button to close the modal. For the life of me, i cant figure out how to integrate Braintrees process to complete a transaction. What i understand is that Braintree needs to have a Merchant ID, Public ID and Private ID, which i have, in the google apps script. The client side needs to get a Client Key, use that key to send a nonce to google apps script, and google apps script will then pass that nonce to Braintree and wait for a response. When google apps script receives the response, it passes it back to the client end payment form, where the modal displays the Success or Error response accordingly. I feel like im wrong somewhere, but i can’t figure out where. Below is my client end payment form, with a couple of things taken out, as they are not relevant.

<!DOCTYPE html>
<html lang="en">
  <head>
 <title>Payment Form</title>
 <meta charset="utf-8">
 <meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

 <script src="https://js.braintreegateway.com/web/dropin/1.31.0/js/dropin.min.js"></script>

 <script>
window.GAS_URL = "https://script.google.com/a/macros/mycompany.com/s/URL/exec";
 </script>

  <style>

//etc......

  </style>
   
 </head>
 
 <body>
<form id="payment-form" method="post">
 
         <label for="firstName">First Name:</label>
         <input type="text" id="firstName" name="firstName" required>

         <label for="lastName">Last Name:</label>
         <input type="text" id="lastName" name="lastName" required>
        

            //other irrelevant fields go here....

         
       
     <div class="col"> 
      <button type="submit" id="submit">Submit Payment</button>
     </div>

    </div>
   </form>


<div id="myModal" class="modal">
    <div class="modal-content">
      <span class="close">&times;</span>
      <div id="processing-text" class="hidden">Processing, Please wait....</div>
      <div class="modal-body">
        <p id="modal-message"></p>
      </div>
      <div class="modal-footer">
        <button class="ok-button" onclick="closeModal()">OK</button>
      </div>
    </div>
  </div>



 <script>
//adds the GAS URL to the POST 
window.addEventListener("load", function() {
            var paymentForm = document.getElementById("payment-form");
            paymentForm.action = window.GAS_URL;
        });
 </script>  

 <script>
    var modal = document.getElementById("myModal");
    var processingText = document.getElementById("processing-text");
    var modalMessage = document.getElementById("modal-message");
    
    // Check if window.highlight is properly initialized
    if (!window.highlight) {
        console.error("window.highlight is not defined. Ensure that the highlight script is properly loaded.");
    } else {
        document.getElementById("submit").addEventListener("click", function (event) {
            event.preventDefault(); 
            var form = document.getElementById("payment-form");
            if (!form.checkValidity()) {
                window.highlight.requiredFields;
            } else {
                var modal = document.getElementById("myModal");
                modal.style.display = "block";
                processingText.classList.remove("hidden");
                modalMessage.textContent = "";
                sendFormDataToGas();
            }
        });
    }
    
    function closeModal(resetForm) {
        modal.style.display = "none";
        if (resetForm) {
            var paymentForm = document.getElementById("payment-form");
            paymentForm.reset();
    }
  } 
  
  // Function to send form data to GAS_URL
    function sendFormDataToGas() {
        var formData = new FormData(document.getElementById("payment-form"));
        var xhr = new XMLHttpRequest();
        xhr.open("POST", window.GAS_URL);
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE){
                if (xhr.status === 200) {
                    var response = JSON.parse(xhr.responseText);
                    if (response && response.status === "Success") {
                        showSuccessMessage();
                    } else {
                        showErrorModal();
                    }
                } else {
                    showErrorModal();
                }
            }
        };

        xhr.onerror = function () {
            showErrorModal();
        };
        xhr.send(formData);
    }
    

    function showErrorModal() {
        modal.style.display = "block";
        processingText.textContent = "Error";
        modalMessage.textContent = "We're sorry, an error occurred while processing your payment. Please try again. If the problem persists, please call us to make your payment over the phone. Thank you."; 
    }
 </script>



 <script>
 //other scripts....
 </script>

 </body>
</html>

Below is the Google Apps Script that i have tried, but it doesn’t work. Maybe i am in need of a complete overhaul, or maybe its a simple modification, but im truly lost.Maybe i am missing something in my client end form to correctly send the information to the google apps script.

// Replace with your Braintree credentials
var BRAINTREE_MERCHANT_ID = 'MID';
var BRAINTREE_PUBLIC_KEY = 'PUID';
var BRAINTREE_PRIVATE_KEY = 'PRID';

function getClientToken() {
  var url = "https://api.sandbox.braintreegateway.com/merchants/" + BRAINTREE_MERCHANT_ID + "/client_token";

  var headers = {
    "Authorization": "Basic " + Utilities.base64Encode(BRAINTREE_PUBLIC_KEY + ":" + BRAINTREE_PRIVATE_KEY),
    "Content-Type": "application/json"
  };

  var options = {
    "method": "POST",
    "headers": headers,
    "muteHttpExceptions": true
  };

  var response = UrlFetchApp.fetch(url, options);

  if (response.getResponseCode() == 201) {
    var xmlResponse = response.getContentText();
    var xmlDoc = XmlService.parse(xmlResponse);
    var root = xmlDoc.getRootElement();
    var clientToken = root.getChild("value").getText();

    return clientToken;
  } else {
    throw new Error("Failed to get Braintree client token: " + response.getResponseCode() + " - " + response.getContentText());
  }
}

function processPayment(data) {
  var url = "https://api.braintreegateway.com/transactions";
  var headers = {
    "Authorization": "Basic " + Utilities.base64Encode(BRAINTREE_PUBLIC_KEY + ":" + BRAINTREE_PRIVATE_KEY),
    "Content-Type": "application/json"
  };

  var payload = {
    "transaction": {
      "amount": data.amount,
      "paymentMethodNonce": data.paymentMethodNonce,
      "options": {
        "submitForSettlement": true
      }
    }
  };

  var options = {
    "method": "post",
    "headers": headers,
    "payload": JSON.stringify(payload),
    "muteHttpExceptions": true
  };

  var response = UrlFetchApp.fetch(url, options);

  if (response.getResponseCode() == 200) {
    var paymentData = JSON.parse(response.getContentText());
    return paymentData;
  } else {
    throw new Error("Failed to process Braintree payment: " + response.getResponseCode() + " - " + response.getContentText());
  }
}

// Handle POST request from the HTML payment form
function doPost(e) {
  try {
    var requestData = JSON.parse(e.postData.contents);

    // Generate a Braintree client token
    var clientToken = getClientToken();

    // Modify the HTML form to include the client token
    requestData.clientToken = clientToken;

    // Log the incoming requestData
    Logger.log("Received requestData: " + JSON.stringify(requestData));

    // Process the payment
    var paymentResult = processPayment(requestData);

    // Log payment processing result
    Logger.log("Payment processing result: " + JSON.stringify(paymentResult));

    // Handle the payment result here
    if (paymentResult.success) {
      Logger.log("Payment successful");
      return ContentService.createTextOutput(JSON.stringify({ success: true, message: "Payment successful!" }));
    } else {
      Logger.log("Payment failed: " + paymentResult.message);
      return ContentService.createTextOutput(JSON.stringify({ success: false, message: "Payment failed: " + paymentResult.message }));
    }
  } catch (error) {
    Logger.log("An error occurred: " + error.message);
    return ContentService.createTextOutput(JSON.stringify({ success: false, message: "An error occurred: " + error.message }));
  }
}