Categories
JavaScript Answers

How to set focus on an element in an HTML form using JavaScript?

To set focus on an element in an HTML form using JavaScript, we call the input’s focus method.

For instance, we write

<input type="text" id="myText" />

to add an input.

Then we write

document.getElementById("myText").focus();

to select the input with getElementById.

Then we call focus to set focus on it.

Categories
JavaScript Answers

How to use moment.js to convert date to string in mm/dd/yyyy format with JavaScript?

To use moment.js to convert date to string in mm/dd/yyyy format with JavaScript, we use the format method.

For instance, we write

const startDate = moment().format("MM/DD/YYYY HH:mm:ss");

to create a moment object with moment with the current datetime.

Then we call format with a format string to return a string in mm/dd/yyyy format with the time in hours:minutes:seconds format.

Categories
JavaScript Answers

How to read a local csv file in JavaScript?

To read in a local csv file in JavaScript, we can use the FileReader constructor.

For instance, we write:

<input type="file">

to add a file input.

Then we write:

const input = document.querySelector('input')
const fileReader = new FileReader()
fileReader.onload = (e) => {
  console.log(e.target.result)
}

input.onchange = (e) => {
  const [file] = e.target.files
  fileReader.readAsBinaryString(file)
}

to select the input with querySelector.

Next, we create a FileReader instance.

Then we set its onload property to a function that logs the file content.

Next, we set input.onchange to a function that gets the selected file from e.target.files.

And then we call fileReader.readAsBinaryString to read the file.

Categories
JavaScript Answers

How to create a unique array of objects with JavaScript?

To create a unique array of objects with JavaScript, we use the array filter method.

For instance, we write

const getUniqueBy = (arr, prop) => {
  const set = new Set();
  return arr.filter((o) => !set.has(o[prop]) && set.add(o[prop]));
};

to define the getUniqueBy function.

In it, we create a set with the Set constructor.

And then we return the array returned by filter that adds the o[prop] to the set if it doesn’t exist and if the property value doesn’t exist.

Categories
JavaScript Answers

How to create a new file with JavaScript?

To create a new file with JavaScript, we use the File constructor.

For instance, we write

const f = new File([""], "filename");

to call File with an array with the file contents and a string with the filename respectively.

We can pass in a third argument with some options.

For example, we write

const f = new File([""], "filename.txt", {
  type: "text/plain",
  lastModified: date,
});

to call File with an object with the MIME type and the lastModified date of the file as the 3rd argument.