Categories
JavaScript Answers

How to Define a JavaScript Array with Conditional Elements?

We can use the spread operator to conditionally spread arrays into another array.

For instance, we can write:

const items = [
  'foo',
  ...true ? ['bar'] : [],
  ...false ? ['falsy'] : [],
]

console.log(items)

Then items is [“foo”, “bar”] since we have a ternary express that has false as the value of the conditional part of the ternary expression.

If it’s true , then the left array is spread into items .

Otherwise, an empty array is spread into items .

Call Array.prototype.push Conditionally

Another way to conditionally add items conditionally to a JavaScript array is to use the push method.

For instance, we can write:

const items = [
  'foo',
]

if (true) {
  items.push("bar");
}

if (false) {
  items.push("false");
}

console.log(items)

Then 'bar' is appended to items but 'false' isn’t .

This is because the first conditionally has true as the conditional and the 2nd one has false as the condition.

Therefore items is [“foo”, “bar”] again.

Categories
JavaScript Answers

How to Run JavaScript Code When an Element Loses Focus?

Listen to the blur Event

We can listen to the blur event to run code when an element loses focus.

For instance, if we have the following input element:

<input type="text" name="name" />

Then we can watch when the blur event is triggered on the input by writing:

const input = document.querySelector('input')  
input.addEventListener('blur', () => {  
  console.log('focus lost')  
})

We get the input element with document.querySelector .

Then we call addEventListener on it with 'blur' as the first argument.

The 2nd argument is a callback that runs when the blur event is triggered.

When we move our cursor away from the input element, we’ll see the 'focus lost' string logged.

Categories
JavaScript Answers

How to Get Tomorrow, Today, and Yesterday’s Date with Moment.js?

We can get today’s date with the moment function.

And then we can format it into a human-readable date string with the format method.

For instance, we can write:

const today = moment();
console.log(today.format('YYYY-MM-DD'))

to create the today variable that’s set to a moment object with today’s date.

And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.

Get Tomorrow’s Date

We can get tomorrow’s date with the moment function and the add method.

And then we can format it into a human-readable date string with the format method.

For instance, we can write:

const tomorrow = moment().add(1, 'days');
console.log(tomorrow.format('YYYY-MM-DD'))

to create the tomorrow variable that’s set to a moment object with today’s date.

Then we call add with 1 and 'days' to add one day to today.

And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.

Get Yesterday’s Date

We can get tomorrow’s date with the moment function and the add method.

And then we can format it into a human-readable date string with the format method.

For instance, we can write:

const yesterday = moment().add(-1, 'days');
console.log(yesterday.format('YYYY-MM-DD'))

to create the tomorrow variable that’s set to a moment object with today’s date.

Then we call add with -1 and 'days' to subtract one day to today.

And then we call format with 'YYYY-MM-DD' to format the date to YYYY-MM-DD format.

Categories
JavaScript Answers

How to Put a Clear Button Inside an HTML Text Input Box?

The easiest way to add an input box with a clear button is to add an input element with the type attribute set to search .

For instance, we can write:

<input type="search" />

Then when we type into the input box, we see the clear button displayed.

And we can click on it to clear its value.

Use CSS Styles

We can also add an input box with CSS.

For instance, we can write:

<form>
  <input type="text" placeholder=" " />
  <button type="reset">&times;</button>
</form>

Then we can style the input to add a clear button with:

form {
  position: relative;
  width: 200px;
}
`
form input {
  width: 100%;
  padding-right: 20px;
  box-sizing: border-box;
}
`
form input:placeholder-shown+button {
  opacity: 0;
  pointer-events: none;
}
`
form button {
  position: absolute;
  border: none;
  display: block;
  width: 15px;
  height: 15px;
  line-height: 16px;
  font-size: 12px;
  border-radius: 50%;
  top: 0;
  bottom: 0;
  right: 5px;
  margin: auto;
  background: #ddd;
  padding: 0;
  outline: none;
  cursor: pointer;
  transition: .1s;
}

We select the button in the form with CSS with the form button selector.

And we set its position to absolute to make the button stay in place.

Then we set width and height to fit inside the input box.

We also set the background to add a background.

To add the ‘x’ inside the button, we use the &times HTML entity.

The button should have reset as the value of the type attributes to clear the button’s value when we click it.

Categories
JavaScript Answers

How to Listen to the Form Submit Event in JavaScript?

We can listen to the submit event of the form to watch for presses of the form submit button.

For instance, if we have the following form:

<form>
  <input type="text" name="name">
  <input type="submit" name="submit">
</form>

Then we can write:

const form = document.querySelector("form")
form.addEventListener("submit", (e) => {
  e.preventDefault();
  const formData = new FormData(form)
  console.log(formData.entries())
});

to listen to the form submit event and get the data from the form with the FormData constructor.

We get the form with document.querySelector .

Then we call addEventListener on it with 'submit' as the first argument.

The 2nd argument of addEventListener is a callback that processes the form when it’s submitted.

In the callback, we call e.preventDefault() to stop the server-side form submission behavior.

Then we use the FormData constructor with the form element we selected to get its value.

And then we use the entries method to get the entered value.

It returns the iterator with the key-value pairs of the form values.

The key of each entry is the name attribute value of the field.

And the value is the value.

So if we entered ‘aaa’ into the text field, we get:

[
  [
    "name",
    "aaa"
  ]
]

as the result returned by entries .