Categories
JavaScript Answers

How to Retrieve the Text of the Selected option Element in a select Element with JavaScript?

Sometimes, we want to retrieve the text of the selected option element in a select element with JavaScript.

In this article, we’ll look at how to retrieve the text of the selected option element in a select element with JavaScript.

Use the selectedIndex Property

We can get the index of the selected item with the selectedIndex property.

Then we can use the text property to get the text of the selected item.

For instance, if we have the following HTML:

<select>
  <option value="1">apple</option>
  <option value="2" selected>orange</option>
</select>

Then we can write the following JavaScript code to get the selected item from the select element:

const getSelectedText = (el) => {
  if (el.selectedIndex === -1) {
    return null;
  }
  return el.options[el.selectedIndex].text;
}

const select = document.querySelector('select')
const text = getSelectedText(select);
console.log(text)

We create the getSelectedText function that takes an element as the parameter.

Then we check if selectedIndex is -1.

If it’s -1, then nothing is selected and we return null .

Otherwise, we get the options with el.options .

And then we get the selected option by passing in the el.selectedIndex into the square brackets.

Finally, we get the text property to get the text of the selected option element.

Therefore, the console log should log 'orange' .

Conclusion

We can retrieve the text of a selected option element with the selectedIndex and text properties.

Categories
JavaScript Answers

How to Convert a Unix Timestamp to a Calendar Date with Moment.js and JavaScript?

Sometimes, we want to convert a Unix timestamp to a calendar date with Moment.js and JavaScript.

In this article, we’ll look at how to convert a Unix timestamp to a calendar dare with moment.js and JavaScript.

Use the unix and format Methods

We can use the unix method to create a moment object from a timestamp.

Then we can use the format method to format the date into a calendar date.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment.unix(dt / 1000).format("MM/DD/YYYY");  
console.log(dateString)

We create the dt date object with the Date constructor.

Then we convert it to a timestamp in milliseconds with the unary + operator.

Next, we call moment.unix with a timestamp in seconds.

And then we call format to format the date into MM/DD/YYYY format.

And so dateString is ‘02/01/2021’ .

Use the moment Function and the format Method

We can just use the moment function without the unix method to create a moment object from a timestamp.

For instance, we can write:

import moment from 'moment'  
const dt = +new Date(2021,1,1)  
const dateString = moment(dt).format("MM/DD/YYYY");  
console.log(dateString)

The moment function takes a timestamp in milliseconds.

Therefore, we don’t have to divide dt by 1000 when we pass it in.

The rest of the code is the same and we get the same result as before.

Conclusion

We can convert a timestamp to a calendar date with format with the moment function or the unix method with the format method.

Categories
JavaScript Answers

How to Get the Browser’s Scrollbar Sizes with JavaScript?

Sometimes, we want to get the scrollbar size of an element with JavaScript.

In this article, we’ll look at how to get the size of the scrollbar that’s part of a scrollable element with JavaScript.

Use the getBoundingClientRect Method and the scrollHeight Property with JavaScript

We can get the element’s scrollbar size with the getBoundingClientRect method and the scrollHeight property of an element with JavaScript.

To do this, we subtract the height property value retuned by getBoundingClientRect method by the scrollHeight property’s value to get the width of the horizontal scrollbar.

For instance, if we have:

<div id="app" style='width: 100px; overflow-x: scroll'></div>

Then we can add elements to the div and get the horizontal scrollbar height by writing:

const app = document.querySelector('#app')
for (let i = 0; i < 100; i++) {
  const span = document.createElement('span')
  span.textContent = i
  app.appendChild(span)
}

const getScrollbarHeight = (el) =>{
  return el.getBoundingClientRect().height - el.scrollHeight;
};
console.log(getScrollbarHeight(app))

We get the div with querySelector .

Then we add some spans into the div.

The div has width set and overflow-x set to scroll.

This means the div should have a horizontal scrollbar.

Next, we create the getScrollbarHeight function that subtracts the height from getBoundingClientRect by the scrollHeight , which gives us the height of the horizontal scrollbar.

Then we log the scrollbar height with console log.

Likewise, we can get the scrollbar width with:

<div id="app" style='height: 100px; overflow-y: scroll'></div>

and:

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

const getScrollbarHeight = (el) =>{
  return el.getBoundingClientRect().width - el.scrollWidth;
};
console.log(getScrollbarHeight(app))

We add p elements into a div that’s scrollable vertically.

Instead of subtracting the heights, we subtract the widths.

And we should get the scrollbar width from the console log.

Conclusion

We can get the scrollbar width and height by calling the getBoundingClientRect method and the scroll width or height and getting the difference between the 2.

Categories
JavaScript Answers

How to fix Jest mock the same function twice with different arguments?

To fix Jest mock the same function twice with different arguments, we call mockReturnValueOnce.

For instance, we write

myMock.mockReturnValueOnce(10).mockReturnValueOnce("x").mockReturnValue(true);

to call mockReturnValueOnce on the myMock mock object.

Then we call mockReturnValue again to return a different mock value for a different call.

Finally, we call mockReturnValue to return a 3rd value for myMock.

Then we can check them with

expect(mock).toHaveBeenNthCalledWith(1, "1st call args");
expect(mock).toHaveBeenNthCalledWith(2, "2nd call arg 1", "2nd call arg 2");

to check with the arguments that mock is called with in different calls.

Categories
JavaScript Answers

How to Convert a Floating-Point Number to a Whole Number in JavaScript?

Converting a floating-point number to a whole number is something that we’ve to do sometimes in JavaScript apps.

In this article, we’ll look at how to convert a JavaScript floating-point number to a whole number.

Math.floor

The Math.floor method lets us round a number down to the nearest integer.

For instance, we can use it by writing:

const intvalue = Math.floor(123.45);  
console.log(intvalue)

Then we get 123 as the value of intValue .

Math.ceil

The Math.ceil method lets us round a number up to the nearest integer.

For instance, we can write:

const intvalue = Math.ceil(123.45);  
console.log(intvalue)

Then intValue is 124.

Math.round

The Math.round method lets us round a number down to the nearest integer if the first decimal digit is 4 or lower.

Otherwise, it rounds the number up to the nearest integer.

For instance, if we have:

const intvalue = Math.round(123.45);  
console.log(intvalue)

Then intValue is 123.

Math.trunc

The Math.trunc method lets us return the integer part of a number by removing the fractional digits.

For example, we can write:

const intvalue = Math.trunc(123.45);  
console.log(intvalue)

Then intValue is 123.

parseInt

The parseInt function lets us convert a floating-point number to an integer.

It works like Math.trunc in that it removes the fractional digits from the returned number.

For example, we can write:

const intvalue = parseInt(123.45);  
console.log(intvalue)

And intValue is 123.

To make sure that we return a decimal number, we pass 10 into the 2nd argument:

const intvalue = parseInt(123.45, 10);  
console.log(intvalue)

Conclusion

JavaScript provides a few functions and methods to lets us convert floating-point numbers to integers.