Highlight a word in webpage using XPath

I want to look for a word TEST using XPath and highlight it. I have managed to search for the word TEST using var xpathResult = document.evaluate("(//text()[contains(., 'TEST')])[1]", document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null); var node=xpathResult.singleNodeValue;

How do I highlight this result TEST in webpage itself? Thank you

POST Request with fetch API not working in ReactJS

I have a ReactJS task that requires me to make a POST request to the server. Now, I want to send a POST request when a user clicks a submit button. But I keep getting these 2 errors:
App.js:19 POST http://localhost:3001/ net::ERR_CONNECTION_RESET
App.js:19 Uncaught (in promise) TypeError: Failed to fetch at handleSubmit (App.js:19:1)

Link to React code:

import './App.css';
//Frontend

function App() {
  const [inputs, setInputs] = useState({});
  const [backendData, setBackendData] = useState();

  const handleChange = (e) =>{
    const name = e.target.name;
    const value = e.target.value;
    setInputs((state)=> ({...state, [name]: value}))
  }

  const handleSubmit = (e) =>{
    e.preventDefault();
    /*when submit is clicked, we are goint to send a POST request so that data of the inputs is created*/
    console.log(inputs)
    fetch('http://localhost:3001/', {
      method: "POST",
      headers: {"Content-Type": "application/json"},
      body: JSON.stringify(inputs)
    })
  }

  return (
    <div className="App">
      <form onSubmit={handleSubmit}>
        <input type="text" name="projectTitle" onChange={handleChange} className="project-title" value={inputs.projectTitle || " "}/>
        <input type="text" name="id" className="id"  onChange={handleChange} value={inputs.id || " "}/>
        <input type="submit" value="Submit"/>
      </form>
     
    </div>
  );
}

export default App;

Link to Server(express code)

/*Now, here we create a Restful api to allow a user to store a list[array] of web project items.*/

const express = require('express');
const app = express();
const fs = require('fs');
const cors = require("cors");
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json())
app.use(cors());


var obj = { projects: []};
app.post('/', (req, res, next)=>{
    let identifier = req.query.identify; //id of project

    fs.readFile('webProjects.json', (err, data)=>{
        if(err) throw err;
            obj = JSON.parse(data);
            obj.projects.push({id:identifier, title: req.query.project, description: req.query.description});
            let json = JSON.stringify(obj);
            fs.writeFile('webProjects.json', json, (err)=>{
                if(err) throw err
                console.log("updatedd", req.body.inputs)
            })
    })
})

/*when user sends delete request, delete specific data.*/
app.delete("/", (req, res, next)=>{

    fs.readFile('webProjects.json', (err, data)=>{
        console.log(data)
        obj = JSON.parse(data);
    
        // assign the filtered array back to the original array
        obj.projects = obj.projects.filter((item)=>{
            let url = req.query.identify; 
            return item.id !== url;
        })
    
        console.log(obj)
        let json = JSON.stringify(obj);
        fs.writeFile('webProjects.json', json, (err)=>{
            if(err) throw err;
            console.log(obj)
        })
    })
})

/*when user navigates to another page, we display the data of the resource*/
app.get('/api', (req, res, next)=>{
    fs.readFile('webProjects.json', (err, data)=>{
     if (err) throw err
     res.json(JSON.parse(data));
     console.log("done")
    })
})


/*we want to catch all errors, with the requests made to the server.
used the wildcard(*) to make sure that we catch all requests made to the server.
*/
app.get('*', (req, res, next)=>{
    let err = new Error('There was an error in accessing the page you wanted');
    err.statusCode = 404;
    next(err);
})

app.use((err, req, res, next)=>{
    console.log(err.message)
    if(!err.statusCode) err.statusCode = 500;
    res.status(err.statusCode).send(err.message);
})

let PORT = process.env.PORT || 3001;

app.listen(PORT, ()=>{
    console.log("server has listened")
})

This is an example from my coding bootcamp, to create a function to print the day according to the input (1 to 7). But my code is disapproved [duplicate]

function returnDay(day) {
while (day > 0 && day <= 7) {
    switch(day) {
        case 1 :
            console.log("Monday");
            break;
        case 2 :
            console.log("Tuesday");
            break;
        case 3 :
            console.log("Wednesday");
            break;
        case 4 :
            console.log("Thursday");
            break;
        case 5 :
            console.log("Friday");
            break;
        case 6 :
            console.log("Saturday");
            break;
        case 7 :
            console.log("Sunday");
            break;
    }
}
return 0;

I used switch statement and while loop. But it says my code took long to execute.

My code was disapproved. What happened here?

Javascript to populate a form field with data extracted from URL Parameters

I am trying to use javascript to extract data from the URL parameter ‘utm_source’ and add it to a field on a form so that it is stored in my contact database for tracking purposes.

I had previously accomplished this on another site, but when trying to reuse the code it is not working for me.

The page is here (with the included URL parameter to be extracted):

https://members.travisraab.com/country-guitar-clinic-optin-1-1?utm_source=youtube&utm_medium=description

The desired result if for the ‘traffic_source’ field on my form to be populated with the value from the ‘utm_source’ URL parameter, in this case ‘youtube’.

Here is the code I am using:

<script type="text/javascript">
function addSource() {
  var fieldToChange = document.getElementsByName("form_submission[custom_4]");
  var source = trafficSource();
  fieldToChange.value = source;
  }

  var trafficSource = function() {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i=0;i<vars.length;i++) {
      var pair = vars[i].split("=");
      if(pair[0] == "utm_source"){
          return pair[1];
      } else if (pair[0] == "gclid") {
          return 'google';
      }
    }
    return 'unknown';
  }


document.onload = addSource();
</script>

using JS to create an array, to work as a Model in MVC 6

I am making a site for a friend. My goal is to add a section like a tag text area when you ask a question. I got something close enough created. The problem is now I want the tags that I created to become part of the Model’s list of ingredients. I want to be added individually but inside the MVC Model. I did something like this but it still asks for ingredients so I don’t know how to set them up so they can reach the controller. It says the ingredients are required.

javascript section

$('#ingredientInput').on('keyup',  (e) => {
        if (e.which == 188 || e.which == 13) {

        let currentValue = $('#ingredientInput').val();
        const current = document.querySelector("#ingredientInput");

        if (currentValue.charCodeAt("/")) {
            currentValue = currentValue.replace(/n/g, '');
        }
        currentValue = currentValue.replace(/,/g, '');
        
        var list = document.getElementById('ingredientList');
        var li = document.createElement("li");
        var input = document.createElement("input");
        input.type = "text";
        input.hidden = true;
        input.setAttribute("asp-for", "Ingredients")
        input.setAttribute("value", currentValue);

        li.classList.add("ingredientInputItem", "badge", "rounded-pill", "ingredientPills");
        
        li.appendChild(document.createTextNode(currentValue));
        li.appendChild(input)
        list.prepend(li);

        //for text area you have to clear like this 
        current.value = "";
    }
})

HTML section

@using MellysUndergroundCuisine.Models.ViewModels
@model DishVM
<section class="vh-100">
    <div class="mask d-flex align-items-center h-100 gradient-custom-3">
        <div class="container h-100">
            <div class="row d-flex justify-content-center align-items-center h-100">
                <div class="col-12 col-md-9 col-lg-7 col-xl-6">
                    <div class="card" style="border-radius: 15px;">
                        <div class="card-body p-5">
                            <h2 class="text-uppercase text-center mb-5">Add A Dish</h2>
                            <form asp-action="AddDish" asp-controller="Admin" enctype="multipart/form-data" method="post">
                                <div class="val" asp-validation-summary="All"></div>
                                <div class="form-outline mb-4">
                                    <input asp-for="Name" class="form-control form-control-lg" />
                                    <label class="form-label" asp-for="Name">Dish Name</label>
                                </div>
                                <div class="form-outline mb-4">
                                    <input asp-for="Information" class="form-control form-control-lg" />
                                    <label asp-for="Information" class="form-label">DishInformation</label>
                                </div>

                                <div class="form-outline  mb-4">
                                    <input asp-for="Price" class="form-control form-control-lg" />
                                    <label asp-for="Price" class="form-label">Price</label>
                                </div>

                                <div class="form-outline  mb-4">
                                    <input asp-for="Quantity"  class="form-control form-control-lg" />
                                    <label asp-for="Quantity" class="form-label">Quantity</label>
                                </div>
                                <div class="form-outline mb-4">
                                    <ul id="ingredientList" >
                                        <li class="ingredientInputItem">
                                            <br />
                                            <label for="Ingredients"> Add a comma to seperate the ingredients</label>
                                            <textarea id="ingredientInput" spellcheck="false" autocomplete="false" autocapitalize="off" autocorrect="off"
                                                      tabindex="1" dir="ltr" aria-label="To" role="combobox" aria-autocomplete="list" ></textarea>
                                        </li>
                                    </ul>
                                </div>


                       <div class="form-outline  mb-4">
                                    <input asp-for="FoodImage" class="form-control form-control-lg" />
                                    <label asp-for="FoodImage" class="form-label">Browse</label>
                                </div>
                                <div class="d-flex justify-content-center">
                                    <button type="submit" id="DishButton"
                                            class="btn btn-success btn-block btn-lg gradient-custom-4 text-body">
                                        Add Dish
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</section>

@section Styles {
    <link href="/css/Register.css" rel="stylesheet" type="text/css" />
}

    @section Scripts {
    @{
        await Html.RenderPartialAsync("_ValidationScriptsPartial");
        <script src="~/js/adminpanel.js"></script>
    }
 }

Detailed example on how to import of a static KMZ file into Openlayers, jszip at user end

I want to import a KMZ file into Openlayers. A KMZ file is a Zipped KML file, so it needs to be extracted first on the user end via JSZIP. There are only a couple examples out there but it isn’t exactly what I want, and I’m missing the final piece of the puzzle.

This is the drag and drop example… https://openlayers.org/en/latest/examples/drag-and-drop-custom-kmz.html
It involves dragging a KMZ file to the map, which extracts and then displaying the features.

How can I do this without dragging, but instead just referring to a static example.KMZ file location.

Here is the basic version of what I have… but I need it to work with a KMZ, not KML file.

<!-- HTML -->

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Import KMZ</title>
    <!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
    <link rel="stylesheet" href="library/openlayers/v6.4.3/ol.css">
    <style>
      .map {
        width: 100%;
        height:400px;
      }
   </style>
  </head>
  <body>

    <div id="map" class="map" > </div>
    
<script src="https://unpkg.com/[email protected]/dist/elm-pep.js"></script>
    <!-- The lines below are only needed for old environments like Internet Explorer and Android 4.x -->
<script src="https://cdn.polyfill.io/v3/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,TextDecoder"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/core-js/3.18.3/minified.js"></script>
<script src='library/openlayers/v6.4.3/ol.js'></script>
<script src="https://code.jquery.com/jquery-3.6.0.js"  integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="  crossorigin="anonymous"></script>   
  
<script  src="js/basic.js"></script>


  </body>
</html>



//JavaScript


//Map Layer
var rasterLayer = new ol.layer.Tile({
  source: new ol.source.OSM()
});

//KML layer Source
const vectorSource=new ol.source.Vector({
    url: 'doc.kml',
    format: new ol.format.KML({ extractStyles: false })
    
  });

//KML Layer
const vector = new ol.layer.Vector({
  source : vectorSource
});

//New Map
const map = new ol.Map({
  layers: [rasterLayer, vector],
  target: document.getElementById('map'),
  interactions : ol.interaction.defaults({doubleClickZoom :false}),
  view: new ol.View({
    center: ol.proj.fromLonLat([-97, 55]),
    zoom: 4,
    maxZoom: 18,
    enableRotation: false
  }),
});

If you can help me see what I am missing, Please help.
Thank you

Why my Vue.js app isn’t auto updating when I push and/or splice an object from the array?

I’m using Quasar and Vue.js to create a form where I can add objects into an array so they can be inserted into the DB all at the same time, but whenever I add or delete one object from this array it just updates after I focus on any other input in the form, it is adding and deleting the objects from the array as it should, but it isn’t showing on the screen unless I focus on any other input in the form, follow the code:

<template>
  <form>
    <q-input
      v-model = "eventTitle"
      label = "Event title"
    />
    <div
      v-for = "(task, index) in tasks" :key = "index"
    >
      <q-btn
        label = "Remove Task"
        @click = "removeTask(index)"
      />
      <q-input
        v-model = "task.title"
        label = "Title"
      />
      <q-input
        v-model = "task.date"
        label = "Date"
      />
      <q-input
        v-model = "task.desc"
        label = "Description"
      />
    </div>

    <q-btn
      label = "Add Task"
      @click = "addTask"
    />
  </form>
</template>

<script>
  export default {
    setup () {

      const singleTask = {
       title: '',
       date: '',
       desc: ''
      }

      var tasks = []

      return {
        tasks,
        singleTask
      }
    },

    methods: {
      addTask() {
        this.tasks.push(this.singleTask)
      },

      removeTask(index) {
        this.tasks.splice(index, 1)
      }
    }
  }
</script>

And whenever I edit a field on one object the others are also modified (which is another problem).
If someone has any suggestions on this one I’ll be grateful because I’ve never seen something like this.

Thanks for the suggestions and answers beforehand.

Npm start cannot find module ‘./utils/verifyPackageTree’

I created a react app using
npx create-react-app skling9

I could start it yesterday using npm start
but now I just cannot start it

I am getting this error…

node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module './utils/verifyPackageTree'
Require stack:
- /home/skul/Documents/web/node/skling9/node_modules/react-scripts/scripts/start.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/skul/Documents/web/node/skling9/node_modules/react-scripts/scripts/start.js:26:27)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    '/home/skul/Documents/web/node/skling9/node_modules/react-scripts/scripts/start.js'
  ]

This is my package.json file

{
  "name": "skling9",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.3.0",
    "@testing-library/user-event": "^13.5.0",
    "react": "^18.1.0",
    "react-dom": "^18.1.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "node node_modules/react-scripts/scripts/start.js",
    "build": "node node_modules/react-scripts/scripts/build.js",
    "test": "node node_modules/react-scripts/scripts/test.js",
    "eject": "node node_modules/react-scripts/scripts/eject.js"
  },

  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Some of the other questions on stack overflow just suggested many things but none of them helped and neither is google search…

I am new to node and cannot understand anything… please help

Access SVG data from URL returned in fetch API call

I’m using an API call to return an SVG but the request is returned as url of the SVG, I need to edit the SVG colors but cannot access the SVG inline data. This url will be different with each request

This is an example URL of the SVG returned from fetch.

url: "https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=test&format=svg"

Is there any way to directly access the data within the SVG e.g paths ?
Or can i create a copy of the SVG and convert it into an inline SVG?

I have seen some suggestions that are in jquery but would like to use vanilla javascript or react library.

How to import javascript function from file without running entire js file?

I have page1.html which uses blah.js. One of the things blah.js does is run a function1() when the page is loaded. I would like to use function2() from blah.js in page2.html without blah.js running function1(). I thought I could add

export {function2}

to blah.js and then just import function2() by adding

<script type = "module">
import { function2 } from './blah.js'
</script>

to page2.html. But this seems to have the same functionality as if I just imported the file as normal:

  <script defer src="blah.js"></script>

i.e. function1() runs in page2 in both cases. How can I get access to function2() without running the other parts of blah.js?

Parcel won’t load images in my javascript file

I am using the parcel bundler for my website.

I’ve been trying to use gsap to change the src attribute of an <img> tag. This change happens when the user clicks on a <button onclick="changeImage()">. However, the localhost:1234 server doesn’t show this change at all. Can parcel change images of my website after build time?

my html file:

<img class="mercury_image" src="images/mercury.png"/>
<button onclick="changeImage()"> Click here </button>

my javascript file

function changeImage() {
    gsap.timeline()
    .set(".mercury_image", {
       attr: {src: "images/differentImage.png"}
  })
}

API that provide hotel prices from various website?

Iam currently working on website that provide list of hotel that available with the price from various website
but i can’t find any API references that provide the data

i want to show price just like in a google maps like this

enter image description here

or like this in a website called visitacity.com

enter image description here

Any references of an API that provide hotel prices from various website?

TypeError: Cannot read properties of undefined (reading ‘destroy’) when using Svelte and egjs-grid

I’m attempting to run a toy example of egjs-grid for Svelte, and I get the titular error when I attempt to run it. My code is very simple:

<script>
    import { JustifiedGrid } from "@egjs/svelte-grid";
  
    const gap = 5;
    const defaultDirection = "end";
    const rowRange = 0;
    const columnRange = [1,8];
    const sizeRange = [200,1000];
    const isCroppedSize = false;
    const displayedRow = -1;
  </script>
  
  <JustifiedGrid
    class="container"
    {defaultDirection}
    {gap}
    {rowRange}
    {columnRange}
    {sizeRange}
    {isCroppedSize}
    {displayedRow}
  >
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
    <div class="item">10</div>
  </JustifiedGrid>