Reputation: 77
I'm making a simple registration form with a declaration asking if the user has read the terms and conditions but when I console log the value of the checkbox it doesn't change depending on if it's checked or not. How do I do this? I've seen other people ask the question but they're using JS libraries like jQuery which I'm not using so how do you differentiate the value from checked and unchecked just using basic JS and HTML
<div class="item">
<input type="checkbox" id="checkbox" value="1">
<label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
</div>
This is the div containing the checkbox.
Upvotes: 1
Views: 3823
Reputation: 15
#AddionalNote
If the checkbox is unchecked, then its value is NULL and the value will not be passed to $_POST[..]
by submit the form.
I would like to share my solution:
<input class="Wertefeld_Checkbox" id="Is_Figure_Onboard_cb" type="checkbox" onclick="checkCheckbox(`Is_Figure_Onboard`)" />
<input class="Wertefeld" id="Is_Figure_Onboard" type="text" name="Is_Figure_Onboard" value="0" hidden="hidden" />
// The input-checkbox
tag has to have no name=
attribute
// so only the other input
tag will be passed to $_POST[..]
<script>
function checkCheckbox(ElementId) {
// Get the checkbox
var checkboxID = ElementId + "_cb";
var checkBox = document.getElementById(checkboxID);
if (checkBox.checked){
// If the checkbox is checked set value to hidden inputfield
document.getElementById(ElementId).value = "1";
} else {
// If the checkbox is unchecked set value to hidden inputfield
document.getElementById(ElementId).value = "0";
};
};
</script>
Upvotes: 0
Reputation: 89324
You need to test the .checked
property. To convert it to an integer, you can use the bitwise OR operator.
document.getElementById('checkbox').addEventListener('change', function(e){
let checked = this.checked;
console.log(checked);
console.log(checked | 0);
});
<div class="item">
<input type="checkbox" id="checkbox">
<label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
</div>
Upvotes: 1
Reputation: 21
You can use the .checked
method:
var checkBox = document.getElementById("checkbox");
if(checkbox.checked){
console.log("checked");
}
else{
console.log("unchecked");
}
Upvotes: 2
Reputation: 18076
You can add an event handler onClick in order to achieve this:
function handleClick(cb) {
cb.value = cb.checked ? 1 : 0;
console.log(cb.value);
}
<div class="item">
<input type="checkbox" id="checkbox" value="1" onclick='handleClick(this);'>
<label>I accept the <a id="termsLink" href="https://imgur.com/5lXi3Lc" target="_blank">Terms and Conditions</a></label>
</div>
Upvotes: 2