Categories
JavaScript Answers

How to get progress from XMLHttpRequest with JavaScript?

To get progress from XMLHttpRequest with JavaScript, we can set the onprogress property to a function that gets the request’s progress.

For instance, we write

const progressBar = document.getElementById("p");
const client = new XMLHttpRequest();
client.open("GET", "/foo/bar");
client.onprogress = (pe) => {
  if (pe.lengthComputable) {
    progressBar.max = pe.total;
    progressBar.value = pe.loaded;
  }
};
client.onloadend = (pe) => {
  progressBar.value = pe.loaded;
};
client.send();

to create the XMLHttpRequest client.

Then we call open to make a get request to /foo/bar.

We then set client.onprogress to a function that gets the progress from toe pe.total and pe.loaded properties.

loaded has the amount of data in bytes that arrived and total has the total number of bytes that we’re supposed to get.

Then we call client.send to make the request.

Conclusion

To get progress from XMLHttpRequest with JavaScript, we can set the onprogress property to a function that gets the request’s progress.

Categories
JavaScript Answers

How to call map() on an iterator with JavaScript?

To call map() on an iterator with JavaScript, we convert the iterator into an array.

For instance, we write

Array.from(m).map(([key, value]) => {
  //...
});

to call Array.from with iterator m to convert it to an array.

Then we get the key and value from the array parameter in the map callback and do what we want with the values.

Conclusion

To call map() on an iterator with JavaScript, we convert the iterator into an array.

Categories
JavaScript Answers

How to add an array of values to a Set with JavaScript?

To add an array of values to a Set with JavaScript, we can call the set add method.

For instance, we write

array.forEach((item) => mySet.add(item));

to call array.forEach with a callback that calls mySet.add to add item in array into the mySet set.

We use forEach to call the same callback for each item in array.

Conclusion

To add an array of values to a Set with JavaScript, we can call the set add method.

Categories
JavaScript Answers

How to preserve line breaks when getting text from a textarea with JavaScript?

To preserve line breaks when getting text from a textarea with JavaScript, we can replace whitespace characters with '<br>\n'.

For instance, we write

const post = document.createElement("p");
post.textContent = postText;
post.innerHTML = post.innerHTML.replace(/\n/g, "<br>\n");

to call replace to replace all the \n characters with '<br>\n'.

Categories
JavaScript Answers

How to stop an input field in a form from being submitted with HTML?

To stop an input field in a form from being submitted with HTML, we add an input without the name attribute.

For instance, we write

<input type="text" id="in-between" />;

to add a text input without the name attribute.

The field’s value won’t be submitted without the attribute.