Issues involving scope of functions in javascript

I happened to find an issue with the weird behaviour of scope in the javascript

const obj  = {
    name : "alex",
    isLoggedIn : true
};

if (true) {
    function takeobject(str) {
        console.log("hello1");
        return `my name is ${str}`;
    }
}

function takeobject(myobj) {
    console.log("hello2");
    return myobj['name'] ? `the object is ${myobj['name']}` : "hello there!";
}

console.log(takeobject(obj));

The output is :

hello1
my name is [object Object]

I created an object name obj with two members name and isLoggedIn
then in the if statement with true condition i created the function takeobject which takes parameter str (supposed to be string).

Then another function in global scope with same name takeobject which takes parameter myobj (supposed to be an object).

Now, after executing the code, the console prints my name is [object Object] i.e., it calls the function inside the if block even though the passed argument is an object.

Why the global function takeobject is not called?

I tried using both functions in same and different if(true) block(s) then the the function takeobject(myobj) is called as it is redefining it but when doing the above, the function takeobject(str) is being called instead of function takeobject(myobj) even though takeobject(myobj) is global and it should redefine it.

const obj  = {
    name : "alex",
    isLoggedIn : true
};

if (true) {
    function takeobject(str) {
        console.log("hello1");
        return `my name is ${str}`;
    }
    
    function takeobject(myobj) {
    console.log("hello2");
        return myobj['name'] ? `the object is ${myobj['name']}` : "hello there!";
    }
}

console.log(takeobject(obj));

To call popup component from main component based on boolean flag

I have a main component and a popup component and i am using popupvisible boolean flag to open it.
First time it opens up but second time it is not opening .There are two components

main component.html
<button icon="add" type="normal" text="Add fruit" style="margin-left: auto;" (onClick)="addfruit()"> <button> <app-add-crew [item]="popupVisible"></app-add-crew>
child html

``<dx-popup 
            [width]="1000"
            [height]="580"
            [showTitle]="true"
            title="Add Crew"
            [dragEnabled]="false"
            [hideOnOutsideClick]="true"
            [showCloseButton]="true"
            container=".dx-viewport"
            [(visible)]="item"
        >`
`
 maincomponent.ts
  

addfruit() { this.popupVisible = true; }

Can anybody help how to pass boolean value to next component so that it opens everytime

let me know if more details needs to be provided

How should I add values in 2-level array format to a formGroup?

I want to insert values, and then read them like this in the frontend (key is 0, 1, 2, 3…):

form?.get(['configuration','configurationMilestone', field?.nameFieldInitial1, key])

This is the method I build the form:

 createControlFormArray(configuration, group) {
    const config = this.form.get('configuration') as FormGroup;
    const newFormArray = this.fb.array([]);

    configuration.forEach(() => {
        newFormArray.push(this.fb.control(null));
    });

    const configGroup = configuration.reduce((acc, item, index) => {
        acc[item] = newFormArray.at(index);
        return acc;
    }, {});

    const newFormGroup = this.fb.group(configGroup);
    config.addControl(group, newFormGroup);
 }

This is the method I want to add the value, but it’s not adding the values, it gives an error:

createFormListInitialWithDefaultValue(config, dataMark, disabled = false) {
    
    const formArray = this.form.get(['configuration','configurationMilestone', dataMark.nameFieldInitial1]) as FormArray;
     formArray.value.push(this.fb.control(dataMark.defaultValue1));
    
}

To create the form, you basically take part of the context of a constant above:

const dataMarkInitial = {
        labelName1:categoriesMenu.LABELS.RESULTS_MARKER_LABEL_1,
        fieldProgress1: 'toAchieveProgressInitial',
        fieldProgress2: 'toSurpassProgressInitial',
        nameFieldInitial1:'resultsMarkerNameInitial',
        nameFieldInitial2:'resultsMarkerPercentInitial',
        nameFieldFinal1:'resultsMarkerNameFinal',
        nameFieldFinal2:'resultsMarkerPercentFinal',
        placeholder1: categoriesMenu.LABELS.RESULTS_MARKER_PLACEHOLDER_INITIAL_1,
        placeholderStart: '0',
        placeholderGoal: '100',
        labelName2:categoriesMenu.LABELS.RESULTS_MARKER_LABEL_2,
        matchesProgress: categoriesMenu.LABELS.MATCHES_PROGRESS,
        ruleProgress1: categoriesMenu.LABELS.RESULTS_MARKER_RULE_1,
        ruleProgress2: categoriesMenu.LABELS.RESULTS_MARKER_RULE_2,
        defaultValue1:'',
        defaultValue2:null,
        defaultValue3:'PROPORTIONAL_CAL',
        defaultValue4:null,
        progressOptions:[
            {id: 'PROPORTIONAL_CAL', name: categoriesMenu.LABELS.OPTIONS.CALCULATED_PROPORTIONALLY},
            {id: 'BACK_PROGRESS', name: categoriesMenu.LABELS.OPTIONS.PROGRESS_FROM_PREVIOUS_MILESTONE}
        ],
        disabled: true
    }

    const milestoneInitial = [
        dataMarkInitial.fieldProgress1,
        dataMarkInitial.fieldProgress2,
        dataMarkInitial.nameFieldInitial1,
        dataMarkInitial.nameFieldInitial2,
        dataMarkInitial.nameFieldFinal1,
        dataMarkInitial.nameFieldFinal2,
        'progressOptions'
    ]
    //create form
    this.createControlFormArray(milestoneInitial, 'configurationMilestone');

How to select default value that should display the records in aura from the drop down menu

I have multiple fields on UI and i am getting the data based on the feilds so for the specific field() it has two values in the dropdown menu( yes and No). So whenever i open the UI I want the records saying yes automatically but it should allow me to select for no from the drop-down. Any idea how can i acheive this.

<td class="filterrow">

<lightning:select aura:id="status" name="Status" onchange="(!c.SubSearch)"

value="{!v.status)" variant="label-hidden">

<option value=""></option>

<option value="Yes">Yes</option>

<option value="No">No</option>

</lightning:select>

</td>

We have it in component along with the attribute
And subserach in controller with

Status= component. Get(v.Status)

How can I make three diffrent overlays with three images?

I’m currently in the process of creating a website with a gallery.

I want to have three images on which you can click, and three different galleries apear. For example, you click on the first picture and than a gallery will appear.

I have tried it with the help of the overlay element, but the problem is now no matter which image I click, the same gallery appears.

<div class="Galerie">
  <div class="column">
    <div style="padding:10px">
      <img src="img/A1.jpg" onclick="on()" alt="Snow" style="width: 100%;">
    </div>
  </div>
  <div class="column">
    <div style="padding:10px">
      <img src="img/B3.jpg" onclick="on()" alt="Forest" style="width:100%">
    </div>
  </div>
  <div class="column">
    <div style="padding:10px">
      <img src="img/C1.JPG" onclick="on()" alt="Mountains" style="width:100%">
    </div>
  </div>
</div>

<div id="overlay" ondblclick="off()">
  <div id="text" img data-src="">


    <!-- The four columns -->
    <div class="row">
      <div class="Reiheeins">
        <img src="img/A1.jpg" alt="Nature" style="width:100%" onclick="myFunction(this);">
      </div>
      <div class="Reiheeins">
        <img src="img/A2.jpg" alt="Snow" style="width:100%" onclick="myFunction(this);">
      </div>
      <div class="Reiheeins">
        <img src="img/A3.jpg" alt="Mountains" style="width:100%" onclick="myFunction(this);">
      </div>
      <div class="Reiheeins">
        <img src="img/A4.jpg" alt="Lights" style="width:100%" onclick="myFunction(this);">
      </div>
    </div>

    <div class="container">
      <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
      <img id="expandedImg" style="width:100%">
      <div id="imgtext"></div>
    </div>

  </div>
</div>




<div id="overlay" ondblclick="off()">
  <div id="text" img data-src="">


    <!-- The four columns -->
    <div class="row1">
      <div class="Reihezwei">
        <img src="img/B3.jpg" alt="Nature" style="width:100%" onclick="myFunction(this);">
      </div>
      <div class="Reihezwei">
        <img src="img/B4.jpg" alt="Snow" style="width:100%" onclick="myFunction(this);">
      </div>
      <div class="Reihezwei">
        <img src="img/B6.jpg" alt="Mountains" style="width:100%" onclick="myFunction(this);">
      </div>
      <div class="Reihezwei">
        <img src="img/B2.jpg" alt="Lights" style="width:100%" onclick="myFunction(this);">
      </div>
    </div>

    <div class="container">
      <span onclick="this.parentElement.style.display='none'" class="closebtn">&times;</span>
      <img id="expandedImg" style="width:100%">
      <div id="imgtext"></div>
    </div>





    <script>
      function on() {
        document.getElementById("overlay").style.display = "block";
      }

      function off() {
        document.getElementById("overlay").style.display = "none";
      }

      function myFunction(imgs) {
        var expandImg = document.getElementById("expandedImg");
        var imgText = document.getElementById("imgtext");
        expandImg.src = imgs.src;
        imgText.innerHTML = imgs.alt;
        expandImg.parentElement.style.display = "block";
      }
    </script>

React-hook-form: Reset / Empty An Input File

I am new to React and I want to create a button to reset/empty the input file for edit functionality. I am using MUI and React-hook-form. When I clicked the reset button, the image had already changed, and the input file also stated ‘No file chosen’, however when I clicked the submit button, the file was still there and sent to my backend. However, it should be null and hence will not be sent to the backend.

I am trying by using useRef and setting the value of the input file to null, I tried console.log for checking, and the value is null. But the value sent is still the latest image I uploaded. This is my full code:

import React, { useState, useEffect, useRef } from "react";
import { Box, TextField, IconButton } from "@mui/material";
import LoopIcon from "@mui/icons-material/Loop";
import { Controller } from "react-hook-form";

export default function MyInput(props) {
  const { name, control, label, width, image } = props;
  const [file, setFile] = useState();
  const [old, setOld] = useState();
  const inputFile = useRef(null);

  const handleReset = () => {
    if (inputFile.current) {
      inputFile.current.value = null;
      document.querySelector(".image").src = old;
    }
  };

  useEffect(() => {
    setOld(document.querySelector(".image").src);
  }, []);

  return (
    <Box sx={{ width: { width } }}>
      <Controller
        name={name}
        control={control}
        render={({ field: { onChange, value }, fieldState: { error } }) => (
          <>
            <Box>
              <TextField
                inputRef={inputFile}
                sx={{ maxWidth: "75%" }}
                onChange={(e) => {
                  onChange(e.target.files[0]);
                  setFile(URL.createObjectURL(e.target.files[0]));
                }}
                id="outlined-basic"
                label={label}
                variant="outlined"
                value={value?.fileName}
                type="file"
                InputLabelProps={{
                  shrink: true,
                  accept: "image/png, image/jpeg",
                }}
                error={!!error}
                helperText={error?.message}
              />
              <IconButton onClick={handleReset}>
                <LoopIcon />
              </IconButton>
            </Box>
            <img
              className="image"
              src={file ? file : image}
              alt={file ? "Error: Image cannot be displayed" : undefined}
              style={{ maxWidth: "100%", height: "auto", marginTop: "20px" }}
            />
          </>
        )}
      />
    </Box>
  );
}

Any idea how to make the value of my input file become null when I click the reset button? What am I missing. Thank you for your help.

Unable to change value of input box to selected option of comboBox

I’m following an introduction-course to HTML, in this particular demo I made a comboBox:

//Combobox to select a course
<div>
        <select id="courses" multiple size="3" onchange="choiceMade(this.value);">
            <option value="" selected>--Choose--</option>
            <option value="Angular">Angular</option>
            <option value="ReactJS">React</option>
            <option value="VueJS">Vue</option>
            <option value="JavaScript">JavaScript</option>
            <option value="Python">Python</option>
       </select>
</div>

The selected value should be printed in this input box using JavaScript:

//Inputbox where above selected course should be printed
<div>
     <label class="standoutLabel">Favorite Course:</label>
     <input type="text"  id="courseName">
</div>

The course tells me the function to do this should be this:

//Function to print selected choice in inputbox
function choiceMade(choice) {
    document.getElementByID("courseName").value = choice;
}

In the video it works fine, but for me… Nope…Nothing…Nada

How do I get this to work? What am I missing?

I tried adding a function call to get the value of choiceMade so it would input the choice in the <input>, but it just isn’t working.

Capture click events on selected if not all toolbar button

Toolbar buttons like: Insert/edit link, Insert/edit images, Insert/edit media, Insert templates and Source code

I already tried the

editor.on("ExecCommand", function(e) { // checking of e.command });

Only the first Insert/edit link works as I have a code that inserts a custom button right beside the URL button.

tinymce 6.7.0

Expected to insert a custom code on the click events on the tinymce toolbar buttons.

Best data structure in Javascript to access nested elements by index?

I want to create a form of sorts that displays questions that the user can navigate to access other answers/questions. Depending on the answer, it will display another question/answer.

Let’s say I have:

var json = 
     {
      "Did you restart the computer?": [
        {
          "Yes": [
            {
              "Is the software running?": [
                {
                  "Yes": "Cannot help",
                  "No": "Open it"
                }
              ]
            }
          ],
          "No": "Please restart it"
        }
      ]
    }

Is there a data structure that lets me access the option Yes/No by index? For example, doing json[0][0] or json[0][1].

Let’s say the user selects Yes on the first set of options. I know I can access the keys by doing

Object.keys(json["Did you restart the computer?"][0]["Yes"][0])
>> ['Is the software running?']

And if the user selects Yes again, I know I can access the keys by doing

Object.keys(json["Did you restart the computer?"][0]["Yes"][0]["Is the software connected to the server?"][0])
>> (2) ['Yes', 'No']

But this seems somehow cumbersome. Is there a better way to do this so I can access keys/values using indexes (ex. json[0][0][1])?

Sorting an array based on an array of IDs with different RANGE

This question is not duplicated or already answered.

I found and I knew how to sort an array based on another array of IDs but with the same RANGE LIKE THIS TOPIC HERE.

I have an array like this:

matches = [ 
            "league": {
            "id":6,
            "score": "score 1",
            },
            "league": {
            "id": 9,
            "score": "score 2",
            },
            "league": {
            "id": 12,
            "score": "score 3",
            },
            "league": {
            "id": 6,
            "score": "score 4",
            },
            "league": {
            "id": 12,
            "score": "score 5",
            },
            "league": {
            "id": 3,
            "score": "score 6",
            },
            "league": {
            "id": 83,
            "score": "score 7",
            },
            "league": {
            "id": 76,
            "score": "score 8",
            },
      ]

The issue that I have a a very big complex data (above an example of data), I tried to sort this example following a list of IDs like that var ids =[6,12,3]

I did something like this:

 result = [];

 matches.forEach(function (a) {
result[ids.indexOf(a.league.id)] = a;
});

console.log(result);

But that give only the sort of three first IDs [6,12,3] and ignore the other IDs.

it’s possible to sort the array like this:

    matches = [ 
            "league": {
            "id":6,
            "score": "score 1",
            },
            "league": {
            "id": 6,
            "score": "score 4",
            },
            "league": {
            "id": 12,
            "score": "score 3",
            },
            "league": {
            "id": 12,
            "score": "score 5",
            },
            "league": {
            "id": 3,
            "score": "score 6",
            },
            "league": {
            "id": 9,
            "score": "score 2",
            },
            "league": {
            "id": 83,
            "score": "score 7",
            },
            "league": {
            "id": 76,
            "score": "score 8",
            },
      ]

images and svg icons can’t load in node.js

Images and svg files do not show up on the page and load alt property instead

    const http = require("http");
    const fs = require("fs");
    const path = require("path");
    
    const express = require("express");
    var app = express();
    app.use(express.static('public'));
    
    const server = http.createServer((req, res) => {
      const filePath = path.join(__dirname, req.url === "/" ? "index.html" : req.url);
     ` const extname = path.extname(filePath);
      
      const contentType = {
        ".html": "text/html",
        ".js": "text/javascript",
        ".css": "text/css",
        ".ttf": "font/ttf",
        ".jpg": "image/jpeg",
        ".png": "image/png",
        ".gif": "image/gif",
      };
    
      fs.readFile(filePath, "utf8", (err, content) => {
        if (err) {
          res.writeHead(500, { "Content-Type": "text/plain" });
          res.end("Internal Server Error");
          console.error(err);
          return;
        }
    
        res.writeHead(200, { "Content-Type": contentType[extname] || "text/plain" });
        res.end(content);
      });
    });
    
    const port = 3000;
    server.listen(port, () => {
      console.log(`Server running at http://localhost:${port}/`);
    });

I tried changing file paths and locations, changing adding mime-types in server, using express. Images still can’t load however i can see them downloaded in Network tab with devtools

Why does RenderItem need item deconstructed but keyExtractor doesn’t in a FlatList

I understand deconstructing, but I’m trying to understand why in a FlatList component one prop would need to deconstruct and another wouldn’t when they both have access to the same data.

For example in a FlatList component in React-Native why does renderItem need to deconstruct item but keyExtractor doesn’t?

Example code

const data = [
  { id: "1", text: "Item 1" },
  { id: "2", text: "Item 2" },
  { id: "3", text: "Item 3" },
];
 
// ---- APP COMPONENT ----
 
const App = () => {
  return (
    <FlatList
      data={data}
      renderItem={({ item }) => <div>{item.text}</div>}
      keyExtractor={(item, index) => item.id}
    />
  );
};
 
export default App;

P.s. I’m just trying to understand something and I have read the react doc’s for render props, I understand FlatList is just a wrapper component that exposes a bunch of props to work more easily with the list data, but I don’t get why renderItem and keyExtractor have to act differently when using that data.

I’ve tried to read the React docs to get a better understanding and googling this specific issue hasn’t helped me.

Javascript Deeplinking is not working, getting popup which I can not remove

If I click on the given link, it will take me to the chrome browser opening a popup with message “This site is opening another application” and if I allow it then gets another popup with “Something is wrong. the application couln`t be opened”.

Chrome browser is not redirecting to mobile schema url and giving popup with “Something is wrong. the application couln`t be opened”.

This only hapening in chrome browser. When I tried the same in safari it worked as expected.

I am using this small code. Only purpose is to redirect to the app if it is installed and if app is not sinatlled the ti twill redirect to app store.

var appLink = "mobile schema url";
if (feature != null) {
 appLink = "mobile schema url;
}
window.location.replace(appLink);
}
window.location.href = "app store url";

Expectation: Whenever link is clicked it should take you to the browser and asked for Opening the app if app is installed or take you to the app store if app is not installed.

fullcalendar io 6.1.8 add event filters

I need to add event filtering to my calendar

I added a special select for this and a function for this select that should update the calendar

But I had a problem that this function only works once. Let’s say I launch the calendar, select a filter, everything is displayed as it should. But when I try to immediately change the filter to another one, all the events disappear altogether, what’s the problem?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/index.global.min.js"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function() {
      var calendarEl = document.getElementById('calendar');

      var calendar = new FullCalendar.Calendar(calendarEl, {
        initialView: 'dayGridMonth',
        events: [
          {
            title: 'Event 1',
            start: '2024-01-01',
            dataFilter: 'filter1'
          },
          {
            title: 'Event 2',
            start: '2024-01-02',
            dataFilter: 'filter2'
          },
        ],
        eventClick: function(info) {
          alert('Event: ' + info.event.title);
        },
        headerToolbar: {
          left: 'prev,next today',
          center: 'title',
          right: 'dayGridMonth,timeGridWeek,timeGridDay'
        },
      });

      calendar.render();

      var filterSelect = document.getElementById('filterSelect');

      filterSelect.addEventListener('change', function() {
        var selectedFilter = filterSelect.value;

        var filteredEvents = calendar.getEvents().filter(function(event) {
          return selectedFilter === 'all' || event.extendedProps.dataFilter === selectedFilter;
        });

        calendar.setOption('events', filteredEvents);
      });
    });
  </script>
</head>
<body>
  <label for="filterSelect">Select event:</label>
  <select id="filterSelect">
    <option value="all">All events</option>
    <option value="filter1">Event 1</option>
    <option value="filter2">Event 2</option>
  </select>

  <div id="calendar"></div>
</body>
</html>