Categories
JavaScript Answers

How to Set the Value of an Input Field with JavaScript?

Setting the value Property

One way to set the value of an input field with JavaScript is to set the value property of the input element.

For instance, we can write the following HTML:

<input id='mytext'>

Then we can set the value property of the input by writing:

document.getElementById("mytext").value = "My value";

Call the setAttribute Method

Also, we can call the setAttribute method to set the value attribute of the input element.

For instance, we can write:

document.getElementById("mytext").setAttribute('value', 'My value');

We call setAttribute with the attribute name and value to set the value attribute to 'My value' .

Setting the value Property of an Input in a Form

We can also get the input element by using the document.forms object with the name attribute value of the form and the name attribute value of the input element.

For example, we can write the following HTML:

<form name='myForm'>
  <input type='text' name='name' value=''>
</form>

Then we can use it by writing:

document.forms.myForm.name.value = "New value";

The form name value comes first.

Then the name value of the input element comes after it.

document.querySelector

We can use the document.querySelector method to select the input.

For instance, we can write the following HTML:

<input type='text' name='name' value=''>

Then we can write:

document.querySelector('input[name="name"]').value = "New value";

to get the element with querySelector .

We select the input with the name attribute by putting the name key with its value in the square brackets.

Categories
JavaScript Answers

How to Increment a Date in JavaScript?

Using Native Date Methods

One way to increment a date with JavaScript is to use native JavaScript date methods.

We can use the setDate method to increment a date with JavaScript.

For instance, we can write:

const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);

We call setDate with the current date plus 1.

To get the current date, we get the getDate method.

Then tomorrow would be tomorrow’s date.

Also, we can add milliseconds with the getTime method and add 1 day in milliseconds.

For instance, we can write:

const tomorrow = new Date();
tomorrow.setTime(tomorrow.getTime() + 1000 * 60 * 60 * 24);

We call setTime to let us set a time with a timestamp in milliseconds.

In the method call, we call getTime to return the timestamp in milliseconds.

And we add the 1 day in milliseconds to it with 1000 * 60 * 60 * 24 .

And so we get the same result as before.

Using Moment.js

Another way to increment a JavaScript date is to use the moment.js library.

To use it, we write:

const today = moment();
const tomorrow = moment(today).add(1, 'days');

We call the moment function with no arguments to create a moment object with the current date and time.

Then we call add on the current date to add a day to it.

We pass in the quantity and the unit to add.

Categories
JavaScript Answers

How to Scroll Automatically to the Bottom of the Page with JavaScript?

The window.scrollTo Method

We can use the window.scrollTo method to scroll to the bottom of the page.

For example, we can write the following HTML:

<div>

</div>

Then we call window.scrollTo by writing:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}
window.scrollTo(0, document.body.scrollHeight);

We get the div with querySelector .

Then we create some p elements with createElement and append them to the div with appendChild .

Next, we call window.scrollTo with the x and y coordinates to scroll to respectively.

document.body.scrollHeight is the height of the body element and so we scroll to the bottom.

If our scroll container isn’t the body element, then we can also get the scrollHeight from whatever element we want.

For instance, we can write:

const div = document.querySelector('div')

for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  div.appendChild(p)
}

window.scrollTo(0, div.scrollHeight);

We use the scrollHeight of the div instead of document.body .

And we get the same scrolling effect as before.

The scrollIntoView Method

We can use the scrollIntoView method to scroll the screen to the element it’s called on.

For instance, we can write:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  p.id = `el-${i}`
  div.appendChild(p)
}

document.querySelector('#el-99')
  .scrollIntoView(false);

We call scrollIntoView to scroll to the element with ID el-99 .

The argument indicates whether we want to scroll to th top of the element or not.

Since it’s false , we aren’t scrolling to the top of the element.

Also, we can change the scroll behavior by writing:

const div = document.querySelector('div')
for (let i = 0; i < 100; i++) {
  const p = document.createElement('p')
  p.textContent = 'hello'
  p.id = `el-${i}`
  div.appendChild(p)
}

document.querySelector('#el-99')
  .scrollIntoView({
    behavior: 'smooth'
  });

We pass in an object with behavior set to 'smooth' .

And so we get smooth scrolling as a result.

Categories
JavaScript Answers

How to Get the Current Date and Time in JavaScript?

Using Date Methods

We can use native JavaScript date methods to get parts of a date-time.

For instance, we can write:

const currentDate = new Date();  
const dateTime = currentDate.getDate() + "/" +  
  (currentDate.getMonth() + 1) + "/" +  
  currentDate.getFullYear() + " @ " +  
  currentDate.getHours() + ":" +  
  currentDate.getMinutes() + ":" +  
  currentDate.getSeconds();

We call the getDate method to get the day of the month.

getMonth returns the month of the year from 0 to 12.

So we’ve to add 1 to get a human-readable month number.

getFullYear returns the 4 digit year number.

getHours returns the hours of the day.

getMinutes returns the minutes of the hour.

getSeconds returns the seconds of the minute.

The toLocaleString Method

We can use the date objects’ toLocaleString method to return a human-readable date string.

For instance, we can write:

const dateTime = new Date().toLocaleString();  
console.log(dateTime)

Then we get something like:

2/24/2021, 3:04:27 PM

as a result.

The toLocaleDateString Method

Another method we can use to return a human-readable date string is the toLocaleDateString method.

For instance, we can write:

const dateTime = new Date().toLocaleDateString();  
console.log(dateTime)

to call the method.

And we get:

2/24/2021

as a result.

The toLocaleTimeString Method

Another method we can use to return a human-readable date string is the toLocaleTimeString method.

It takes a locale string and an object with options we want to set for returns the date string as the second argument.

For example, we can write:

const dateTime = new Date().toLocaleTimeString('en-US', {  
  hour12: false,  
  hour: "numeric",  
  minute: "numeric"  
});  
console.log(dateTime)

and we get something like:

15:06

from the console log.

hour12 set to false means we return a 24-hour date.

hour and minute are set th 'numeric' means we return the hour and minute as numbers.

Categories
JavaScript Answers

How to Remove Duplicates From an Array of Objects in JavaScript?

Array.prototype.filter

We can use the JavaScript array’s filter method to remove duplicate entries from an array.

To use it, we write:

const arr = [{
    place: "san francisco",
    name: "jane"
  },
  {
    place: "san francisco",
    name: "jane"
  },
  {
    place: "new york",
    name: "james"
  }
]
const result = arr.filter((thing, index, self) =>
  index === self.findIndex((t) => (
    t.place === thing.place && t.name === thing.name
  ))
)
console.log(result)

The 2nd entry in arr is a duplicate, and we want to remove it.

To do this, we call arr.filter with a callback to check that the index of the item is the same as the index returned by findIndex .

If they’re the same, then they’re the first instance of an object.

findIndex takes a callback that returns the condition with the item we’re looking for.

The callback checks if thing.place is the same as t.place .

And the same check is done with the name property.

t is the item in the arr array.

And self if the arr array.

So we go through the arr array to check if the index is the index of the first instance of the item meeting the given condition.

As a result, we get:

[
  {
    "place": "san francisco",
    "name": "jane"
  },
  {
    "place": "new york",
    "name": "james"
  }
]

returned from filter and assigned to result .

Using JSON.stringify

We can use the JSON.stringify method to convert a plain JavaScript object into a string.

This lets us check all the properties at once instead of hard coding the check as we did in the previous example.

For instance, we can write:

const arr = [{
    place: "san francisco",
    name: "jane"
  },
  {
    place: "san francisco",
    name: "jane"
  },
  {
    place: "new york",
    name: "james"
  }
]
const result = arr.filter((thing, index, self) =>
  index === self.findIndex((t) => (
    JSON.stringify(t) === JSON.stringify(thing)
  ))
)
console.log(result)

to remove the duplicate item by using JSON.stringify to convert t and thing to strings.

Then we can check the JSON strings directive with === .

And we get the same result as before.

Using Sets and JSON.stringify

JavaScript comes with the Set constructor to let us create sets, which are data structures that don’t have duplicate items.

We can use it with JSON.stringify to create a set of stringified JavaScript objects.

Then we can convert the sets back to an array with the spread operator.

Then we can convert the array of strings back to an array of objects with JSON.parse .

So we can write:

const arr = [{
    place: "san francisco",
    name: "jane"
  },
  {
    place: "san francisco",
    name: "jane"
  },
  {
    place: "new york",
    name: "james"
  }
]
const result = [...new Set(arr.map(a => JSON.stringify(a)))].map(a => JSON.parse(a))
console.log(result)

to do this.

We map the arr entries to strings with:

arr.map(a => JSON.stringify(a)

And we pass that into the Set constructor.

This would remove the duplicates.

And then we spread it back into an array.

And finally, we call map to map the stringified object array back to an object array with JSON.parse .

So we get the same result as before.