Categories
JavaScript Answers

How to Generate a Sequence of Numbers or Characters in JavaScript?

Sometimes, we want to generate a sequence of numbers or characters in JavaScript.

In this article, we’ll look at how to generate a sequence of numbers or characters in JavaScript.

Generate a Sequence of Numbers or Characters in JavaScript

To generate a sequence of numbers or characters in JavaScript, we can create our own function.

For instance, we write:

const makeArray = (count, content) => {
  const result = [];
  if (typeof content === "function") {
    for (let i = 0; i < count; i++) {
      result.push(content(i));
    }
  } else {
    for (let i = 0; i < count; i++) {
      result.push(content);
    }
  }
  return result;
}

const arr1 = makeArray(8, 1);
console.log(arr1)

const arr2 = makeArray(8, (i) => {
  return i * 3;
});
console.log(arr2)

We create the makeArray function that takes the count and content parameters.

count has the number of entries in the array.

content has the content we want to add, which can be generated from a function or any value.

In the function, we initialize result to an empty array.

Then we check if content is a function with typeof .

If it is, then we use a for loop to push the entries returned by content to result .

Otherwise, we push content into result directly with another for loop.

Therefore, arr1 is [1, 1, 1, 1, 1, 1, 1, 1] .

And arr2 is [0, 3, 6, 9, 12, 15, 18, 21] .

Conclusion

To generate a sequence of numbers or characters in JavaScript, we can create our own function.

Categories
JavaScript Answers

How to Convert a JavaScript Array to Object Keys?

Sometimes, we want to convert a JavaScript array to object keys.

In this article, we’ll look at how to convert a JavaScript array to object keys.

Convert a JavaScript Array to Object Keys

To convert a JavaScript array to object keys, we can use the JavaScript array’s reduce method to return an object with the array entries as keys.

To do this, we write:

const arr = ['a', 'b', 'c'];
const res = arr.reduce((acc, curr) => (acc[curr] = '', acc), {});
console.log(res)

We call arr.reduce with a callback that adds the object keys to the acc object parameter.

Then we return the acc object after that.

curr has the arr entries that are being iterated through.

And we set each property’s value to an empty string.

The comma operator always returns the last item in the list, so acc is returned in the callback.

The 2nd argument is an empty object, so we set acc to an empty object initially.

Therefore, res is:

{a: "", b: "", c: ""}

Conclusion

To convert a JavaScript array to object keys, we can use the JavaScript array’s reduce method to return an object with the array entries as keys.

Categories
JavaScript Answers

How to Detect Focus Initiated by Tab Key with JavaScript?

Sometimes, we want to detect focus initiated by tab key with JavaScript.

In this article, we’ll look at how to detect focus initiated by tab key with JavaScript.

Detect Focus Initiated by Tab Key with JavaScript

To detect focus initiated by tab key with JavaScript, we can listen to the keyup event.

And if the keyup event is triggered by a tab key and the input is focused, then we know the focus is triggered by the tab key.

For instance, we can write:

<input type="text" id="foo" />  
<input type="text" id="detect" />

to add the inputs.

Then we can detect whether the input with ID detect is focused by pressing the tab key by writing:

$(window).keyup((e) => {  
  const code = (e.keyCode ? e.keyCode : e.which);  
  if (code === 9 && $('#detect:focus').length) {  
    console.log('I was tabbed!');  
  }  
});

We call keyup on window with an event listener.

In the event listener, we check if the keyCode is 9, which is the key code for the tab key.

And we also check if there’s an element with ID detect that is focused with $(‘#detect:focus’).length .

If both are true , then we know it was focused by pressing tab.

Conclusion

To detect focus initiated by tab key with JavaScript, we can listen to the keyup event.

And if the keyup event is triggered by a tab key and the input is focused, then we know the focus is triggered by the tab key.

Categories
JavaScript Answers

How to Disable an HTML Button After One Click with JavaScript?

Sometimes, we want to disable an HTML button after one click with JavaScript.

In this article, we’ll look at how to disable an HTML button after one click with JavaScript.

Disable an HTML Button After One Click with JavaScript

To disable an HTML button after one click with JavaScript, we can call the jQuery one method on an element to attach an event handler that emits once only.

We can also call addEventListener with the once option set to true if we want to use plain JavaScript.

For instance, we can write:

<button>  
  click me  
</button>

to add a button.

Then we call one by writing:

$('button').one('click', () => {  
  $('button').attr('disabled', 'disabled');  
});

We call one with 'click' to listen to the click event on the button once.

The callback sets the disabled attribute of the button to true .

We can do the same thing with plain JavaScript by writing:

const button = document.querySelector('button');  
button.addEventListener("click", () => {  
  button.setAttribute('disabled', 'disabled')  
}, {  
  once: true  
});

We get the button with document.querySelector .

Then we call addEventListener on the button with 'click' to add a click listener to it.

And we call setAttribute to set the disabled attribute value in the callback.

In the 3rd argument, we set once to true to make the event only emit once.

Conclusion

To disable an HTML button after one click with JavaScript, we can call the jQuery one method on an element to attach an event handler that emits once only.

We can also call addEventListener with the once option set to true if we want to use plain JavaScript.

Categories
JavaScript Answers

How to Set a Dropdown’s Selected Item Based on Option Text with JavaScript?

Sometimes, we want to set a dropdown’s selected item based on option text with JavaScript.

In this article, we’ll look at how to set a dropdown’s selected item based on option text with JavaScript.

Set a Dropdown’s Selected Item Based on Option Text with JavaScript

To set a dropdown’s selected item based on option text with JavaScript, we search for the index of the option text in the dropdown.

Then we can set the selectedIndex of the select drop down to the returned index.

For instance, we write:

<select>
  <option value='yahoo'>Yahoo</option>
  <option value='bing'>Bing</option>
  <option value='google'>Google</option>
</select>

to create a drop-down with some options.

Then we write:

const textToFind = 'Google';
const dd = document.querySelector('select');
dd.selectedIndex = [...dd.options].findIndex(option => option.text === textToFind);

to set textToFind to the text we want to find.

Then we select the drop-down with document.querySelector .

Next, we spread the dd.options which has the option elements in the select drop down into an array.

Then we call findIndex to find the index of the option element that has the textToFind as the text, which is the content between the opening and closing tags.

Finally, we set the returned index as the value of dd.selectedIndex .

Therefore, we should see 'Google' selected as a result.

Conclusion

To set a dropdown’s selected item based on option text with JavaScript, we search for the index of the option text in the dropdown.

Then we can set the selectedIndex of the select drop down to the returned index.