Disable submit button when Tags Input on textarea is empty

I created a form where users can input words in a textarea as tags and submit them as a string using JavaScript. The feature I want to add is to disable the submit button whenever the textarea is empty (does not contain any tags).

Here is what I have tried so far:

HTML

<form>
  <textarea onkeyup="success()" name="tags" id="tag-input1" required>
  </textarea>
  <p class="instruction">Press enter to add a new word</p>
  <!-- Disable Submit Button -->
  <input type="submit" id="submit" class="save" value="Submit">
</form>

JavaScript

function success() {
  if (document.getElementById("tag-input1").value === "") {
    document.getElementById('submit').disabled = true;
  } else {
    document.getElementById('submit').disabled = false;
  }
}

A demo and the rest of my JavaScript code on the tags input could be found HERE

How to handle unknown routes in Express

I am at a complete lost

app.js

app.use('/', userRoutes); app.use('/adminID', adminRoutes); app.all('*', (req, res, next) => { next(new AppError(Url Not Found ${req.originalUrl}, 404)); }) const ErrorHandler = require('./ErrorHandler.js'); app.use(ErrorHandler); module.exports = app;

How to reorder a object after array manipulation with specific order using JS

I have an array

[{"Name": "MyName","First Name": "ABS","Last Name": "ACS","College": [{"card": {"Name": "card1","Id": "id1"},"Status": "Active","Type": "add","Class": {"Class No": "123"},"Room": {"RoomA": "NULL","RoomB Number": "NULL"}},{"card": {"Name": "card1","Id": "id1"},"Status": "Active","Type": "add","Class": {"Class No": "123"},"Room": {"roomA": "NULL","RoomB Number": "NULL"}}],"Odd Structuring": null,"Accountable Class": "5663"}]

Since I need to flat this array, I have written the below logic

const uniqueKeys = Object.keys(
  arr.reduce((result, obj) => Object.assign(result, obj), {})
);

if (uniqueKeys.includes('College')) {
  arr.map((item) => {
    item.College.map((element, k) => {
      let getKeys = Object.entries(element);
      getKeys.forEach((data) => {
        if (typeof data[1] === 'object') {
          let keys = Object.keys(data[1]);
          keys.forEach((key) => {
            item[`${data[0]} - ${key} ${k + 1}`] = data[1][key];
          });
        } else {
          item[`College - ${data[0]} ${k + 1}`] = data[1];
        }
      });
    });
  });
  arr = arr.map(({ College, ...data }) => ({ ...data }));
  console.log(arr);
}

I am getting the result like this

[{"Accountable Class": "5663","Class - Class No 1": "123","Class - Class No 2": "123","College - Status 1": "Active","College - Status 2": "Active","College - Type 1": "add","College - Type 2": "add","First Name": "ABS","Last Name": "ACS","Name": "MyName","Odd Structuring": null,"Room - RoomA 1": "NULL","Room - RoomB Number 1": "NULL","Room - RoomB Number 2": "NULL","Room - roomA 2": "NULL","card - Id 1": "id1","card - Id 2": "id1","card - Name 1": "card1","card - Name 2": "card1"}]

But my expected result should be

{"Name" : "MyName","First Name": "ABS","Last Name": "ACS","card Name 1": "card1","card Id 1": "id1","College Status 1": "Active","College Type 1": "add","Class Class No 1": "123","Room RoomA 1": "NULL","Room RoomB Number 1": "NULL","card Name 2": "card1","card Id 2": "id1","College Status 2": "Active","College Type 2": "add","Class Class No 2": "123","Room RoomA 2": "NULL","Room RoomB Number 2": "NULL","Odd Structuring":null,"Accountable Class": '5663'}

Can anyone please help me to get the expected result

Warning error: Trying to access array offset on value of type null php

From javscript code I am comsuming an api rest using a fectch but I receive this error:

Warning error: Trying to access array offset on value of type null php

This api has been made in php. If I call this api from soap ui work fine but when I call this api from javscript code receive the error:

This is th javsacript code:

function compareValueKey(numInput) {

    let digit_key = document.getElementById("input_compare" + numInput).value;
    
    let configFetch = {
        method: "POST",
        body: "digit_key=" + digit_key + "&numInput=" + numInput,
        headers: {'Content-Type': 'application/x-www-form-urleancoded'}
    };

    let promesa = fetch("compareValueKey.php", configFetch);
    promesa.then(function(response){
        if(response.ok){
            console.log("Respuesta OK");
        }
        response.json().then(
            function(objectoJSON){
                let valido = objectoJSON.valido;
                let numInput = objectoJSON.n;
                document.getElementById("input_compare"+ numInput).nextElementSibling.innerHTML = valido;
            });
        }).catch(function (error){
            console.log('Error con la peticion' + error.message);
        });
}


This is php code:

<?php
session_start();
$key =1111;

$data = json_decode(file_get_contents('php://input'), true);
$digit_key  =  $data['digit_key'];

$numInput  =  $data['numInput'];

if($digit_key == substr($key, $numInput - 1, 1)){
    echo json_encode(array("valido" => "ok", "n" => $numInput));
}else{
    echo json_encode(array("valido" => "error", "n" => $numInput));
}

I think that there is a error in javascript code.

Could you be so kind to check?

Uncaught SyntaxError: Cannot use import statement outside a module (at app.js:1:1) [duplicate]

I have looked at the previous similar questions but none of them answered my question correctly, please I want an answer according to my context.

I am working with vue 3 as a beginner. I downloaded vue and added it to vue.js file and then created index.html and app.js files. After that I downloaded axios through npm.

My file structure looks like this:

Folder Structure

The index.html looks like this:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>YouTube Subscribers</title>
    <script src="vue.js"></script>
</head>
<body>
<h1>YouTube Subscribers</h1>

<div id="app">
    <ul>
      <li v-for="subscriber in subscribers" :key="subscriber.id">
        {{ subscriber.name }}
      </li>
    </ul>
    <p>{{ title }}</p>
</div>


<script src="app.js"></script>

The app.js looks like this:

import axios from "axios";

const app = Vue.createApp({
data() {
    return {
      subscribers: [],
      title: "Hello"
    };
  },

  created() {
    const apiKey = '';
    const channelId = '';

    axios.get(``)
      .then(response => {
        this.subscribers = response.data.items[0].statistics.subscriberCount;
      })
      .catch(error => {
        console.error(error);
      });
  }
});

app.mount("#app");  

The packge.json file looks like this:

{
  "dependencies": {
    "axios": "^1.2.2"
}
}  

But when I run the files, I see the following error in the console:

Uncaught SyntaxError: Cannot use import statement outside a module (at app.js:1:1)  

And the vue does not render the correct output.
Any assistance is appreciated in advance.

Bootstrap list-group-item texts are invisible

I am using this libraries in my html file ;

<script src="./scripts/jquery-3.5.1.slim.min.js"></script>
<script src="./scripts/bootstrap.min.js"></script>
<script src="./scripts/popper.min.js"></script>

and here is my js file tags ;

<div className="modal" id="dlgOpen" tabIndex="-1" aria-hidden="true">
        <div className="modal-dialog">
          <div className="modal-content">
            <div className="modal-header">
              <h5 className="modal-title" id="exampleModalLabel">
                Open Report
              </h5>
              <button type="button" className="close" data-dismiss="modal" aria-label="Close">
                <span aria-hidden="true">&times;</span>
              </button>
            </div>
            <div className="modal-body">
              <h2>Select Report:</h2>
              <div className="list-group">
                <button
                  type="button"
                  className="list-group-item list-group-item-action"
                  onClick={() => onSelectReport('assets/CustomersTable.rdlx-json')}
                >
                  Customers Report
                </button>
                <button
                  type="button"
                  className="list-group-item list-group-item-action"
                  onClick={() => onSelectReport('assets/TaxiDrives.rdlx-json')}
                >
                  Taxi Drives Report
                </button>
              </div>
            </div>
            <div className="modal-footer">
              <button type="button" className="btn btn-secondary" data-dismiss="modal">
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

I want to show my modal like this ;
popup

But all texts are invisible. I’m not sure what causes this. I will be glad if you help

How do I execute javascript before image load, but after content load?

The goal is to add loading=”lazy” code to every image before It’s actually loaded.

I cannot add that manually.

This is what I have so far (it adds the loading attribute, but image is still loaded even above the viewport):

function preloadFunc()
{
  var images = document.getElementsByTagName('img'); 
  console.log(images.length)
  
  for(var i = 0; i < images.length; i++) {
      console.log(images[i].src);

      var bounding = images[i].getBoundingClientRect();
      var myElementHeight = images[i].offsetHeight;
      var myElementWidth = images[i].offsetWidth;
  
      if (bounding.top >= -myElementHeight 
          && bounding.left >= -myElementWidth
          && bounding.right <= (window.innerWidth || document.documentElement.clientWidth) + myElementWidth
          && bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) + myElementHeight) {
  
          console.log('Element is in the viewport!');
      } else {
        images[i].setAttribute('loading', 'lazy');
  
          console.log('Element is NOT in the viewport!');
      }
  } 
}
document.addEventListener("DOMContentLoaded", preloadFunc);

Tree View Constructor from a list of nested objects

I have the following json file:

[
    {
      "name": "Knowledge Base",
      "children": [
        {
          "name": "Base 1"
        },
        {
          "name": "Base 2"
        }
      ]
    },
    {
      "name": "Downloads",
      "children": [
        {
          "name": "Download 1"
        },
        {
          "name": "Important Downloads",
          "children": [
            {
              "name": "I.D. 1"
            },
            {
              "name": "I.D. 2"
            }
          ]
        }
      ]
    }
  ]

I want to make a tree view list, like this:
Tree List

such that when for example,

a) when only the arrow of knowledge base is clicked, there are 2 files inside with names Base 1 and base 2 that appear

b) when the words of the folder, i.e. knowledge base is clicked, the 2 files appear in the main page, just like in file explorer

c) I also want this to work for nested folders

Basically, acting like the file explorer of a windows laptop.

Merging and Tranforming Array of object in javascripts

So i have two array of object like this…

const planned = [
    {
        '2023-01-06': 46,
        '2023-01-04': 45,
        '2023-01-05': 43,
        '2023-01-07': 53
    }
]
const actual =[
    {
        "2023-01-07": 12,
        "2023-01-06": 16,
        "2023-01-04": 14,
        "2023-01-08": 10,
        "2023-01-05": 12,
        "2023-01-03": 10
    }
]

i try to merge it into one array of object that separated the date and the value, here is my expected array:

const transformed =  [{
    date:"2023-01-03",
    actual:10,
    planned:0,
  },{
    date:"2023-01-05",
    actual:10,
    planned:5,
  },{
    date:"2023-01-06",
    actual:16,
    planned:46,
  }]

here is my try:

const transformed = planned.map((el)=>{
  let obj ={}
  actual.map((els)=>{
     if(el.key === els.key){
       obj["date"]=== el.key
       obj["actual"]=== el.keys
       obj["planned"]=== el.key
     }
  })
 return {...obj}
})

i try to figure it out, but have some issues on how to create the logic… anyone here to give me clue on it? can we use reduce prototype array or any built in?, any help on this will be verry thankful

Javascript object keys and values

createSlice is
a function that accepts an object of reducer functions where keys in the reducer object will be used to generate string action type constants like this:

const counterSlice = createSlice({
  name: 'counter',
  initialState: 0,
  reducers: {
    increment: (state) => state + 1,
  },
})

That is ok but I am confused about this.
where are the keys and values of this object?

reducers: {
    increment(state) {
        state.value++
    },
    decrement(state) {
        state.value--
    },
    incrementByAmount(state, action) {
        state.value += action.payload
    }
}

typerror Undefined reading ‘replace’ on select element [duplicate]

i have a table to input some data that contain input and select element with array as name. everytime I want to add new row to the table I made Javascript to do this. When I add new rows to the table, replace is used with regex to increase the array index.

this works on input element but does not work with select element.

Uncaught TypeError: Cannot read properties of undefined (reading 'replace')

this is the error when it come to the select element

 function addRows() {
        // Get the table element
        var table = document.getElementById("sales").getElementsByTagName("tbody")[0];

        // Call the function to add a new row and copy the previous element to the new row
        updateArrayIndex(table);
    }
    function updateArrayIndex(tbody) {
        // Get the last row of the table
        var lastRow = tbody.rows[tbody.rows.length - 1];

        // Get the cells of the last row
        var lastRowCells = lastRow.cells;

        // Insert a new row
        var row = tbody.insertRow();

        for (var i = 0; i < lastRowCells.length; i++) {
            // Insert a cell into the new row at the same index
            var cell = row.insertCell(i);

            // Get the element from the last row
            var element = lastRowCells[i].firstChild;

            // Clone the element and set its name attribute
            var newElement = element.cloneNode(true);

            /*
                This works with <input>, but failed on <select>
            */
            newElement.setAttribute("name", element.name.replace(/[d+]/, "[" + (tbody.rows.length - 1) + "]"));

            // Append the cloned element to the cell
            cell.appendChild(newElement);
        }
    }
    //delete last row
    function deleteRows(){
        var table = document.getElementById('sales').getElementsByTagName('tbody')[0];
        var rowCount = table.rows.length;
        if(rowCount > '1'){
            var row = table.deleteRow(rowCount-1);
            rowCount--;
        }
        else{
            alert('There should be atleast one row');
        }
    }
            <table class="w3-table" id="sales">
                <thead>
                    <tr>
                        <th>Date</th>
                        <th>Cash Bill No</th>
                        <th>Item Code</th>
                        <th>Quantity</th>
                        <th>Sales Person</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td id="col0"><input class="w3-input w3-border" type="text" placeholder="DD/MM/YYYY" name="data[0]['date']"/></td>
                        <td id="col1"><input class="w3-input w3-border" type="text" placeholder="CB123456" name="data[0]['cash_bill_no']"/></td>
                        <td id="col2">
                            <select class="w3-select" name="data[0][item_code]">
                                <repeat group="{{ @items}}" value="{{ @item }}">
                                    <option value="{{ @item.id }}" title="{{ @item.item_name }}">{{ @item.item_code }}</option>
                                </repeat>
                            </select>
                        </td>
                        <td id="col3"><input class="w3-input w3-border" type="number" placeholder="1" name="data[0]['quantity']"/></td>
                        <td id="col4">
                            <select class="w3-select" name="data[0][sales_person]">
                                <repeat group="{{ @text }}" value="{{ @data }}">
                                    <option value="{{ @data.id }}">{{ ucwords(@data.sales_person) }}</option>
                                </repeat>
                            </select>
                        </td>
                    </tr>
                </tbody>
                <tfoot>
                    <tr> 
                        <td><input type="button" value="Add Row" onclick="addRows()" /></td> 
                        <td><input type="button" value="Delete Row" onclick="deleteRows()" /></td> 
                        <td><input type="submit" value="Submit" /></td> 
                    </tr>  
                </tfoot>
            </table>

Hi, I’m a beginner at backend development. I need help in passing id from view to model in an MVC project

I’m trying to fetch details of 1 movie from backend API.
From backend routes I’m getting the data of 3 movies with 3 separate id’s from mongo dB, but I only need 1 of them to open to create a new page.
What do I write in model.js in this kind of situations.

in model.js –>

async loadMovieFromBackend() {
    const res = await axios.get('http://localhost:9000/movies')
    const movies = res.data

    return movies;
}

in view.js –>

const params = new URLSearchParams(window.location.search)
const movieId = params.get('id')

function initMovies() {
    controller.loadMovieFromBackend()
    .then(data => {
        console.log(data)
        render(data)
    })
    .catch(error => {
        console.log(error)
    }) 
}

in controller.js –>

loadMovieFromBackend() {
    return this.model.loadMovieFromBackend()
}