'Put value null if none of checkbox is selected [closed]
get_genre_value=this.value; //setting value of current check box to get_genre_value.
Here i had globally declared var get_genre_value; which is necessary for my project and I am taking the value from get_genre_value on button click. Selecting checkbox value and getting it was easy but how am I able to set the value to null for get_genre_value if no check box is selected this got me thinking hard, as the get_genre_value will use its value stored globbaly if I try to click the button second time without selecting any checkbox , any help would be much appreciated.
Solution 1:[1]
Here is an example how to do it:
You set get_genre_value to null in the beginning.
For each checkbox you add an EventListener. In the callback you check, if the checkbox is checked:
- It is: You uncheck the checkbox that was checked before (it is perhaps
nullif no checkbox was checked before) and set get_genre_value to the value of the checkbox - It is not: You set get_genre_value to
nullagain
let get_genre_value = null;
const checkboxes = document.querySelectorAll("input[name=select]");
checkboxes.forEach((checkbox) => {
checkbox.addEventListener("change", (event) => {
if (event.target.checked) {
const checkedbefore = document.querySelector(`input[name=select][value=\"${get_genre_value}\"]`);
if (checkedbefore !== null)
checkedbefore.checked = false;
get_genre_value = event.target.value;
} else {
get_genre_value = null;
}
console.log(get_genre_value);
});
});
<input type="checkbox" name="select" value="1">
<input type="checkbox" name="select" value="2">
<input type="checkbox" name="select" value="3">
<input type="checkbox" name="select" value="4">
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Apollo79 |
