How to retain dynamically added table rows after invalid form input?

I have here a laravel project with a dynamic table. The dynamic table is working fine. However, after submitting the form with an invalid input, the dynamically added table rows resets and I’m unable to retain old values.

Here’s the code for the table:

<div class="modal fade" id="addOrderModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h3 class="modal-title" id="exampleModalLabel">Deliver Items</h3>
                <a class="btn" data-dismiss="modal" aria-label="Close">
                    <i class="bi bi-x-circle"></i>
                </a>
            </div>
            <form method="POST" id="forms">
                @csrf
                <div class="modal-body">
                    <div class="mb-3">
                        <div class="form-row">
                            <div class="col">
                                <label for="location" class="block font-medium text-sm text-gray-700">Location</label>
                                <select name="location" id="location" class="form-control" required>
                                    <option value="" selected disabled>Select Location</option>
                                    <option value="ORTIGAS" {{ old('location') === 'ORTIGAS' ? 'selected' : '' }}>
                                        ORTIGAS</option>
                                    <option value="A-JUAN" {{ old('location') === 'A-JUAN' ? 'selected' : '' }}>A-JUAN
                                    </option>
                                    <option value="MARIKINA" {{ old('location') === 'MARIKINA' ? 'selected' : '' }}>
                                        MARIKINA</option>
                                </select>
                                @error('location')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>

                            <div class="col">
                                <label for="checkoutdate">Checkout date</label>
                                <input type="date" required name="checkoutdate" id="checkoutdate"
                                    class="form-control" value="{{ old('checkoutdate', '') }}" />
                                @error('checkoutdate')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-row">
                            <div class="col">
                                <label for="client">Client</label>
                                <input type="text" required name="client" id="client" class="form-control"
                                    value="{{ old('client', '') }}" placeholder="Enter client name" />
                                @error('client')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>

                            <div class="col">
                                <label for="contact">Contact Person</label>
                                <input type="text" required name="contact" id="contact" class="form-control"
                                    value="{{ old('contact', '') }}" placeholder="Enter contact person" />
                                @error('contact')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-row">
                            <div class="col">
                                <label for="site">Site/Event</label>
                                <input type="text" required name="site" id="site" class="form-control"
                                    value="{{ old('site', '') }}" placeholder="Enter site/event" />
                                @error('site')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>
                            <div class="col">
                                <label for="address">Address</label>
                                <input type="text" required name="address" id="address" class="form-control"
                                    value="{{ old('address', '') }}" placeholder="Enter address" />
                                @error('address')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="form-row">
                            <div class="col">
                                <label for="srnumber">SR No.</label>
                                <input type="text" required name="srnumber" id="srnumber" class="form-control"
                                    value="{{ old('srnumber', '') }}" placeholder="Enter SR no." />
                                @error('srnumber')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>
                            <div class="col">
                                <label for="ponumber">PO No.</label>
                                <input type="text" required name="ponumber" id="ponumber" class="form-control"
                                    value="{{ old('ponumber', '') }}" placeholder="Enter PO no." />
                                @error('ponumber')
                                    <p class="text-danger">{{ $message }}</p>
                                @enderror
                            </div>
                        </div>
                    </div>

                    <div class="mb-3">
                        <div class="table-responsive text-nowrap">
                            @if ($errors->any())
                                <div class="alert alert-danger">
                                    Check fields for invalid input.
                                </div>
                            @endif
                            <table class="table table-bordered" id="dynamicTable">
                                <thead class="table-dark">
                                    <tr>
                                        <th>SKU</th>
                                        <th>Product Code</th>
                                        <th>Model</th>
                                        <th style="width:13%">Quantity</th>
                                        <th>UOM</th>
                                        <th>Item Description</th>
                                        <th>Serial No.</th>
                                    </tr>
                                </thead>
                                <tr>
                                    <td>
                                        <input type="text" name="addmore[0][sku]" placeholder="SKU"
                                            value="{{ old('addmore.0.sku') }}" class="form-control" />
                                    </td>

                                    <td><input type="text" name="addmore[0][productcode]"
                                            value="{{ old('addmore.0.productcode') }}" placeholder="Product Code"
                                            class="form-control" /></td>

                                    <td><input type="text" name="addmore[0][model]" placeholder="Model"
                                            value="{{ old('addmore.0.model') }}" class="form-control" /></td>
                                    <td><input type="number" name="addmore[0][quantity]" placeholder="Quantity"
                                            value="{{ old('addmore.0.quantity') }}" class="form-control" /></td>

                                    <td><select name="addmore[0][uom]" class="form-control">
                                            <option value="UNIT/S"
                                                {{ old('addmore.0.uom') === 'UNIT/S' ? 'selected' : '' }}>UNIT/S
                                            </option>
                                            <option value="PANEL/S"
                                                {{ old('addmore.0.uom') === 'PANEL/S' ? 'selected' : '' }}>PANEL/S
                                            </option>
                                            <option value="PC/S"
                                                {{ old('addmore.0.uom') === 'PC/S' ? 'selected' : '' }}>PC/S</option>
                                        </select></td>

                                    <td><input type="text" name="addmore[0][itemdescription]"
                                            value="{{ old('addmore.0.itemdescription') }}"
                                            placeholder="Item Description" class="form-control" /></td>

                                    <td>
                                        <textarea name="addmore[0][serialnumber]" class="form-control" cols="15" rows="1"
                                            placeholder="Serial no.">{{ old('addmore.0.serialnumber') }}</textarea>
                                    </td>

                                    <td class="border border-white"><button type="button" name="add"
                                            id="add" class="btn btn-success btn-sm"
                                            style="background-color: #4D83FF; color: white;  border-color: #4D83FF;"><i
                                                class="bi bi-plus-circle"></i></button></td>

                                </tr>
                            </table>

                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="submit" id="submitButt" class="btn btn-primary">Save</button>
                </div>
            </form>
        </div>
    </div>



</div>

And here’s the script for the dynamic table:

 <script type="text/javascript">
        var i = 0;
        $("#add").click(function() {
            ++i;
            $("#dynamicTable").append('<tr><td><input type="text" name="addmore[' + i +
                '][sku]" placeholder="SKU" class="form-control"/></td><td><input type="text" name="addmore[' +
                i +
                '][productcode]" placeholder="Product Code" class="form-control"/></td><td><input type="text" name="addmore[' +
                i +
                '][model]" placeholder="Model" class="form-control"/></td><td><input type="number" name="addmore[' +
                i +
                '][quantity]" placeholder="Quantity" class="form-control"/></td><td><select name="addmore[' +
                i +
                '][uom]" class="form-control"><option value="Units">Unit/s</option><option value="Panels">Panel/s</option><option value="Pcs">Pc/s</option></select></td><td><input type="text" name="addmore[' +
                i +
                '][itemdescription]" placeholder="Description" class="form-control"/></td><td><textarea name="addmore[' +
                i +
                '][serialnumber]" placeholder="Serial No." class="form-control" rows="1"></textarea></td><td class="border border-white"><button type="button" class="btn btn-danger btn-sm remove-tr" title="Remove item"><i class="bi bi-x-circle"></i></button></td></tr>'
            );
            event.preventDefault();
        });

        $(document).on('click', '.remove-tr', function() {
            $(this).parents('tr').remove();
        });
    </script>

I tried many fixes but I still can’t make it work.

functionality for a react/node calendar that sorts available time slots based on bookings

I am trying to create a react/vite/node app, but I am having issues with implementing functionality where the dates taken from the database eliminate the time slots which have already been booked. My problem at this stage is having the splicedSlots be shown on the user interface although the console already shows them as jsx buttons with proper keys (times).

the code:

import React, { useState, useEffect } from 'react';
import { Link } from 'react-router-dom';
import 'bootstrap';
import axios from 'redaxios';


// code for calendar and timeSelect was here


  let daySelected = localStorage.getItem('daySelected');
  let allowedDates = [];
  let forbiddenDates = [];
  let allDates = [];
  let fetchDataCalled = false;
  let updatedForbiddenDates = [];
  let wantedSlots = [];
  let times = [];
  let allDatesUnique = [];


  let timeSlotKeys = [];
  let timeSlots = [];

  let splicedSlots = [];
  const generateTimeSlots = (wantedSlots) => {


    const startDate = new Date(selectedDate);
    startDate.setHours(8, 0, 0, 0);
    const endDate = new Date(selectedDate);
    endDate.setHours(18, 0, 0, 0);

    wantedSlots = allDatesUnique.filter(
      (item) => !forbiddenDates.includes(item)
    );

    for (let i = 0; i < wantedSlots.length; i++) {
      times.push(wantedSlots[i].split(', ')[1]);
    }
    const uniqueTimes = [...new Set(times)];

    for (let i = 0; i < uniqueTimes.length; i++) {
      wantedSlots.push(
        <button
          key={uniqueTimes[i]}
          onClick={() => handleTimeSelect(uniqueTimes[i])}
          className={`time-slot ${
            selectedTime === uniqueTimes[i] ? 'selected' : ''
          } `}
          disabled={false}
        >
          {uniqueTimes[i]}
        </button>
      );
    }
    splicedSlots = wantedSlots.splice(19);


    while (startDate < endDate) {
      timeSlotKeys = timeSlots.map((timeSlot) => timeSlot.key);
      let time = startDate.toLocaleTimeString('en-US', {
        hour: 'numeric',
        minute: '2-digit',
        hour12: true,
      });
      startDate.setMinutes(startDate.getMinutes() + 30);

      timeSlots.push(time);
    }
    return splicedSlots;
  };

  const fetchData = async () => {
    if (!fetchDataCalled) {
      fetchDataCalled = true;

      const startDate = new Date(selectedDate);
      startDate.setHours(8, 0, 0, 0);
      const endDate = new Date(selectedDate);
      endDate.setHours(18, 0, 0, 0);
      try {
        const response = await axios.get('/api/v1/booking').then((res) => {
          const bookedDates = res.data.bookings.map(
            (booking) => booking.selectedDateTime
          );

          const keysArray = timeSlots;

          for (let j = 0; j < keysArray.length; j++) {
            const timeKey = keysArray[j];
            const hour = timeKey
              .replace(`${daySelected}_`, '')
              .replace('-', ':');
            const splitDate = daySelected.split('-');
            const monthWithZero = splitDate[1];
            const monthWithoutZero = parseInt(monthWithZero, 10);
            const date = monthWithoutZero + '/' + splitDate[2];

            const formattedTime = `${date}, ${hour}`;
            allDates.push(formattedTime);
          }
          allDatesUnique = [...new Set(allDates)];
          // console.log(allDatesUnique);
          for (let i = 0; i < allDatesUnique.length; i++) {
            if (bookedDates.includes(allDatesUnique[i]) === false) {
              allowedDates = allowedDates + ' ' + allDatesUnique[i];
            } else {
              forbiddenDates.push(allDatesUnique[i]);
            }
          }
          for (let i = 0; i < forbiddenDates.length; i++) {
            updatedForbiddenDates.push(forbiddenDates[i].split(', ')[1]);
          }
        });

        splicedSlots = generateTimeSlots(splicedSlots);

        console.log(splicedSlots);
      } catch (error) {
        console.error('Error fetching data:', error);
      }
    }
  };
  fetchData();

  generateTimeSlots();

  return (
    <div className="booking-calendar-container">
      <div className="month-header">
        <button className="month-button" onClick={() => handleMonthChange(-1)}>
          <span className="arrow left"></span>
        </button>
        <h2>
          {currentMonth.toLocaleString('default', { month: 'long' })}{' '}
          {currentMonth.getFullYear()}
        </h2>
        <button className="month-button" onClick={() => handleMonthChange(1)}>
          <span className="arrow right"></span>
        </button>
      </div>
      <table className="calendar">
        <thead>
          <tr>
            <th>Sun</th>
            <th>Mon</th>
            <th>Tue</th>
            <th>Wed</th>
            <th>Thu</th>
            <th>Fri</th>
            <th>Sat</th>
          </tr>
        </thead>
        <tbody>{generateCalendar()}</tbody>
      </table>

      <div>{generateTimeSlots()}</div>

      <Link
        className="calendar-continue-link"
        to={`/booking_info/${courseID}`}
        onClick={handleLinkClick}
      >
        next
      </Link>
    </div>
  );
};

export default Calendar;

this is the object that is shown in the console for splicedSlots

Array(19) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, … ]
​
0: Object { "$$typeof": Symbol("react.element"), type: "button", key: "8:00 AM", … }
​
1: Object { "$$typeof": Symbol("react.element"), type: "button", key: "8:30 AM", … }
​
2: Object { "$$typeof": Symbol("react.element"), type: "button", key: "9:00 AM", … }
​
3: Object { "$$typeof": Symbol("react.element"), type: "button", key: "9:30 AM", … }
​
4: Object { "$$typeof": Symbol("react.element"), type: "button", key: "10:00 AM", … }
​
5: Object { "$$typeof": Symbol("react.element"), type: "button", key: "10:30 AM", … }
​
6: Object { "$$typeof": Symbol("react.element"), type: "button", key: "11:00 AM", … }
​
7: Object { "$$typeof": Symbol("react.element"), type: "button", key: "11:30 AM", … }
​
8: Object { "$$typeof": Symbol("react.element"), type: "button", key: "12:00 PM", … }
​
9: Object { "$$typeof": Symbol("react.element"), type: "button", key: "12:30 PM", … }
​
10: Object { "$$typeof": Symbol("react.element"), type: "button", key: "1:00 PM", … }
​
11: Object { "$$typeof": Symbol("react.element"), type: "button", key: "2:00 PM", … }
​
12: Object { "$$typeof": Symbol("react.element"), type: "button", key: "2:30 PM", … }
​
13: Object { "$$typeof": Symbol("react.element"), type: "button", key: "3:00 PM", … }
​
14: Object { "$$typeof": Symbol("react.element"), type: "button", key: "3:30 PM", … }
​
15: Object { "$$typeof": Symbol("react.element"), type: "button", key: "4:00 PM", … }
​
16: Object { "$$typeof": Symbol("react.element"), type: "button", key: "4:30 PM", … }
​
17: Object { "$$typeof": Symbol("react.element"), type: "button", key: "5:00 PM", … }
​
18: Object { "$$typeof": Symbol("react.element"), type: "button", key: "5:30 PM", … }
​
length: 19
​
<prototype>: Array []
calender.jsx:198:16

thank you for anyone who tries to help!

Chrome extension: Error: cannot read properties of undefined (reading ‘url’)

In my chrome extension, in my background.js file, the following code seems to trigger an error in my console.log on the launch of chrome.

“Error in event handler: Typeerror: Cannot read properties of undefined (reading ‘url’)”

The code in question is the following:

chrome.tabs.onHighlighted.addListener(function(tabId, changeInfo, tab) {
    let url = tab.url;

The error doesn’t occur AFTER I have loaded other tabs, only on the initial load of chrome. I think this indicates my background script is running before the URL is available in the very first loaded tab.

I have attempted using if(tab.url) but the error still flags.

Is there a way to ignore the code if the url is undefined or another easy way to fix?

compare each value before in array object javascript

so i have an response from my mongodb as result of my aggregation function using mongopaginateaggregate as below:

const data = {
  docs: [
    {
      Material_Description: 'NABATI VITAKRIM RSY 122g MT (24 pcs)',
      Plant: 'K105',
      Channel: 'MT',
      Material: '300973',
      expiredDate: 'January-2024',
      '2023-04-12': 124
    },
    {
      Material_Description: 'NEXTAR GANDUMKU RCO 22g GT(10pc x 12bal)',
      Plant: 'K105',
      Channel: 'GT',
      Material: '303923',
      expiredDate: 'October-2023',
      '2023-04-12': 1
    }
  ],
  totalDocs: 2,
  limit: 1000,
  page: 1,
  totalPages: 1,
  pagingCounter: 1,
  hasPrevPage: false,
  hasNextPage: false,
  prevPage: null,
  nextPage: null
}

i try to group it and compare each value by adding function datelist:

const dateLists = Array.from({ length: 7 }, (_, index) => {
        const local = new Date();
        local.setDate(local.getDate() - index);
        return local.toLocaleDateString("en-SE", {
          timeZone: "Asia/Jakarta",
        });
      });

here is my try and my result:
i succeed adding other dates to the data but failed to compare each date value to get the comparasion:

const new_data = data.docs.map((item) => {
        const newItem = {
          Material: item.Material,
          Material_Description: item.Material_Description,
          Plant: item.Plant,
          Channel: item.Channel,
          expiredDate: item.expiredDate,
        };
        let a = 1;

        dateLists.sort().forEach((date) => {
          newItem[date] = item[date] ? item[date] : 0;

          // `${'Keterangan_'+ parseStr(a)}` = item[date] ? item[date] : 0;
        });
        return newItem;
      });

      data.docs = new_data;

result:

{
        "docs": [
            {
                "Material": "300973",
                "Material_Description": "NABATI VITAKRIM RSY 122g MT (24 pcs)",
                "Plant": "K105",
                "Channel": "MT",
                "expiredDate": "January-2024",
                "2023-04-12": 124,
                "2023-04-13": 0,
                "2023-04-14": 0,
                "2023-04-15": 0,
                "2023-04-16": 0,
                "2023-04-17": 0,
                "2023-04-18": 0
            },
            {
                "Material": "303923",
                "Material_Description": "NEXTAR GANDUMKU RCO 22g GT(10pc x 12bal)",
                "Plant": "K105",
                "Channel": "GT",
                "expiredDate": "October-2023",
                "2023-04-12": 1,
                "2023-04-13": 0,
                "2023-04-14": 0,
                "2023-04-15": 0,
                "2023-04-16": 0,
                "2023-04-17": 0,
                "2023-04-18": 0
            }
        ],
        "totalDocs": 2,
        "limit": 1000,
        "page": 1,
        "totalPages": 1,
        "pagingCounter": 1,
        "hasPrevPage": false,
        "hasNextPage": false,
        "prevPage": null,
        "nextPage": null
    }

is that possible to compare each value of the date like this?:

enter image description here

here is my expected resulted that when compare each value of the date inside the object:

"docs": [
            {
                "Material": "300973",
                "Material_Description": "NABATI VITAKRIM RSY 122g MT (24 pcs)",
                "Plant": "K105",
                "Channel": "MT",
                "expiredDate": "January-2024",
                "2023-04-12": 124,
                "Keterangan_1":"No Data",
                "2023-04-13": 0,
                "Keterangan_2":"Berkurang",
                "2023-04-14": 0,
                "Keterangan_3":"Sama",
                "2023-04-15": 0,
                "Keterangan_4":"Sama",
                "2023-04-16": 0,
                "Keterangan_5":"Sama",
                "2023-04-17": 0,
                "Keterangan_6":"Sama",
                "2023-04-18": 0,
                "Keterangan_7":"Sama",
            },

any help on this… or any one can help to improve my code to get the expected result

Enabling IntelliSense for Javascript in Visual Studio Code

For most of my languages like CSS and HTML, certain snippets will autofill which really helps me with my formatting and spelling since I’m not used to all the commands.

I’ve seen this work for Javascript in Youtube tutorials but even after installing every Javascript extension imaginable the autofill still will not work.

I’ve looked at the other related threads on this website but those don’t seem to work for me either. Was hoping someone on here has had a similar problem.

My settings.json file

{
    "[python]": {
        "editor.formatOnType": true
    },
    "cmake.configureOnOpen": true,
    "workbench.colorTheme": "Sapphire (Dim)",
    "css.styleSheets": [],
    "javascript.suggest.alwaysAllWords": true,
    "javascript.suggest.completeFunctionCalls": true,
    "[html]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "[css]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
    "emmet.includeLanguages": {
        "javascript": "javascriptreact"
    },
    "emmet.triggerExpansionOnTab": true,
    "enableTelemetry": false,
    "bracket-pair-colorizer-2.depreciation-notice": false,
    "workbench.startupEditor": "none",
    "[javascript]": {
        "editor.defaultFormatter": "esbenp.prettier-vscode"
    },
}

I tried implementing this code from online

"emmet.includeLanguages": {
  "javascript": "javascriptreact"
},`

but that did not work

Google Doc won’t load do to custom Chrome Extension

I am super new to Chrome Extensions but I am trying to make my own with some simple js and json. I currently have a script that finds all instances of the word “cave” on a page and replaces it with “cheeseburger”… don’t ask. It works fine when I search on Google for caves, all the instances of caves change to cheeseburgers. I now want it to work in google docs though. For instance, if I open a Google doc that has the word cave in it it should show up as cheeseburger. For some reason while the extension is running and working elsewhere when I open a Google doc with Word, I get this page.

enter image description here

Funny enough when I was trying to load the image I could click the image icon when posting the image on this answer to browse my files until I turned my extension off.

Code:

manifest.json:

{
  "name": "Cave to Cheeseburger",
  "version": "1.0",
  "description": "Replaces the word 'cave' or 'Cave' with 'Cheeseburger' on any webpage.",
  "manifest_version": 2,
  "permissions": ["activeTab"],
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

content.js:

document.body.innerHTML = document.body.innerHTML.replace(/cave/gi, "Cheeseburger");

Thanks in Advance!!

I can’t get the right access to the elements inside the IFRAME tag

Faced with such a problem. I am creating an extension for the backend of one service. There was a need to integrate information from one page into another. I decided to use the IFRAME tag to access the page, get the table from there by its ID and already integrate the data of this table into the first one. Here’s the code.



let bonustable = document.getElementById('bonustable')
let iframe = document.createElement('iframe')
iframe.src = 'somepage.html'
bonustable.before(iframe)
iframe.contentWindow.onload = () => {
    console.log('frame is loaded')
    let table = iframe.contentDocument.getElementById('transactions-grid')
    console.log(table)
  }

I expect to see all the internal HTML inside the “transactions-grid” element in the console, but I don’t see it. Only the opening and closing tag. Although there are a bunch of TD tags inside to the innerText that needs access.
I’ve tried
table = window.frames['ifr'].contentDocument.getElementById('transactions-grid').getElementsByTagName('td')[0] but this returns undefined. Can you tell me why this might be?

Decrypt function not working as intended in javascript code

I had a friend write some code and I cant figure out whats wrong

When i input text it encrypts it and when i click decrypt it spits whatever i typed back out (so if i took encrypted code and tried to decrypt it after inputting different text it would not work)

Here is the code:

<!DOCTYPE html>
<html>
  <head>
    <title>Text Encryption and Decryption</title>
  </head>
  <body>
    <h1>Text Encryption and Decryption</h1>
    <label for="input-text">Input Text:</label>
    <input type="text" id="input-text" /><br /><br />
    <button onclick="encrypt()">Encrypt</button>
    <button onclick="decrypt()">Decrypt</button><br /><br />
    <label for="encrypted-text">Encrypted Text:</label>
    <input type="text" id="encrypted-text" /><br /><br />
    <label for="decrypted-text">Decrypted Text:</label>
    <input type="text" id="decrypted-text" /><br /><br />

    <script>
      function encrypt() {
        const inputText = document.getElementById("input-text").value;
        const encryptedText = btoa(inputText);
        document.getElementById("encrypted-text").value = encryptedText;
      }

      function decrypt() {
        const encryptedText = document.getElementById("encrypted-text").value;
        const decryptedText = atob(encryptedText);
        document.getElementById("decrypted-text").value = decryptedText;
      }
    </script>
  </body>
</html>

I tried messing around with the variables but it didnt work as planned so this is the original code. Any help would be greatly appreciated.

Cards using html , css and js

how can i create a Cards that maps as the data enter and all the cards hould scroll horizontally but the content inside it should be static.

I try using json file and the content inside card is also scrolling hosizontaly

click on copy button using javascript

I am trying to click on copy button on an editor using Javascript for automation purposes but the text not stored in the clipboard

tried the below codes

  const button = document.getElementById("copy-1");
button.click();

and

   const button = document.getElementById("copy-1");
   const event = new Event("click");
   button.dispatchEvent(event);

the HTML code

<button id="copy-1" type="button" tabindex="-1" role="button" class="fr-command fr-btn" data-cmd="copy" data-title="Copy" style="outline: 1px solid blue;">
    <froalacopy_button class="hoverable"><i class="fas fa-copy"></i></froalacopy_button><span class="fr-sr-only">Copy</span>
</button>

also, I tried to copy it directly but the copied text was not formatted

enter image description here

Full stack web app using Spring and Angular Search method not displaying alert properly

When a user is searching for a player that doesn’t exist, the alert message pops up in between me typing that name that doesn’t exist. The alert doesn’t stay on the page. When I am done typing the name that doesn’t exist, it still shows the page of all the players that already exist.

This is my app.component.html for the notification and for the ngModelChange.

<!-- Notification for no players -->
<div *ngIf="players?.length == 0" class="col-lg-12 col-md-12 col-xl-12">
<div class="alert alert-info" role="alert">
  <h4 class="alert-heading">NO PLAYERS!</h4>
  <p>No Players were found.</p>
</div>
</div>

<form class="form-inline my-2 my-lg-0">
        <input type="search" (ngModelChange)="searchPlayers(key.value)" #key="ngModel" ngModel
         name="key" id="searchName" class="form-control mr-sm-2" placeholder="Search players..." required>
</form>

This is my app.component.ts search method

public searchPlayers(key: string): void {
    console.log(key);
    const results: Player[] = [];
    for (const player of this.players) {
      if (player.name.toLowerCase().indexOf(key.toLowerCase()) !== -1
      || player.email.toLowerCase().indexOf(key.toLowerCase()) !== -1
      || player.phoneNumber.toLowerCase().indexOf(key.toLowerCase()) !== -1
      || player.position.toLowerCase().indexOf(key.toLowerCase()) !== -1) {
        results.push(player);
      }
    }
    this.players = results;
    if (results.length === 0 || !key) {
      this.getPlayers();
    }
  }

Any suggestions would be appreciated.

How can stop event propagation in Vue 3 to the root component

I’ve created several components that communicate with each other using custom events.

The issue is that I’m having difficulties with event propagation. I have an App.vue component that instantiates a GeneriqueButton component, which in turn instantiates a BaseButton component. I’ve added an event listener on GeneriqueButton with the .stop modifier to prevent event propagation to App.vue, but the event still bubbles up to App.vue, I’ve message in my console.

I don’t understand why the event continues to propagate despite the use of the .stop modifier. I’ve verified that the event is emitted from BaseButton, but it’s still captured by App.vue.

Here’s the code for the three components:

App.vue :

<template>
  <GeneriqueButton @base-button="printConsole"/>
</template>

<script setup>
import GeneriqueButton from './GeneriqueButton.vue'
function printConsole(event) {
  console.log('App.vue : BaseButton clicked !', event)
}
</script>

GeneriqueButton.vue

<template>
  <BaseButton @base-button.stop="printConsole" />
</template>

<script setup>
import BaseButton from './BaseButton.vue'
function printConsole(event) {
  console.log('GeneriqueButton.vue : BaseButton clicked !', event)
}
</script>

BaseButton.vue

<template>
  <button type="button" @click="$emit('base-button', $event)">
    Click me
  </button>
</template>

I use console.log in App.vue and GeneriqueButton.vue, each click on button I have 2 logs in my console.

Do you have any idea what might be causing this event propagation issue? Do you have any suggestions on how to fix it?

Thank you in advance for your help.

Socket.io emit on express route to specific user=

I have an express server set up as follows:

Server Side

const express = require('express')
const app = express()
const port = 3001
const http = require('http')
const server = http.createServer(app)
const { Server } = require("socket.io");
const io = new Server(server, {
    cors: {
        origin: "http://localhost:3000"
    }
});
app.io = io

//emitting works fine, but if more than one user sends a request to this endpoint, everyone gets all messages
app.get('/test', (req, res) => {
   req.app.io.emit('started', true)
   setInterval(() => {
        var clientConnected = true //some way to test if the client is connected. Anything including req.app.io or res.app.io doesn't work
        if (clientConnected) {
            req.app.io.emit('data', {key: value})
        } else {
            //shut down data transfer
            return;
        }
    }, 1000);
    //more stuff here
    res.end()
})
server.listen(port, () => {
  console.log(`Running on http://localhost:${port}`)
})

React Client Side

import * as React from 'react';
React.useEffect(() => {
   socket.on('started', (data) => {
       console.log(data)
       //do something here
   })
   socket.on('data', (data) => {
      console.log(data)
      //do something here
   })
}, [])

The post I got the base code from is almost 7 years old and doesn’t have much information on how to do these things, along with the socket.io docs that doesn’t really have any good information on this either.

There are two problems here. The first one is that all users are receiving the same messages which is a problem for my ui which adds the data to a state and it renders a part of the page with the new data. So I need every user who gets connected to get only their data that they requested.

The second problem is that using this method, I have no way of telling if the user is still connected to the route. If they are still connected I want to continue sending data, and if they aren’t I want to kill the process the server is doing to retrieve and send that data. Even emitting to the server inside of one of the ‘socket.on’ never gets received by the server. How do I go about checking if the client is still connected so I don’t waste bandwidth or waste storage space? I can’t use io.on(‘connect’) inside the route because I use it elsewhere to check if a user is online and count how many users are online. I just want to know if the user is still connected to the /test route specifically. Again, emitting works fine. I also want the messages to only be sent to that specific user connected to the /test route WHILE they are connected to the /test route. If the user refreshes their page or cancels I want to stop the data transfer on the server side which is doing things on its own.

Why is credit card not showing? [closed]

I am trying to implement the following credit card form… https://github.com/jessepollak/card following the section named Usage (without jQuery). I am implementing it using a text file which has the following code…

<script>
var card = new Card({
    form: '#myform', 
    container: '#con', 
    formSelectors: {
        numberInput: 'input#number'
}  
});
</script>
</head>
<body>
<div id="con">
<form id=myform>
<input type="text" name="number">
</form>
</div>

<script src="D:card-masterdistcard.js">
</script>
</body>

Unforunately, the result is just that the text item is displayed on the web page. Nothing else. Here’s a pic of what I am seeing…
Result
And here’s a code pen with the same code…
My Pen
What am I missing here?

How to format the tick labels of the noUiSlider with SI symbols?

Here is how my noUiSlider looks like:

enter image description here

I would like to format the tick labels as: 1000 -> 1K, 900000 -> 900K, 5000000 -> 5M, etc; i.e. abbreviating the number with the appropriate SI symbol.

library(shiny)
library(shinyWidgets)

ui <- fluidPage(
  
  tags$br(),
  
  noUiSliderInput(
    inputId = "noui", 
    label = "Slider vertical:",
    value =  50,
    orientation = "vertical",
    range = list("min" = list(0),
                 "25%" = list(1000, 500),
                 "50%" = list(10000, 50000),
                 "75%" = list(4000000, 500000),
                 "max" = list(10000000)),
    pips = list(
      mode = "values",
      values = list(0, 500, 1000, 900000, 5000000, 10000000),
      density = 4
    ),
    format = wNumbFormat(decimals = 0),
    width = "300px", height = "300px"
  ),
  verbatimTextOutput(outputId = "res")
  
)

server <- function(input, output, session) {
  
  output$res <- renderPrint(input$noui)
  
}

shinyApp(ui, server)