Categories
JavaScript Answers

How to Change an HTML Selected Option Using JavaScript?

Sometimes, we may want to change the selected drop-down option with JavaScript.

In this article, we’ll look at how to change an HTML selected option with JavaScript.

Set the value Property of the Select Drop Down

We can change the HTML select element’s selected option with JavaScript by setting the value property of the select element object.

For instance, we can write the following HTML:

<select>
  <option value="apple">Apple</option>
  <option value="orange">Orange</option>
  <option value="grape">Grape</option>
</select>

<button id='apple'>
  apple
</button>
<button id='orange'>
  orange
</button>

We have a select drop down with some options and 2 buttons that sets the selected options when clicked.

Then we can add the following JavaScript code to set the options with the buttons:

const appleBtn = document.getElementById('apple')
const orangeBtn = document.getElementById('orange')
const select = document.querySelector('select')

appleBtn.addEventListener('click', () => {
  select.value = 'apple'
})

orangeBtn.addEventListener('click', () => {
  select.value = 'orange'
})

We get the 2 buttons with getElementById .

And we get the select drop down with querySelector .

Then we call addEventListener with 'click' to add click listeners on the buttons.

And we set select.value of each to the value that we want to select.

value should be set to the value of the value attribute for this to work.

Now when we click the buttons, we should see the selected value in the drop-down change to one we set in the click listener.

Conclusion

We can set the select option with the HTML select dropdown with JavaScript by setting the value property.

Categories
JavaScript Answers

How to Convert Any String into Camel Case with JavaScript?

Sometimes, we want to convert a JavaScript string into camel case with JavaScript.

In this article, we’ll look at how to convert any string into camel case with JavaScript.

Use the String.prototype.replace method

We can use the string instances’ replace method to convert each word in the string to convert the first word to lower case, the rest of the words to upper case, then remove the whitespaces.

To do this, we write:

const camelize = (str) => {
  return str.replace(/(?:^\w|\[A-Z\]|\b\w)/g, (word, index) => {
    return index === 0 ? word.toLowerCase() : word.toUpperCase();
  }).replace(/\s+/g, '');
}
`
console.log(camelize("EquipmentClass name"));

We call replace with a regex that looks for word boundaries with \b and \w .

\b matches a backspace.

\w matches any alphanumeric character from the Latin alphabet.

We check the index to determine if it’s the first word or not.

If it’s 0, then we return word.toLowerCase() to convert it first character of the word to lower case since it’s the first word.

Otherwise, we return word.toUpperCase to convert the first character of the word to upper case.

Then we call replace again with /\s+/g and an empty string to replace the spaces with empty strings.

Therefore, camelize returns 'equipmentClassName’ as a result.

Lodash camelCase Method

We can use the Lodash camelCase method to convert any string to camel case the same way the camelize function does.

For instance, we can write:

console.log(_.camelCase("EquipmentClass name"));

Then we get the same result as the previous example.

Conclusion

We can convert any JavaScript string to camel case with the String.prototype.replace method or the Lodash camelCase method.

Categories
JavaScript Answers

How to Count Certain Elements in a JavaScript Array?

Sometimes, we may want to count certain elements in a JavaScript array.

In this article, we’ll look at how to count certain elements in a JavaScript array.

Using the Array.prototype.filter Method

The Array.prototype.filter method lets us return an array with the items that meets the condition we’re looking for.

Therefore, we can use the length property of the array returned by filter to count the elements that meet the given condition.

For instance, we can write:

const arr = [1, 2, 3, 5, 2, 8, 9, 2]
const numEvens = arr.filter(x => x % 2 === 0).length
console.log(numEvens)

We have the arr with some numbers.

To count all the even numbers in the array, we can use the filter method with the callback that returns x % 2 === 0 to return an array that meets this condition, which are even numbers.

Then we can use the length property to get the number of entries in the array.

So we have numEvens equal 4 as seen from the console log.

Using the Array.prototype.reduce Method

Also, we can use the Array.prototype.reduce method to count the number of items that meet the given condition.

To count the number of even numbers with reduce , we write:

const arr = [1, 2, 3, 5, 2, 8, 9, 2]
const numEvens = arr.reduce((total, x) => (x % 2 === 0 ? total + 1 : total), 0)
console.log(numEvens)

We call reduce with a callback that takes the total and x parameters.

total is the total returned so far, and x is the value being iterated through to compute the total .

We return total + 1 if x % 2 is 0 and total otherwise.

0 in the 2nd argument is the initial value of total .

Therefore, we should get the same value for numEvens as before.

Conclusion

We can count certain elements in an array with the array instances filter or reduce methods.

Categories
JavaScript Answers

How to Set Time Delay in JavaScript?

Sometimes, we want to run some JavaScript code after a delay.

In this article, we’ll look at how to set a time delay in JavaScript.

Use the setTimeout Method

We can use the setTimeout method to run code after a time delay.

For instance, we can write:

setTimeout(() => {
  console.log('hello world')
}, 1000);

We pass in a callback to run after the delay as the first argument.

And we pass in the delay to wait until the callback is run in milliseconds as the 2nd argument.

Now we should see 'hello world' logged after 1 second.

Use the setTimeout Function in a Promise

We can use the setTimeout function in a promise so that we can easily use setTimeout multiple times sequentially.

To do this, we write:

const sleep = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}
`
(async () => {
  console.log("Hello");
  await sleep(2000)
  console.log("world");
})()

We create the sleep function which returns promise created with the Promise constructor.

We pass in a callback that takes the resolve function and calls setTimeout with the resolve function so that the promise is resolved.

ms is the delay to wait in milliseconds until resolve is run.

Then we can use it in the async function below that.

So we should see 'Hello' logged first.

Then after 2 seconds, 'world' is logged.

Conclusion

We can run code with a time delay with the setTimeout method.

To use it sequentially, we can wrap it in a promise.

Categories
JavaScript Answers

How to Convert a Date String to Timestamp in JavaScript?

Sometimes, we may want to convert a date to UNIX timestamp in JavaScript.

In this article, we’ll look at ways to convert a date to a timestamp in JavaScript.

Use the Date.parse Method

We can use the Date.parse method to convert the date string into a timestamp.

For instance, we can write:

const toTimestamp = (strDate) => {  
  const dt = Date.parse(strDate);  
  return dt / 1000;  
}  
console.log(toTimestamp('02/13/2020 23:31:30'));

We create the toTimestamp method that calls the Date.parse method with a date string to parse it into a timestamp.

The unit is in milliseconds, so we’ve to divide it by 1000 to convert it to seconds.

Use the getTime Method

We can use the getTime method of a Date instance to convert the date string into a timestamp.

To use it, we write:

const toTimestamp = (strDate) => {  
  const dt = new Date(strDate).getTime();  
  return dt / 1000;  
}  
console.log(toTimestamp('02/13/2020 23:31:30'));

We create the Date instance with the Date constructor.

Then we call getTime to return the timestamp in milliseconds.

So we’ve to divide that by 1000 to get the number of seconds.

Moment.js’s unix Method

We can use the moment.js’s unix method to return a timestamp.

For instance, we can write:

const toTimestamp = (strDate) => {  
  const dt = moment(strDate).unix();  
  return dt;  
}  
console.log(toTimestamp('02/13/2020 23:31:30'));

We pass strDate into the moment function to return a moment object with the time.

Then we can call the unix method on that to return the timestamp.

The unix method returns the timestamp in seconds so we don’t have to divide the returned result by 1000.

Conclusion

We can use plain JavaScript or momnent.js to convert a date string into a UNIX timestamp.