Tuesday, January 21, 2025
HomeTechJavascript - Get the value of checked checkbox?

Javascript – Get the value of checked checkbox?

In JavaScript, you can get the value of a checked checkbox using the DOM. Here’s how you can retrieve the value of a checked checkbox:

1. Using document.querySelector (for a single checkbox)

<input type="checkbox" id="myCheckbox" value="checkbox_value" />

<script>
    const checkbox = document.querySelector('#myCheckbox');
    
    if (checkbox.checked) {
        console.log(checkbox.value); // Get the value if checked
    } else {
        console.log('Checkbox is not checked');
    }
</script>

2. Using document.querySelectorAll (for multiple checkboxes)

If you have multiple checkboxes and you want to get the values of all checked checkboxes, you can use querySelectorAll to loop through them:

<input type="checkbox" name="checkboxGroup" value="Option 1" />
<input type="checkbox" name="checkboxGroup" value="Option 2" />
<input type="checkbox" name="checkboxGroup" value="Option 3" />

<script>
    const checkboxes = document.querySelectorAll('input[name="checkboxGroup"]:checked');
    
    checkboxes.forEach((checkbox) => {
        console.log(checkbox.value); // Get the value of each checked checkbox
    });
</script>

Explanation:

  • document.querySelector: Used to select a single checkbox.
  • document.querySelectorAll: Used to select all checkboxes with the specified name (or any other selector), and then you can filter with :checked to get only the checked ones.
  • .checked: Property that returns true if the checkbox is checked, and false otherwise.
  • .value: Returns the value attribute of the checkbox element.
See also  ReactJS setState()

This will log the values of all the checked checkboxes. If none are checked, no output will appear.

Let me know if you’d like further details or examples!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x