Categories
JavaScript Answers

How to Check or Uncheck a Checkbox with JavaScript?

Sometimes we may want to check or uncheck a checkbox with JavaScript programmatically in our web apps.

In this article, we’ll look at how to check or uncheck a checkbox with JavaScript.

Set the checked Value of the Checkbox Element

One way to check or uncheck a checkbox with JavaScript is to set the checked property value of the HTML checkbox element.

For instance, we can write the following HTML:

<button id='check'>
  check
</button>
<button id='uncheck'>
  uncheck
</button>
<input type='checkbox' id='checkbox'>

Then we can write the following JavaScript to add click listeners to the check and uncheck buttons so we can check and uncheck the checkbox respectively:

const checkBtn = document.getElementById("check")
const uncheckBtn = document.getElementById("uncheck")
const checkbox = document.getElementById("checkbox")

checkBtn.addEventListener('click', () => {
  checkbox.checked = true
})

uncheckBtn.addEventListener('click', () => {
  checkbox.checked = false
})

In the first 3 lines, we get the elements with getElementById .

Then we call addEventListener with the 'click' string to add a click listener.

And then we pass in callbacks to set the checked property to true and false respectively.

true will check the box and false will uncheck it.

Click the Checkbox Element

Another way to toggle the checkbox is to click the checkbox input itself with the click method.

For instance, we can write the following HTML:

<button id='toggle'>
  toggle
</button>
<input type='checkbox' id='checkbox'>

Then we can add a click listener to the toggle button to click the checkbox by writing:

const toggleBtn = document.getElementById("toggle")
const checkbox = document.getElementById("checkbox")

toggleBtn.addEventListener('click', () => {
  checkbox.click()
})

We call the checkbox.click method to click the checkbox.

Set the checked Attribute with the setAttribute and removeAttribute Methods

We can add or remove the checked attribute with the setAttribute and removeAttrbute methods respectively.

For instance, if we have the following HTML:

<button id='check'>
  check
</button>
<button id='uncheck'>
  uncheck
</button>
<input type='checkbox' id='checkbox'>

Then we can add click listeners to the buttons to check and uncheck the checkbox by writing:

const checkBtn = document.getElementById("check")
const uncheckBtn = document.getElementById("uncheck")
const checkbox = document.getElementById("checkbox")
checkBtn.addEventListener('click', () => {
  checkbox.setAttribute('checked', 'checked')
})
uncheckBtn.addEventListener('click', () => {
  checkbox.removeAttribute('checked')
})

In the check button’s click listener, we call setAttribute to set the checked attribute to check the checkbox.

And in the uncheck button’s click listener, we call removeAttribute to remove the checked attribute to uncheck it.

Conclusion

To check or uncheck a checkbox with JavaScript, we can set the checked property of a checkbox.

ALso, we can call the click method to click the checkbox as if the user clicks it.

And we can also call setAttribute and removeAttribute to add and remove the checked attribute from the checkbox respectively.

Categories
JavaScript Answers

Using HTML5 Local Storage vs. Session Storage

With modern browsers, at least 2 kinds of client-side storage for small amounts of text data are provided.

One is local storage and the other is session storage.

They both have different uses in our JavaScript web apps.

In this article, we’ll look at the difference between them.

And we also look at how to use them in our JavaScript code.

Differences Between Local Storage and Session Storage

Local storage and session storage serve different purposes.

Local storage lets us store data until they’re deleted.

They stay with the domain.

And changes are available for all current and future visits to the site.

Session storage changes are only available per tab.

Changes that are made are only available in that tab until it’s close.

Once it’s closed the stored data is deleted.

Using Local Storage

To use local storage, we can call methods in the localStorage method to get and set data.

To add data, we call the localStorage.setItem method, which takes a string key and the corresponding value respectively.

Both the key and value should be strings.

If they aren’t strings, then they’ll be converted into strings.

To get data, we call localStorage.getItem with the key.

It returns the value corresponding to the given key.

And to clear all local storage data, we call localStorage.clear .

To remove a local storage item with the given key, we call localStorage.removeItem .

For instance, we can use it by writing:

localStorage.setItem('foo', 'bar')
console.log(localStorage.getItem('foo'))

'foo' is the key and 'bar' is the corresponding value.

We can remove an item with removeItem by writing:

localStorage.setItem('foo', 'bar')
localStorage.removeItem('foo')
console.log(localStorage.getItem('foo'))

getItem should return null since we removed the entry with key 'foo' .

And we can call clear to clear all local storage entries:

localStorage.setItem('foo', 'bar')
localStorage.clear()

Using Session Storage

To manipulate session storage, we just remove localStorage with sessionStorage .

So we can write:

sessionStorage.setItem('foo', 'bar')
console.log(sessionStorage.getItem('foo'))

to add an item into session storage with setItem

'foo' is the key and 'bar' is the corresponding value.

We can remove an item with removeItem by writing:

sessionStorage.setItem('foo', 'bar')
sessionStorage.removeItem('foo')
console.log(sessionStorage.getItem('foo'))

getItem should return null since we removed the entry with key 'foo' .

And we can call clear to clear all session storage entries:

sessionStorage.setItem('foo', 'bar')
sessionStorage.clear()

Conclusion

We can use local storage or session storage to store small amounts of text data.

Local storage data are saved until they’re deleted and are available throughout the site.

Session storage data are only available in the current tab and are deleted once the tab is closed.

Categories
JavaScript Answers

How to Delete First Character of a String in JavaScript?

Sometimes we need to remove the first character of a string with JavaScript.

In this article, we’ll look at how to remove the first character of a string with JavaScript.

String.prototype.substring

We can use the JavaScript string’s substring method to extract a substring from a string.

We pass in the start and end index arguments respectively.

The character at the start index is included, but the character at the end index isn’t.

The end index is optional.

If we don’t include it, then the end index is the length property value of the string.

For instance, we can write:

const str = "foobar";
const newStr = str.substring(1);
console.log(newStr)

Then newStr is 'oobar' .

String.prototype.slice

The JavaScript string’s slice method also lets us get a substring from a string.

It takes the same arguments and they’re used the same way as substring .

For instance, we can write:

const str = "foobar";
const newStr = str.slice(1);
console.log(newStr)

And we get the same result.

slice also takes negative indexes.

Index -1 is the index of the last character of a string, -2 is the index of the 2nd last character of a string, and so on.

So to call slice with negative indexes to extract the substring from the first character to the end of the string, we write:

const str = "foobar";
const newStr = str.slice(-str.length + 1);
console.log(newStr)

We multiply str.length by -1 and add 1 to that to get the index of the 2nd character of the string.

And so newStr is the same as the other examples.

Rest Operator

Since JavaScript strings are iterable objects, we can use the rest operator to get the characters other than the first in its own array.

For instance, we can write:

const str = "foobar";
const [firstChar, ...chars] = str
const newStr = chars.join('')
console.log(newStr)

We have the chars array which has an array of characters from str other than the first character.

Then we can call join with an empty string to join the characters back into a string.

And so newStr is the same as we have before.

Conclusion

We can use the substring and slice methods to extract a substring from a string that has the 2nd character to the end of the original string.

Also, we can use the rest operator to get all the characters other than the first characters and call join to join the characters back into a string.

Categories
JavaScript Answers

How to Replace a Character at a Particular Index in JavaScript?

Sometimes, we need to replace a character at a particular index in our JavaScript strings.

In this article, we’ll look at how to replace a character at a particular index with JavaScript.

Use the String.prototype.substr Method

We can extract substrings from a string with the substr method.

This will help us with the replacement since we can extract the substrings from index 0 to the index of the character we want to replace.

And we can extract the string from the index to the end of the string.

Then we can add the replacement between the 2 substrings.

For instance, we can write:

const replaceAt = (str, index, replacement) => {
  return str.substr(0, index) + replacement + str.substr(index + 1);
}

const str = 'a b c'
const newStr = replaceAt(str, 2, 'foo')
console.log(newStr)

We create the replaceAt function which takes the str string that we want to the replacement with.

The index of the character that we want to replace.

And replacement is the replacement string.

Then we return the first substring concatenated with the replacement concatenated with the 2nd substring.

So when we pass in the arguments to it, we get newStr , which is:

'a foo c'

The substr and substring method are the same so we can write:

const replaceAt = (str, index, replacement) => {
  return str.substring(0, index) + replacement + str.substring(index + 1);
}

const str = 'a b c'
const newStr = replaceAt(str, 2, 'foo')
console.log(newStr)

We can use this to replace any character with another substring of any length.

String.prototype.split and String.prototype.join

We can also use the split and join methods to split and join a string together.

For instance, we can write:

let str = 'a b c'
str = str.split('');
str[2] = 'd';
str = str.join('');
console.log(str)

We call split with an empty string to split the string into an array of characters.

Then we assign the character of a string with the given index with a new character.

And then we join the string back together with the join method and an empty string as an argument.

Therefore, str should be 'a d c’ .

This is handy for replacing one character with another.

Conclusion

To replace a character with another substring, we can split the string into substrings.

Then we can join them back together with a replacement.

We can also split a string into an array of characters, assign the character at the position to another character.

Then we can join the string back together.

Categories
JavaScript Answers

How to Watch the JavaScript Window Resize Event?

We can watch window resize events with JavaScript to detect screen size changes of any kind.

In this article, we’ll look at how to watch the JavaScript window resize event to detect window resizes.

Assign an Event Handler to the window.onresize Property

One way to add an event handler for the window resize event is to assign an event handler function to the window.onresize property.

For instance, we can write:

window.onresize = (event) => {  
  console.log(event)  
};

to assign a function to window.onresize .

The event parameter has the event object, which is the data emitted with the window resize event.

Call window.addEventListener to Attach an Resize Event Handler

We can also call the window.addEventListener method to attach an event listener for window .

To listen to the resize event, we pass in 'resize' as the first argument.

And the 2nd argument is the event handler for the resize event.

For instance, we can write:

window.addEventListener('resize', (event) => {  
  console.log(event)  
});

The event parameter is the same one as we assigned to the onresize method in the example before.

ResizeObserver

A more modern way to watch for resizing of an element is to use the ResizeObserver constructor.

It lets us create an object with tyhe observe method that takes the element we want to watch the resizing of.

For instance, we can write:

const ro = new ResizeObserver(entries => {  
  for (const entry of entries) {  
    const cr = entry.contentRect;  
    const {  
      width,  
      height,  
      top,  
      left  
    } = cr  
    console.log(entry.target);  
    console.log(width, height, top, left)  
  }  
});  
ro.observe(document.querySelector('html'));

We invoke the ResizeObserver constructor with a function that loops through the entries whyich has the items we’re watching.

And in the loop body, we get the dimensions from the entry.contentRect property.

width and height have the width and height of the element.

top and left have the x and y coordinates of the top left corner respectively.

entry.target has the element we’re watching.

Then we call ro.observe with the element that we’re watching.

If we want to watch the browser window’s resizing, then we can watch the html element.

We can select it with document.querySelector .

Conclusion

We can listen to resize events by assigning a resize event listener to the window object.

Or we can use the ResizeObserver constructor to create an object that lets us watch an element for resizing.