How to uncomment inline script in DOM

Say I have an inline script in my DOM that’s been commented out:

<!-- <script type type='text/javascript' id='my-script'>
  alert('Boo!');
</script> -->

I can successfully find said comment in the DOM, but if I

const script = comment.nodeValue;
comment.replaceWith(script);

The comment does indeed get replaced in the DOM; however, it gets replaced by a text node, not a script node.

function myFunction() {
  const locator = document.getElementById('foo');
  let comment = locator.nextSibling;

  if ( 3 === comment.nodeType ) {
    comment = comment.nextSibling;
  }

  if ( 8 !== comment.nodeType ) {
    console.warn('Oops! That's not a comment!');
  } else {
    const script = comment.nodeValue;
    comment.replaceWith(script);
  }
}
    <div id='foo'></div>
    <!-- <script type type='text/javascript' id='my-script'>
      alert('Boo!');
    </script> -->
    <button onclick="myFunction()">Click me</button>

Is there a way to insert it as a script other than by regex parsing the comment.nodeValue and manually building up a script node?

Option hide on second selection

I facing a problem in HTML and JavaScript, when I select color it’s work fine but when I select any Cell option red box and its disappear from screen
also check my screen shot.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Show Hide Elements Using Select Box</title>
<style>
    .box{
        color: #fff;
        padding: 20px;
        display: none;
        margin-top: 20px;
    }
    .red{ background: #ff0000; }
    .green{ background: #228B22; }
    .blue{ background: #0000ff; }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("select").change(function(){
        $(this).find("option:selected").each(function(){
            var optionValue = $(this).attr("value");
            if(optionValue){
                $(".box").not("." + optionValue).hide();
                $("." + optionValue).show();
            } else{
                $(".box").hide();
            }
        });
    }).change();
});
</script>
</head>
<body>
    <div>
        <select>
            <option>Choose Color</option>
            <option value="red">Red</option>
            <option value="green">Green</option>
            <option value="blue">Blue</option>
        </select>
    </div>
    <div class="red box">
        <select>
           <option>Cell One</option>
           <option>Cell Two</option>
           <option>Cell Three</option>
           <option>Cell Four</option>
        </select>
    </div>
    <div class="green box">You have selected <strong>green option</strong> so i am here</div>
    <div class="blue box">You have selected <strong>blue option</strong> so i am here</div>
</body>
</html>

You can also run this code live on https://www.tutorialrepublic.com/codelab.php

enter image description here

javascript : Identify the form in the loop after submission?

I have a loop that creates 4 forms in the view And I put a button for each form to submit the form? What solution would you suggest to find out which form was submitted?
Html :

@foreach (var item in 4){
<form id="Form_ImgGallery" method="post">
    <div class="box_galleryimg col-lg-3 col-md-3 col-sm-6 col-xs-12">                       
        <input type="file" class="form-control">
        <div class="form-group">
            <input  type="submit" class="btn btn-info waves-effect" value="upload">
        </div>
    </div>
</form>

}

How to make the second Function await until the first function gets done?

Hi I am a javascript beginner, and trying to figure out how to make appendElement wait until createForm done, without using setTomeout(). As createForm is a div pop up with a button fires updateValues(). I want to appendElement to wait until updatesValues() sets localStorage values so that change on localStorage is going ot be reflected. AppendItem creates card based on values in localStorage. Currently, i have to refresh page to see the result on local storage. I tried use async, but appendElement would never wait.
Let me know your insight. Thanks!

Create form

Pop up

Current outcome

Prefabl outcome

JS

async function addPlace (){
    await createForm(idNum);
    appendElement("listParent", idNum)
    idNum += 1  
};

async function createForm(number){
        console.log(`locationName_${number}`)
        let items = `key, phone, book,...`
    
        let newForm = `
        <div id="container" class="d-flex align-items-stretch">
        <div class="reveal-modal d-flex flex-column bd-highlight mb-3" id="exampleModal">
            <div class="mb-3 d-flex flex-column ">
                <label for="locationName" class="form-label">Location</label>
                <input type="name" class="form-control" id="updateLocationName_${number}" placeholder="Location Name">
    
                <label for="Lost items" class="form-label">Lost items<br>Please separate items with comma (,)</label>
                <input type="name" class="form-control" id="updatedLocationItems_${number}" placeholder="${items}">
            </div
            <div>
                <button class="btn btn-primary" onclick="deleteListCard('container')">Cancel</button>
                <button class="btn btn-primary" onclick="updateValues(${number})">Add</button>
            </div>
        </div>
    </div>
        `
        const parentDom = document.querySelector('body')
        parentDom.innerHTML += newForm
        await updateValues(number)

    }

async function updateValues(number){
    console.log(`${number} is updated!`)
    let updatedName = document.getElementById(`updateLocationName_${number}`).value
    let updatedItems = document.getElementById(`updatedLocationItems_${number}`).value
    console.log(updatedName)
    console.log(updatedItems)

    const itemArr = updatedItems.split(',')

    // set Array

    localStorage.setItem(`locationName_${number}`, updatedName)
    localStorage.setItem(`locationItems_${number}`, JSON.stringify(itemArr))
    deleteListCard('container') //exit popup
}

//Appned List
function appendElement(parentID, number){
    const parentDom = document.getElementById(parentID)

    if(document.getElementById("stevens_barbar")){
        deleteListCard("stevens_barbar")
    }

    let location = localStorage.getItem(`locationName_${number}`)
    let storedItems = JSON.parse(localStorage.getItem(`locationItems_${number}`))
    
    parentDom.innerHTML += `
    <div id="location_${number}">
        <h1>${location}</h1>
        ${generateCheckbox(storedItems)}
        <div>
            <button class="btn btn-primary" onclick="updateLocalstorage('${number}')">Edit</button>
            <button class="btn btn-warning delete_button" onclick="deleteListCard('location_${number}')">Delete</button>
        </div>
    </div>
    `
}

JQuery Refactoring ( separate codes by functionality, improve readability)

recently I have been studying way of refactoring Jquery code to handling UI events.

Jquery is on the down hill due to invention of MVVM frame works and library such as angler, vue, react therefore It was hard to find documents which wrote recently.

So, I write my result via this document and hope reviewing my decision from skilled developers such as you.

<purpose of refactoring>

  • separate codes by functionality
  • improve readability

Jquery source is composed by html elements’ event. So I usually saw coding style below

$("#nameText").on("input", function () {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}
$("#surveyText").on("input", function () {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}
 $("#submitBtn").on("click", function (e) {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}

It’s pretty simple and we can read which action is needed and conducted by some elements action.
But that could be verbose and confusing us because there are many roles and we have to check the element’s css attributes which related selector.
Some times, css class name or id don’t have proper name which not enough explain role of element or in case of, use navigator function like find() or selector by element hierarchy.

$("#s_f01").find("li").on("click", function () {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}
$(".s_btn01").on("click", function () {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}
$("#submitBtn").on("click", function (e) {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}

And functions for particular element could be spread out by modified history for adding function or some of modification.

//Codes for Survey Form (line 10 - 200)
$("#s_f01").find("li").on("click", function () {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}
$(".s_btn01").on("click", function () {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}
$("#submitBtn").on("click", function (e) {
 //Some of actions to control html elements, extract data, validation, ajax request, etc,,, 
}

,,,

//added after statistics function for enable Survey form action(line 1200) 
$("#SurveyFormOpenBtn").on("click", sendStatisticInfo_SurveyFormOpened());

I don’t know how to fix problem with events?

I am building a battleship game in js. I added event listener on targeted element of the grid and I am trying to make a function that takes one argument(boat length) and according to that argument, function should render the boat on my grid. Problem is that no matter what argument I passed in to the function it renders the boat same length. I think that problem is event listener that stays the same when I clicked the element first time.

Here is the code:

function placeBoat (boatLength){
    domElements.yourGrid.onclick = function(event){
        let target = event.target;
        console.log(event)
        let clickedPosition = target.id
        let clickedPositionId = clickedPosition.slice(4, 6)
        let clikedPositionInt = parseInt(clickedPositionId);
        for(let i = 0; i < boatLength; i++){
            target.style.background = "green";
            target = document.querySelector("#cell" + clikedPositionInt)
            clikedPositionInt += 10;
        }
    }
}

domElements.boat1Button.addEventListener("click", placeBoat(3))
domElements.boat2Button.addEventListener("click", placeBoat(4))
domElements.boat3Button.addEventListener("click", placeBoat(5))

Thanks in advance for your help.

How to Interact between js table and python code

I have python code that pulls data from a web browser, my local file system, and Outlook emails, and puts the data into an sqlite dB.

I want to be able to use this code from a file that displays the data in a table. For example, ‘open the email ID from this table cell.’ Datatables is a simple, nice looking table that has the functionality I need: https://datatables.net/ . However, if I make a flask jinja template html file with this js code, I’ve read that I would not be able to interact with my local files and programs because of limitations from browsers for security purposes. Is this the case? Even if I’m not hosting this file somewhere – everything is local?

The other option I was considering, is to use a gui – tkinter or pysimplegui. but can I use jQuery and Javascript to create the data table from there?

Or, would I need electronjs?

I don’t want to spend a few hours going down one of these roads if it turns out to be a dead end.

JavaScript Sort by number in a string

How could i sort e.g an array like this one:

[
  '<@520968882077433856> is level **7,64** _(18115.5 total xp)_',
  '<@289037609274048513> is level **7,07** _(14473 total xp)_',
  '<@672835870080106509> is level **8,25** _(22473.5 total xp)_',
  '<@536686935134175254> is level **6,22** _(10184.5 total xp)_',
]

I would like to sort it by the amount of total xp, so the number within the brackets.

how to run a file once in nodejs just once

I am saving my .env content dynamically from AWS secrets manager but I want to save all values just once the server starts. What should be the approach?
I am using typescript

getSecrets("key").then((keys: any) => {
 const originalKeys = JSON.parse(keys);
 for (const key in originalKeys) {
  if (originalKeys.hasOwnProperty(key)) {
    appendFileSync(
      __dirname + "/.env",
      `${key}='${originalKeys[key]}'n`
    );
  }
}

How to check if an array of dates has the value of an array of objects specific value inside and push to a new array [duplicate]

Im looking to take an array of dates(from range selection) and then run through each date and check if that date exists in and list of objets.

If the date value is not in the list of objects then I would like to push the value of 0 to a new array if the value does exits in the array of objects I would like to take push objects “amount” from the specific object where the date is to the new array. Please see example below

const newArray = []

const dateArray1 = [‘2022-02-03′,’2022-02-04′,’2022-02-05′,’2022-02-06′,’2022-02-07′,’2022-02-08’]

const objArray2 = {“orders”:[

{
“id”: 4419830775973,
“sale_amount” :200,
‘date’:’2022-02-03′
},

{
“id”: 44198340775973,
“sale_amount” :100,
‘date’:”2022-02-05″
},

{
“id”: 4419660775973,
“sale_amount” :700,
‘date’:’2022-02-08′
},

],}

New pushed array would be – newArray[200, 0, 100, 0, 0, 700]

All help would be appreciated thanks

how to throw new Error in axios when response.data.code is not 200

I am using an old API.
Which responds to every call with 200 OK.

{
    "msg": "invalid",
    "result": null,
    "code": 400
}

I need to trow an error somehow. So the catch block can handle it.

axiosInstance.interceptors.response.use(
  (response) => {
    if (response.data.code < 200 || response.data.code > 399) Promise.reject(response.data.msg);
    return response;
  },
  (error) =>
    Promise.reject(
      (error.response && error.response.msg) || "مشکلی پیش امده است"
    )
);

Not Able to Update Syntax in Prism.js With JavaScript keyup in Input Element

Can you please take a look at this code and let me know why I am not able to update syntax in Prism? I wan t to add value from #column to #column-out inside the <pre><code class="language-python"></pre></code>

$("#column").keyup(function(e) {
   var str = $(this).val();
   $('#column-out').text(str);
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/themes/prism-tomorrow.min.css" integrity="sha512-vswe+cgvic/XBoF1OcM/TeJ2FW0OofqAVdCZiEYkd6dwGXthvkSFWOoGGJgS2CW70VK5dQM5Oh+7ne47s74VTg==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/prism.min.js" integrity="sha512-RDQSW3KoqJMiX0L/UBgwBmH1EmRYp8LBOiLaA8rBHIy+7OGP/7Gxg8vbt8wG4ZYd29P0Fnoq6+LOytCqx3cyoQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.28.0/components/prism-python.min.js" integrity="sha512-AKaNmg8COK0zEbjTdMHJAPJ0z6VeNqvRvH4/d5M4sHJbQQUToMBtodq4HaV4fa+WV2UTfoperElm66c9/8cKmQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

<div class="input-group mb-3">
  <span class="input-group-text" id="basic-addon1">Column(s)</span>
  <input type="text" class="form-control" placeholder="Column(s)" id="column" aria-label="Columns" aria-describedby="basic-addon1">
</div>
<pre><code class="language-python">import pandas as <span id="column-out"></span>
</code></pre>

Why do window.innerWidth and window.devicePixelRatio differ between Chrome and Firefox

After updating chrome version (to 102)., the fonts on my web page are very small.
In firefox they show up ok.
(If I enable “Toggle Device Toolbar” in Chrome, to emulate e.g. a mobile device, the font sizes are reasonable).

The reported window.innerWidth is completely different when displaying the page
in fireforx and chrome.

In Firefox:

window.innerWidth: 769
window.innerHeight: 968
window.devicePixelRatio 1.0

In Chrome:

window.innerWidth: 7204
window.innerHeight: 1780
window.devicePixelRatio 0.25

In Chrome for emulating a mobile device:

window.innerWidth: 349
window.innerHeight: 716
window.devicePixelRatio 2

How come the values differ so much?
Specifically, why does window.devicePixelRatio differ?
I’m running the browsers on the same hardware. The Screen size is:

width: 1920
height: 1080

Thanks

Props value is Undefined while passing through Context API in REACT

My Provider File of Context API (Exp file)

import react form 'react';
import {createContext} from "react";

export const ContextforFile = createContext();

export function ContextData(props){
   let rdata=props.data
   <>
  <p>{rdata}</p>  //I am able to Get the Data here NO ISSUES TILL HERE
  <ContextforFile.Provider value={rdata} >{props.children}</ContextforFile.Provider>
  </>
}

function A() {
  return (
    <div>
      <ContextData data="Sara" />
    </div>
  );
}

export default A;
    

My App.js File

import Exp, { ContextData } from './afterlogin/patirel/patmain';
import Experiment from './experi';
import {Routes,Route} from 'react-router-dom';
import * as React from 'react';

function App() {
 

  return (

   <ContextData>

    <div>
    <Routes>
      <Route index element={<Exp/>} />
      <Route path="/experi" element={<Experiment/>} />
      </Routes>

    </div>
    </ContextData>

  );
}

export default App;

only props.data value is not coming here while other values can be easily obtained
This is Experi file Where I want to get my values my Consumer File



import * as React from 'react';
import { useContext } from 'react';
import { ContextforFile } from './afterlogin/patirel/patmain';

export default  function Experi(){

const first= useContext(ContextforFile);
return(
    <div>
   <h1>ISSUE is Here Other VALUES are COMING BUT NOT props.data: {first}</h1>
    </div>
);

  }

Please help! It’s been days and i cannot figure out what am i missing? How can I resolve it?

The child component properties are getting overlapped. Don’t know why?

I am new to Angular. Tried to make a button/badge component. But when I am trying to use it more than one time, the css are getting overlapped and misbehaving. I think that when new instance of the badge component got created the second time, it overwrote on the first one, not sure.

app.html

<div class="container">
  <app-badge [title]="'First'" [bgColor]="'Green'"></app-badge>
  <app-badge [title]="'Second'" [bgColor]="'Blue'"></app-badge>
</div>

badge.html

<div class="container">
    {{title}}
</div>

badge.ts

import { Component, ElementRef, Input, OnInit } from '@angular/core';

@Component({
  selector: 'app-badge',
  templateUrl: './badge.component.html',
  styleUrls: ['./badge.component.css']
})
export class BadgeComponent implements OnInit {

  @Input()
  title : String="Badge";
  @Input()
  bgColor : String="";
  @Input()

  constructor() { }

  ngOnInit(): void {
    
  }

  ngAfterViewInit(){
    const ele = (document.getElementsByClassName('container')[0]);
    ele.setAttribute("style", `background-color:${this.bgColor};`);
  }

}