Is it possible to store the value of a variable in an event listener?

I’d like to assign several “click” eventlisteners to several elements that I create using a “for” loop. The unique information for each of these elements is stored in a dictionary, and I can access it using the index of the for loop.
What I’d like to do, then, is to have the eventlisteners assigned to these buttons retain the index (or the value of the dictionary associated with the index, but it amounts to the same thing), because at the moment I’m only getting what appears to be the loop index when the loop has finished.

Here’s the simplified code;

for (var ind = 0; ind < JSON.parse(localStorage.getItem('data')).length; ind++) {
    var sc = document.createElement('div');
    sc.addEventListener('click', function () {
        console.log(ind);
    })
}

I tried googling for answers but couldn’t find anything, then I tried putting the index in the parentheses of the event listener function but it returns a strange pointer instead.
Something like PointerEvent {...} with a series of attributes.

Moment JS Get start of day in specific timezone in utc

In typescript using moment, I want some code that will return the start of date in a given timezone converted to UTC time. The code should be able to be executed from any machine within any timezone and give the same output.

Examples:

Date string: “2023-07-07”, timezone: “America/Bahia”, expected result: 2023-07-07T03:00:00Z
Date string: “2023-07-07”, timezone: “Europe/Paris”, expected result: 2023-07-06T22:00:00Z

import moment from 'moment-timezone';

const date = '2023-07-07';
const timeZone = 'America/Bahia';

result = moment.tz(date, timeZone).startOf('day').utc().format();

The unit tests for this pass and “2023-07-07T03:00:00Z” is returned.
But when running in my app on local host, the day before is returned “2023-07-06T03:00:00Z”.
I have suspicion this is because the timezone I am in is behind UTC, I want this code to return the same result no matter what timezone the app is in.

Select option is not getting cleared once set to 0 in javscript

I want to reset the select option while another option is selected to 0. So I tried below code.

if (varALPO1MobNum == "0") {                    
                var selectElement = $('#ddlALPO1STUpd');
                resetSelectElement(selectElement); // here I want to reset it to 0
                $('#ddlALPO1STUpd').attr('disabled', 'disabled');
            } else {
                $('#ddlALPO1STUpd').removeAttr('disabled');
            }

And the source code HTML for the same is below

<select name="ctl00$ddlALPO1STUpd" id="ddlALPO1STUpd" class="form-control" disabled="disabled">
     <option value="0">--Select--</option>
     <option value="Base">Base</option>
    <option selected="selected" value="Primary">Primary</option>
   <option value="Additional">Additional</option></select>

The above logic is not working and resetting to 0. Please suggest what is wrong here

Also reset code is below

function resetSelectElement(selectElement) {
selectElement.selectedIndex = 0; 

}

Error deleting articles by ID in Express.js and SQLite – ‘Cannot DELETE /author/1’

I’m working on a blogging web application using Express.js and SQLite as the database. I have a functionality where authors can create and manage articles. However, I’m encountering an issue with deleting articles by their ID.

Here’s an overview of my current setup:

I have a draftArticles table in the SQLite database to store draft articles.
On the author’s homepage, I display a list of draft articles with options to edit and delete each article.
I’m using EJS templates for rendering the views and Express.js for handling routes.
The problem I’m facing is that when I click the delete button for an article, I receive a “Cannot DELETE /author/1” error. I suspect that there might be an issue with how the article IDs are connected.

Here are some details about my implementation:

In my EJS template, I have a table listing the draft articles with a delete button for each article.
The delete button is wrapped inside a form, and I’m using the method-override library to add a custom DELETE method to the form.
In my Express.js route for handling the delete request, I’m using req.params.id to retrieve the article ID and perform the deletion.

Here is my delete route implementation:

 router.delete("/:id", (req, res, next) => {
    const id = req.params.id;
  
    // Delete the draft article from the database
    global.db.run("DELETE FROM draftArticles WHERE id = ?", [id], function (err) {
      if (err) {
        next(err);
      } else {
        res.redirect("/author/home");
      }
    });
  });

Here is the table in home.ejs that includes the delete buttons:

<h2 class="mt-4">Draft Articles</h2>
    <table class="mb-4">
      <thead>
        <tr>
          <th>Title</th>
          <th>Subtitle</th>
          <th>Created</th>
          <th>Last Modified</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <% draftArticles.forEach(function(article) { %>
          <tr>
            <td><%= article.title %></td>
            <td><%= article.subtitle %></td>
            <td><%= article.created %></td>
            <td><%= article.last_modified %></td>
            <td>
                <a href="/author/drafts/<%= article.id %>" class="btn btn-secondary">Edit Article</a>
                <form action="/author/<%= article.id %>?_method=DELETE" method="post" class="d-inline">
                  <button type="submit" class="btn btn-danger">Delete</button>
                </form>
            </td>
          </tr>
        <% }); %>
      </tbody>
    </table>

I have tried to troubleshoot the issue by verifying the article IDs in the database and checking the template usage. However, I haven’t been able to identify the root cause of the issue. I would appreciate any insights or suggestions on how to debug and resolve this problem. Let me know if any additional code snippets or details would be helpful.

how to Change dark theme to light teme after reclick [duplicate]

i made a button that when u click it, the webpage turn to dark theme but when i reclick it, it stays black i want it to return back to the default (white) like a loop

const myBtn = document.getElementById("darktheme");
const body = document.body;
const welcome = document.getElementById("txtt")

myBtn.addEventListener("click", function(){
    body.style.backgroundColor = "rgb(17, 17, 17)";
    body.style.color = "white";
    welcome.style.color = "white";
    
}) 

can anyone Help ?

How do I make an array that adds a day (number) in a specified increment, but follows the “rules” of a calendar?

Sorry for the sloppily worded title, but here is an example of what I want to achieve:

//increment of 5
const daysOfMonthArray = [16, 21, 26, 31, 5, 10, 15, 20, 25, 30, 4, 9.....]

I’m having a hard time trying to find a good way to do this using dayJS, but I’m sure it’s reasonably doable with JavaScript’s built in date objects as well. Any help would be greatly appreciated, thanks!

Transform array of strings in JavaScript

I have an array of strings:

['braid', 'write', 'pence', 'schmo']

I would like some method to transform this into this:

['bwps', 'rrec', 'ainh', 'itcm', 'deeo']

I.e. I want the new strings to be the combination of all 1st letters, 2nd letters, 3rd letters, etc. of the old strings

What is use of Proxy in frontend part

What is use of Proxy "proxy": "http://localhost:5000", in Package.json in frontend part
when Backend (API Part) is starting in 5000 Port ?

Please Explain how Proxy work in package.json when calling rest API.
and also explain how writing proxy provide to directly with the API

How can I listen to the onFieldChange event in Odoo 16 using JavaScript?

I would like to listen for the onChange event of a field in Odoo 16 using JavaScript. I have attempted the following code snippets, but they did not yield the desired results.

my_module/static/src/js/on_field_changes.js

odoo.define('my_module.on_field_changes', function (require) {
"use strict";

const fieldRegistry = require('web.field_registry');
const { FieldChar } = require('web.basic_fields');

const onchange_widget = FieldChar.extend({

    _onFieldChanged(ev) {
        console.log('=========  > > > > Hello')
        this._super.apply(this, arguments);
    },
});

fieldRegistry.add('onchange_widget', onchange_widget);  });

In form view:

<field name="father_name" widget="onchange_widget"/>

In manifest.py:

'assets': {
    'web.assets_backend': [
        'my_module/static/src/js/on_field_changes.js',
    ]
}

In addition, I have attempted several other code snippets, but unfortunately, none of them proved successful either.

Redux error when trying to retrieve data from slice: Uncaught TypeError: Cannot read properties of undefined (reading ‘list’)

I’m building a simple todo app with ReactJS and Redux but i get an error when i try to retrieve the todos that i added to a list that is in the initial state. The error is the following:

Uncaught TypeError: Cannot read properties of undefined (reading
‘list’)

the error comes from this line:

export const selectTodos = (state) => state.todos.list;

SLICE CODE:

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
  list: [],
};

export const todosSlice = createSlice({
  name: "todos",
  initialState,

  reducers: {
    addTodo: (state, action) => {
      state.list = [...state.list, action.payload];
    },
  },
});

export const { addTodo } = todosSlice.actions;
export const selectTodos = (state) => state.todos.list;

export default todosSlice.reducer;

APP.JSX:

import React, { useRef } from "react";
import { useDispatch, useSelector } from "react-redux";
import { addTodo, selectTodos } from "./features/todos/todosSlice";

const App = () => {
  const inputRef = useRef(null);
  const todos = useSelector(selectTodos);
  const dispatch = useDispatch();

  const createTodo = async (e) => {
    e.preventDefault();

    const newTodo = inputRef.current.value;
    dispatch(addTodo(newTodo));
  };

  return (
    <div>
      <h1>Todo List</h1>
      <form>
        <input type="text" placeholder="task..." ref={inputRef} />
        <button onClick={createTodo}>Add Todo</button>
      </form>
      <h2>Your Todos:</h2>
      {todos}
    </div>
  );
};

export default App;

If you have any suggestions please let me know.

Ajax PUT request sends parameter as null when it shouldn’t

I am trying to pass these two variables to a servlet, but get an error stating that sessionid is a null string.

var sessionid = document.getElementById("Session-select").value;
var attendeeid = document.getElementById("Attendee-select").value;
            console.log(attendeeid + " " + sessionid);
    $.ajax({

        url: 'http://localhost:8180/Project_2_Highfield/registrations',
        contentType: 'application/json',
        method: 'PUT',
        data: {sessionid: sessionid, attendeeid: attendeeid},
        dataType: 'json',
        success: function (jsondata) {
            console.log(JSON.stringify(jsondata));
            document.getElementById("output").innerHTML = "";
             var success = jsondata['success'];
             $("#output").append("<p>"+ "Success: " + success +"</p>");
        }});
}

The error is as follows:
java.lang.NumberFormatException: Cannot parse null string

I tried adding a console log to ensure the variables weren’t null; they aren’t, yet one still gets sent as null in the ajax query.

How can I trigger React-to-Print using the print option in the context menu?

I have a React component that displays a table and I am using the React-to-Print library to enable printing functionality. Currently, the printing is triggered by a button click, but I would like to enhance the user experience by allowing them to initiate the print action using the print option in the context menu (right-click).

Here’s a simplified version of my component:

const PrintView = () => {
  const tableRef = useRef(null);
  const printRef = useRef();

  useEffect(() => {
    const handleKeyDown = (event) => {
      if ((event.ctrlKey || event.metaKey) && event.key === 'p') {
        event.preventDefault();
        if (printRef.current) {
          printRef.current.handlePrint();
          window.focus();
        }
      }
    };

    document.addEventListener('keydown', handleKeyDown);

    return () => {
      document.removeEventListener('keydown', handleKeyDown);
    };
  }, []);

  const handleAfterPrint = () => {
    window.focus();
  };

  const handleMouseRightClick = () => {
    // How can I trigger the React-to-Print functionality here?
  };

  return (
    <div onContextMenu={handleMouseRightClick}>
      <ReactToPrint
        content={() => tableRef.current}
        ref={printRef}
        onAfterPrint={handleAfterPrint}
      />
      <table ref={tableRef}>
        {/* Table contents */}
      </table>
    </div>
  );
};

I have already set up the context menu event using onContextMenu, but I’m not sure how to trigger the React-to-Print functionality from there. I attempted to find a solution by searching online documentation and examples, but I couldn’t find any specific guidance on how to achieve this integration.

My expectation is that when a user right-clicks within the component, the context menu appears and selecting the print option should trigger the React-to-Print functionality, resulting in the table being printed.

I would greatly appreciate any insights or suggestions on how to accomplish this functionality. Thank you!

How to update a dynamically added row values of a table?

I have a table that the rows are dynamically added using javascript:

<div class="bg-white p-3" id="IPCRTable"> 
      <div class="hotel pb-4 table-bordered"> 
        <div style="overflow-x:auto;">
          <table class="table" id="table" name="table">
           <thead>
              <tr class="table-active">
                <th scope="col" rowspan="2">Output <br>(A)</th>
                <th scope="col" rowspan="2">Success Indicators<br>(Targets + Measures)<br>(B)</th>
                <th scope="col" rowspan="2">Actual Accomplishments<br>(C)</th>
                <th scope="col" colspan="4">Rating<br>(D)
                  <table class="table table-borderless" id="rating">
                    <tr>
                      <td>Q</td>
                      <td>E</td>
                      <td>T</td>
                      <td>A</td>
                    </tr>
                  </table>
                </th>
                <th scope="col" rowspan="2">Remarks<br>(E)</th>
                <th scope="col" rowspan="2">Action</th>
              </tr>
           </thead>
            <tbody id = "tbody">
          <!-- to be filled by javascript-->
            </tbody>
          </table> 
        </div>
      </div>

here is the modal that adds values to the row that will be appended onto my table:

</div>
    <div class="d-grid gap-2 d-md-flex justify-content-md-end align-items-center">
      <button class="btn btn-success btn-sm" role="button" id="addheader" aria-pressed="true" data-bs-toggle="modal" data-bs-target="#addHeader">ADD HEADER</button>
      <button class="btn btn-success btn-sm" role="button" id="addtask" data-bs-toggle="modal" data-bs-target="#exampleModal" aria-pressed="true">ADD OUTPUTS/INDICATORS/ACCOMPLISHMENTS</button>
      <a href="Create_IPCR.php" class="btn btn-success btn-sm" role="button" aria-pressed="true">ADD SUB-HEADER</a>
    </div>

here is the javascript function that adds rows to my table,

function addRows(){
        var table = document.getElementById('tbody'),
            newRow = table.insertRow(table.length),
            cell0 = newRow.insertCell(0),
            cell1 = newRow.insertCell(1),
            cell2 = newRow.insertCell(2),
            cell3 = newRow.insertCell(3),
            cell4 = newRow.insertCell(4),
            cell5 = newRow.insertCell(5),
            cell6 = newRow.insertCell(6),
            cell7 = newRow.insertCell(7),
            cell8 = newRow.insertCell(8),
            outputA = document.getElementById("outputA").value,
            indicatorB = document.getElementById("indicatorB").value,
            accomplishmentC = document.getElementById("accomplishmentC").value;

            cell0.innerHTML = outputA;
            cell1.innerHTML = indicatorB;
            cell2.innerHTML = accomplishmentC;
            cell3.innerHTML;
            cell4.innerHTML;
            cell5.innerHTML;
            cell6.innerHTML;
            cell7.innerHTML;
            cell8.innerHTML = '<button class="btn btn-success btn-sm" role="button" data-bs-toggle="modal" data-bs-target="#editData" aria-pressed="true" name="tdName" id="editModal"><span class="fas fa-edit"></span></button><a href="#" class="btn btn-info btn-sm" role="button" aria-pressed="true"><span class="fas fa-comment"></span></a> <button class="btn btn-danger btn-sm" role="button" aria-pressed="true" name = "deletebtn" id="deletebtn" onclick= "deleteRow(this)"><span class="fas fa-trash" ></span></button>';
           
    };

as you can see from the function, there is a group of bootstrap buttons on cell8 that are supposed to be able to edit, delete, and add a comment on the row (though im not really sure how to implement that, i will just figure it out next time)

I successfully made the delete button to work, but I’m having trouble making the edit button work. What’s supposed to happen is when it is pressed, a modal would pop up and then it would take the users new value, after hitting the save changes button on the modal, its supposed to edit the data of that certain row without reloading the page.

I know I’m supposed to get the rowIndex of that row… but other than that I’m completely stumped. How can I make this button work?

I have a windows application in which we are using a chromium browser to open new html dialog having vuetify components

Is there any way we can extend the combobox of Vuetify to open beyond the frame of dialog…>?

Combobox dropdown

I was not able to find any useful suggestion which would help me achieve that..as the background is MFC so we have only that much html space..which is inside the chromium browser, so I suppose it’s not achieveable, but is there any hack..>?