Replace select options with ajax?

i have three dropdowns and 1 depends on 2 and 2 depends on 3. This is how it works. I have an issue with the 3rd one, when users changes something on 2 then 3 appends new options along with the old options. How to just replace the old ones with new ones ?

my code:

<script>
    $("#id_name").change(function () {
      var url = $("#create_application_form").attr("data-cities-url"); 
      var nameId = $(this).val();  
      var temp_intakes = null
      $.ajax({                       
        url: url,                    
        data: {
          'name': nameId 
        },
        success: function (data) { 
            temp_intakes = data.data;
            $.each(data.data, function(index, name){
                $('select[id=id_course]').append(
                $('<option></option>').val(name.id).html(name.name)
                );
              });
            }
      });
      $("#id_course").change(function () {
          
          var selected = $(this).val()
          var data = temp_intakes.filter(v => v.id === parseInt(selected ));
          $.each(data, function(index, name){
            $.each(name.intakes, function(index, test){
                $('select[id=id_intakes]').append(
                    $('<option></option>').attr("value",test).text(test) // problem on here
                )
            })
          });
      })
    });
  </script>

And my data for the above look like this

{id: 2, name: 'John', intakes: Array(3)} // the third option using this "intakes" array as options.

Please help.

Nextjs importing a commonjs module (@theatrejs/core) that depends on a ES module (lodash-es) is causing [ERR_REQUIRE_ESM]

As explained in the title, I created a fresh Nextjs project (v12), installed @theatrejs/core npm package, upon import the package and using it in the code my build started showing errors, more specifically:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /home/projects/nextjs-xtxeun/node_modules/lodash-es/get.js
require() of ES modules is not supported.
require() of /home/projects/nextjs-xtxeun/node_modules/lodash-es/get.js from /home/projects/nextjs-xtxeun/node_modules/@theatre/dataverse/dist/index.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename get.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /home/projects/nextjs-xtxeun/node_modules/lodash-es/package.json

In a nutshell, nextjs 12 app -> @theatrejs/core (commonjs) -> lodash-es (ESM).

you can see a reproduction of the error here: https://stackblitz.com/edit/nextjs-xtxeun?file=node_modules%2Flodash-es%2Fpackage.json

Can anyone point me toward a way to make it work?

Javascript Delay/Sleep function

I am writing a vanilla javascript function to add a page scrolling animation to my website. The problem is that I want the event listener to pause for the specified millisecond time to give time for the animation to complete since if I scroll normally, the animation will happen multiple times one after the other.

/*  Event handler for scroll event  */

// This is a function which allows a time to be passed in miliseconds. This function will then cause a sleep effect for the specified ms time
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

// Initial state
var iniState = 0;

// Adding scroll event
window.addEventListener('scroll', function(){
    // Detects new state and compares it with the old one
    if ((document.body.getBoundingClientRect()).top > iniState)
        console.log('up');
    else
        console.log('down');
    
    // Saves the new position for iteration.
    iniState = (document.body.getBoundingClientRect()).top;

    sleep(2000).then(() => { console.log("test"); });
});

I tried the timeout function, but this only delayed the event listener instead of pausing for the period of time. This is a link to the console in browser if that makes the problem easier to understand.

In summery, I am trying to make a event listener to listen for a scroll event, then wait 2000 milliseconds to wait for the animation to complete. After this the event listener will then start listening again for a scroll event again.

JavaScript: Chrome and Safari trigger no mouse events when already-selected of is clicked

I’m trying to respond when the user re-clicks the currently-selected <option> in a <select>. Current desktop FF (v95.0.2) fires mousedown, mouseup, and click on the <option> element itself, and everything captures down and bubbles up through the entire HTMLDocument hierarchy, including the containing window.

In the same situation, current desktop Chrome (96.0.4664.110) and Safari (14.1.2) don’t seem to fire any events at all.

<html lang="en" id="thehtml">

<head>
</head>

<body id="thebody">
  <select id="theselect">
    <option id="option1" value="1">one</option>
    <option id="option2" value="2">two</option>
  </select>
</body>

<script>
  function logEvent(ev) {
    console.log(
      ev.type +
      '   target: ' + (ev.target.localName ? `${ev.target.localName} #${ev.target.id}` : `(${ev.target.constructor.name})`) +
      '   this: ' + (this.localName ? `${this.localName} #${this.id}` : `(${this.constructor.name})`)
    );
  }

  var eventList = ['change', 'click', 'dblclick', 'input', 'mousedown', 'mouseup'];
  var elementList = ['thehtml', 'thebody', 'theselect', 'option1', 'option2'];

  for (let ev of eventList) {
    window.addEventListener(ev, logEvent, true); // capture
    window.addEventListener(ev, logEvent, false); // bubble

    document.addEventListener(ev, logEvent, true); // capture
    document.addEventListener(ev, logEvent, false); // bubble

    for (let id of elementList) {
      document.getElementById(id).addEventListener(ev, logEvent, true); // capture
      document.getElementById(id).addEventListener(ev, logEvent, false); // bubble
    }
  }
</script>

</html>

Is there any way on Chrome or Safari to detect the user clicking the mouse on the currently-selected <option>?

What is the difference between `document` and `document.body`?

What is actually the difference between document and document.body?

For example, I have the following code:

document.addEventListener('click',function(){ 
document.write('You click me!') 
})
<div>Click anywhere</div>

What will be the difference if I use document.body instead of document ?

And what is actually the difference between document and document.body?

I tried to search online, but couldn’t find any useful information.

Thanks for any responds!

How does a React application start without explicit references to its JS implementation files?

I’m learning React. In the tic-tac-toe game ( https://reactjs.org/tutorial/tutorial.html ) the index.html file had some event handlers and a div pointing at id=root. But nothing about an index.js file, which has a ReactDOM.render.

What tells the browser to run the index.js code if there is no tag loading it?

This link ( Where’s the connection between index.html and index.js in a Create-React-App application? ) says:

Our configuration specifies that Webpack uses src/index.js as an “entry point”. So that’s the first module it reads, and it follows from it to other modules to compile them into a single bundle.

When webpack compiles the assets, it produces a single (or several if you use code splitting) bundles. It makes their final paths available to all plugins. We are using one such plugin for injecting scripts into HTML.

But if this is the answer, then why should a browser know about webpack, especially as this isn’t mentioned in the minimal index.html file?

attribute height and y: Expected length, “NaN”

i have this d3 code and when i run it, it display an error which is

Error: attribute y: Expected length, “NaN”.

Error: attribute height: Expected length, “NaN”.

and it display the plot without any line
what the problem, please help i’m a begginer at d3
also i’m trying to plot multiple lines and can’t do it
i thought this code might work but there is an error

// Set our margins
var margin = {
        top: 20,
        right: 20,
        bottom: 30,
        left: 60
    },
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

// Our X scale
var x = d3.scaleBand()
    .rangeRound([0, width], .1);

// Our Y scale
var y = d3.scaleLinear()
    .rangeRound([height, 0]);

// Our color bands
var color = d3.scaleOrdinal()
    .range(["#308fef", "#5fa9f3", "#1176db"]);

// Use our X scale to set a bottom axis
var xAxis = d3.axisBottom()
    .scale(x);

// Smae for our left axis
var yAxis = d3.axisLeft()
    .scale(y)
    .tickFormat(d3.format(".2s"));

// Add our chart to the document body
var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

// Fetch data via SODA from the Chicago data site
d3.csv("mn.csv?$select=Year,Under20,f20to24,f25to29,f30to34,f35to39,f40to44,f45andover", function (error, data) {
    // Make sure our numbers are really numbers
    data.forEach(function (d) {
        d.Year = d.Year;
        d.Under20 = d.Under20;
        d.f20to24 = d.f20to24;
        d.f25to29 = d.f25to29;
        d.f30to34 = d.f30to34;
        d.f35to39 = d.f35to39;
        d.f40to44 = d.f40to44;
        d.f45andover = d.f45andover;
    });

    console.log(data);
   // console.log(data.split(",").join(""))

    // Use our values to set our color bands
    color.domain(d3.keys(data[0]).filter(function (key) {
        return key !== "Year";
    }));

    data.forEach(function (d) {
        var y0 = 0;
        d.types = color.domain().map(function (name) {
            return {
                name: name,
                y0: y0,
                y1: y0 += +d[name]
            };
        });
        d.total = d.types[d.types.length - 1].y1;
    });

    // Sort by year
    data.sort(function (a, b) {
        return a.Year - b.Year;
    });

    // Our X domain is our set of years
    x.domain(data.map(function (d) {
        return d.Year;
    }));

    // Our Y domain is from zero to our highest total
    y.domain([0, d3.max(data, function (d) {
        return d.total;
    })]);

    svg.append("g")
        .attr("class", "x axis")
        .attr("transform", "translate(0," + height + ")")
        .call(xAxis);

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis)
        .append("text")
        .attr("transform", "rotate(-90)")
        .attr("y", 6)
        .attr("dy", ".71em")
        .style("text-anchor", "end")
        .text("Ridership");

    var year = svg.selectAll(".Year")
        .data(data)
        .enter().append("g")
        .attr("class", "g")
        .attr("transform", function (d) {
            return "translate(" + x(d.Year) + ",0)";
        });

    year.selectAll("rect")
        .data(function (d) {
            return d.types;
        })
        .enter().append("rect")
        .attr("width", x.bandwidth())
        .attr("y", function (d) {
            return y(d.y1);
        })
        .attr("height", function (d) {
            return y(d.y0) - y(d.y1);
        })
        .style("fill", function (d) {
            return color(d.name);
        });

    var legend = svg.selectAll(".legend")
        .data(color.domain().slice().reverse())
        .enter().append("g")
        .attr("class", "legend")
        .attr("transform", function (d, i) {
            return "translate(0," + i * 20 + ")";
        });

    legend.append("rect")
        .attr("x", width - 18)
        .attr("width", 18)
        .attr("height", 18)
        .style("fill", color);

    legend.append("text")
        .attr("x", width - 24)
        .attr("y", 9)
        .attr("dy", ".35em")
        .style("text-anchor", "end")
        .text(function (d) {
            return d;
        });
});

Mutation Observer fails to detect original element, does detect its duplicate

I have written a Chrome extension that loads a script with run_at set to document_start.

My script uses Mutation Observer in order to invoke some code upon the addition of an element with id X to a certain webpage.

That element is created when the page first loads, and then recreated when part of the page reloads following some button click.

My mutation observer fails to detect that element in either case.

However, if I duplicate the element (Developer Tools > Elements > element > context menu > Duplicate element), then my mutation observer does detect the duplicate.

I ran a test: I changed the id of some random element to X. It was not detected. That has made me suspect the original element is first created and then has its id assigned or updated. I am not sure how I could prove of refute this theory (the process of generating the webpage code looks very complex, with layers and layers of scripts involved, and I have very little experience).

Does this theory make sense? Can I observe an id change? If the theory does not make sense or if it is impossible to observe an id change, what alternatives do I have?

Thank you!

html5 validation api gives an empty array of messages if a markup is wrong

trying to validate my html5 markup by clicking on a button and using w3c validator
the code source is from here
so my code is like this:

$('.btnw3').on('click', async function(){
    valid()
  .then(data => {
    console.clear();
    console.log(data); // Console was cleared - {messages: Array(0)}
        const error = data.messages.filter(msg => msg.type === 'error');
const warning = data.messages.filter(msg => msg.type === 'info' && msg?.subType === 'warning');

if (warning.length) {
  console.group(`%c${warning.length} validation warnings`, "background-color:#FFFBE5;padding:1px 4px");
  warning.forEach(msg => {
    console.groupCollapsed(`%c${msg.message} (line: ${msg.lastLine})`, "background-color:#FFFBE5");
    console.table(msg)
    console.groupEnd();
  })
  console.groupEnd();
}
if (error.length) {
  console.group(`%c${error.length} validation errors`, "background-color:#D93025;color:#FFF;padding:1px 4px");
  error.forEach(msg => {
    console.groupCollapsed(`%c${msg.message} (line: ${msg.lastLine})`, "color:#D93025");
    console.table(msg)
    console.groupEnd();
  })
  console.groupEnd();  // empty output
}
  })

});

so I intentionally make my markup wrong – write </divx> instead of <div> – for example

problem – I’m getting an empty array of messages on (console.log(data)) line

the same happens if I write this code as a snippet in chrome dev tools

if I copy my markup source and paste it on https://validator.w3.org/nu/#textarea – I’m getting the expecting errors

any help ?

Is it bad practice to accept setState as a function parameter in React?

Basically, before uploading an image to the firebase, I’m trying to control the input as:

export const controlThumbnail = (selectedThumbnail, setThumbnailError) => {
  if (!selectedThumbnail) {
    setThumbnailError('Please select a thumbnail!');

    return;
  }

  if (!selectedThumbnail.type.includes('image')) {
    setThumbnailError('Please select an image!');

    return;
  }

  if (selectedThumbnail.size > 1000000) {
    setThumbnailError('Image size must be less than 1MB!');

    return;
  }

  setThumbnailError(null);
};

which I call the above method from /lib/controlThumbnail.js to:

import { controlThumbnail } from '../../lib/controlThumbnail';
    
const Signup = () => {
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    password: '',
    thumbnail: null
  });
  const [thumbnailError, setThumbnailError] = useState(null);


  const userInputHandler = (e) => {
    setUserInfo((prevUserInfo) => {
      if (e.target.name === 'thumbnail') {
        const thumbnail = e.target.files[0];
        controlThumbnail(thumbnail, setThumbnailError);

        return { ...prevUserInfo, thumbnail };
      } else {
        return { ...prevUserInfo, [e.target.name]: e.target.value };
      }
    });
  };
...

so, this is now works correctly, but I wonder if this is the good way of doing it? Or should I put the control method inside the component and never give setState as parameter?

Asynchronous Loading – Three.js

How can I properly load objects asynchronously using Three.js? I’ve been having lots of trouble with this. Currently, I have the following (simplified, albeit irreproducible without downloading GTLF models) code:

const loader = new THREE.GLTFLoader();
async function init(){
    obj = await loader.loadAsync("./public/modelo/scene.gltf");
    obj2 = await loader.loadAsync("./public/earth/scene.gltf");
    console.log(obj2.scene.children[0].position);
}
init();

This throws an error in the line with console.log, claiming Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'position'). Can someone explain what is going wrong here and how to fix it? I’m not very familiar with await, but I thought its functionality was to specifically avoid things like this from happening.

My reason for using asynchronous loading is so that I can pass these 3D objects to animation functions, and without asynchronous loading, the objects get passed before they have fully loaded, which throws an error.

Google Map won’t display [closed]

I am farily new to Java Script Programming. I am learing Java Script reading from a book titled Head First HTML5 Programming. There is this step by step exercise that teaches me how to find my location and insert a google map next to my location when it is tested in any browser. However map won’t display in any browser when i test it. This book was published in 2011. Since then google has changed a few things such as requireing an API Key inorder to display the map. So I created an API key using Google Map Console.
Then Commented out the old code from the book and included the one with API_Key. Yet map won’t show in any browser.
There is also no error messages on console log view of any of the browsers. However When i type localhost/My Loction/myLoc.html I get the following message:
enter image description here
Unchechecked runtime last error:The message Port closed before a response was recieved. myLoc.html: 1
Here is the myLoc.html page:
enter image description here
This is chorm browser:
enter image description here
Neither show any error messages. Yet map wont’t display.
What I am missing here. Please help.
Thx.
Shervin

How to identify the browser and redirect the user if that’s not the correct browser?

I have a website to do for university and the teacher wants us to include code that checks what browser the user is using and if the browser isn’t Firefox, they should be redirected elsewhere.

I have this so far:


function fnBrowserDetect(){                            
  let userAgent = navigator.userAgent;          
  let browserName;                    
  if(userAgent.match(/chrome|chromium|crios/i)){              
    browserName = "chrome";            
  }else if(userAgent.match(/firefox|fxios/i)){              
    browserName = "firefox";            
  }  else if(userAgent.match(/safari/i)){
    browserName = "safari";            
  }else if(userAgent.match(/opr//i)){              
    browserName = "opera";            
  } else if(userAgent.match(/edg/i)){              
    browserName = "edge";            
  }else{              
    browserName="No browser detection";            
  }                     
document.querySelector("h1").innerText="You are using "+ browserName +" browser";            
}

function redirect(){
  if(browserName != "firefox"){
    window.location.replace("www.google.com");
  } else {
    window.location.href = "../index.php";
  }
}

Can someone help me out and let me know how can I do this correctly?

Having an issue when using load events on firefox and safari

Both firefox and safari refuses to execute load event when loaded from an external js file. It only works on google chrome.

I can’t really understand the problem.

in my html :

<script src="/assets/js/pages/myFile.js" type="text/javascript"></script>

in myFile.js :

window.addEventListener("load", function(event){
// do someting (only works in chrome browser)
})

My html page is serverd by node.js (ejs page), myFile.js is recognized by the 3 browsers (Firefox, chrome & safari), so I don’t really understand why my load event fail with ff & safari.

I’ve also tried window.unload unsuccessfully.

Any suggestion ?

JS, React: Api requests queue

I’ve implemented a queue of api requests:

class QueueStore {
  private _requests: AxiosRequestConfig[] = [];

  private _loadingState = new LoadingStateStore();

  enqueue = (req: AxiosRequestConfig) => {
    this._requests = [...this._requests, req];
  };

  addEvent = (req: AxiosRequestConfig) => {
    this.enqueue(req);
  };

  processEvents = (() => {
    let isReady = true;

    return async () => {
      if (isReady && this._requests.length > 0) {
        this._loadingState.setLoading(true);

        const response = this.dequeue();

        isReady = false;
        this.retryApiCalls(response as AxiosRequestConfig);

        isReady = true;
        this.processEvents();
      }
    };
  })();

  private retryApiCalls = async (req: AxiosRequestConfig) => {
    try {
      await HttpService.request(req);
    } catch (error) {
      ToastService.onDanger(
        ExceptionsService.errorResolver(error as ServerError)
      );
    } finally {
      this._loadingState.setLoading(false);
    }
  };

  dequeue = () => {
    return this._requests.shift();
  };

  length = () => {
    this._requests.length;
  };

  get isSyncing() {
    return this._loadingState.loading;
  }

  get requests() {
    return toJS(this._requests);
  }
}

Problem: processEvents fires API calls one by one, even if they are failing. As a result, the queue is empty.

Goal:

  • processEvents should be stopped if one of the API calls has
  • only successful requests should be dequeud. Failing requests should be left in the queue

How can I modify the existing solution?