Checkbox returns true even when unchecked - javascript

I am having trouble with an if-statement. In this statement i want to check if a checkbox is checked true (or isSelected) then it shall proceed with the instruction to disable a textarea. This part is working fine. But unfortunately if the checkbox is unchecked it still disabling the textarea, but it shouldn't. It should leave the textarea enabled.
function auswahl_bestaetigen(){
tweet = document.getElementById("chk_tweet")
twitter = document.getElementById("twitter")
if (tweet.isSelected = true)
twitter.disabled = true
else if (tweet.isSelected = false)
twitter.disabled = false
}
i hope someone can help me with this problem. Thanks in advance :)

The property to test whether an <input type="checkbox"> is checked is called checked. So your code should be:
if (tweet.checked) {
twitter.disabled = true
} else {
twitter.disabled = false
}
Or even shorter:
twitter.disabled = tweet.checked
Here's a simple demo:
var tweet = document.getElementById('chk_tweet')
var twitter = document.getElementById('twitter')
tweet.addEventListener('change', function () {
twitter.disabled = tweet.checked
});
#twitter[disabled] {
background: grey;
}
<input id="chk_tweet" type="checkbox" />
<textarea id="twitter"></textarea>
https://jsfiddle.net/foxbunny/m4oda3zy/

Related

How to check/uncheck a checkbox in pure JS using an onclick event?

Here is my code:
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
if (toggleButton.checked = true){
toggleButton.checked= false;
}else{
toggleButton.checked= true;
}
}
<div>
<p onclick="toggleOffer()">1 mois</p>
<input type="checkbox" id="select-time" checked>
<p onclick="toggleOffer()">12 mois</p>
</div>
It works one way: when my checkbox is checked and I click on either <p>, the checkbox gets unchecked, but I can't get the other way round to work.
You're having a problem because you're using an assignment operator, =, when a comparison operator, == is appropriate, as a few others have said.
The following, corrected javascript should therefore work:
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
if (toggleButton.checked == true) {
toggleButton.checked = false;
} else {
toggleButton.checked = true;
}
}
Actually, there's no need to ever use == true or == false in javascript anyway. You could simplify your code further to this:
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
if (toggleButton.checked) {
toggleButton.checked = false;
} else {
toggleButton.checked = true;
}
}
Or, because of the way that the .checked property works in javascript:
function toggleOffer() {
toggleButton.checked = !toggleButton.checked;
}
This always sets the checkbox to the opposite boolean value, which is the same as toggling it.
But I would also like to add that you could achieve this behaviour completely without javascript using label elements.
This would be my preferred way to do this:
<div>
<label for="select-time">1 mois</label>
<input type="checkbox" id="select-time" checked>
<label for="select-time">12 mois</label>
</div>
Change your p element to label, and add a for attribute specifying the id of the checkbox they are meant to toggle.
In your case, for="select-time" for both labels, because you want both labels to toggle the checkbox.
'toggleButton.checked = true' is setting the value rather than comparing it, what you need to do is change it to the following
if(toggleButton.checked === true){...
or since it is boolean value in question just simply do this
if(toggleButton.checked){...
I would even propose the cleaner way is to do it like this.
Instead of this
if (toggleButton.checked === true){
toggleButton.checked= false;
}else{
toggleButton.checked= true;
}
just do this toggleButton.checked = !toggleButton.checked
Your'e setting the value of checked inside the if statement instead of checking for it.
You can remove the comparison inside the if statement:
if (toggleButton.checked) { ... }
Or use ==/=== instead:
if (toggleButton.checked === true) { ... }
you can try to reverse boolean (true/false) with '!'
toggleButton.check = !toggleButton.check
!toggleButton.check is the reverse of toggleButton.check
for you it's something like this
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
toggleButton.check = !toggleButton.check
}
use if(toggleButton.checked===true) instead of if(toggleButton.checked=true)
function toggleOffer() {
let toggleButton = document.getElementById("select-time");
if(!toggleButton) return;
toggleButton.checked = !toggleButton.checked;
}
Or in one go
<p onclick="((el)=>{el.checked = !el.checked})(document.getElementById('select-time') || {})">12 mois</p>
Replace this with your current javascript code and it'll work:
const toggleButton = document.getElementById("select-time");
function toggleOffer() {
if (toggleButton.checked == true){
toggleButton.checked= false;
} else {
toggleButton.checked= true;
}
}
Beside the problem that toggleButton.checked = true should be toggleButton.checked === true (or just toggleButton.checked) it is generally not a good idea to use inline event handlers. Try adding event handling to the document, and using event delegation. Something like (function simplified):
document.addEventListener("click", toggleOffer);
function toggleOffer(evt) {
if (evt.target.dataset.offer) {
const checkBox = document.querySelector("#select-time");
checkBox.checked = !checkBox.checked;
}
}
p[data-offer] {
cursor: pointer;
}
<p data-offer="0">1 mois</p>
<input type="checkbox" id="select-time" checked>
<p data-offer="1">12 mois</p>

Click event works correctly in onclick attribute but not as addeventlistener

I'm having an interesting issue that I feel should be pretty simple but it has me stumped. I'm trying to simply track the checked state of a checkbox (if checked, enable a button, if unchecked, leave button disabled). The issue I've come up against is that I can't seem to properly track the checked state of the checkbox in an event listener, but it works if I add it as an onclick attribute in the html and I have no idea why this is.
Working code with html onclick attribute:
Html:
<input type='checkbox' name='check' id='consent' onclick='checkConsent()'>
<label for='check'>Lorem ipsum</label>
<button id='consentBtn' disabled>Agree</button>
JS:
const dialogConsentBtn = document.getElementById('consentBtn');
const consentCheck = document.getElementById('consent');
const checkConsent = () => {
if (consentCheck.checked === true) {
console.log('checked');
dialogConsentBtn.disabled = false;
} else {
console.log('unchecked');
dialogConsentBtn.disabled = true;
}
}
Non-working code with event listener:
HTML:
<input type='checkbox' name='check' id='consent'>
<label for='check'>Lorem ipsum</label>
<button id='consentBtn' disabled>Agree</button>
JS:
const dialogConsentBtn = document.getElementById('consentBtn');
const consentCheck = document.getElementById('consent');
consentCheck.addEventListener('click', (event) => {
event.preventDefault();
if (consentCheck.checked === true) {
console.log('checked');
dialogConsentBtn.disabled = false;
consentCheck.checked = true;
} else {
console.log('unchecked');
dialogConsentBtn.disabled = true;
consentCheck.checked = false;
}
}, false);
In the above (non-working) code, I get the following behavior:
checkbox does not check or uncheck visually
console.log is always printing out 'unchecked' so the if condition is
always coming back true
I have a feeling there's some sort of fundamental difference between how these two things are handled by the browser that's at the heart of my dilemma, but I just can't seem to figure out what that is. Any help with this would be greatly appreciated.
P.S. I also attempted the above code with a 'change' event in the event listener instead of a click event but I come up on the same issue.
The reasons are that a) you're event.preventDefault() on the checkbox's event which will prevent it from getting checked and b) if it's checked you uncheck it immediately with consentCheck.checked = false. You were also having the opposite logic for the agree button, so you were disabling it when the checkbox was checked and enabling it when the checkbox was unchecked.
So the checkbox in the second example can't be checked for those two reasons, see below:
const dialogConsentBtn = document.getElementById("consentBtn");
const consentCheck = document.getElementById("consent");
consentCheck.addEventListener(
"click",
(event) => {
// event.preventDefault();
if (consentCheck.checked === true) {
console.log("checked");
dialogConsentBtn.disabled = false; // was true
// consentCheck.checked = false;
} else {
console.log("unchecked");
dialogConsentBtn.disabled = true; // was false
// consentCheck.checked = true;
}
},
false
);
<input type="checkbox" name="check" id="consent" />
<label for="check">Lorem ipsum</label>
<button id="consentBtn" disabled>Agree</button>
Like the answer above, you're preventing the default action by calling the event.preventDefault() method. In addition to that, you should be using an onChange event rather than a click.

javascript onchange checkboxes still select on cancel

<script>
function no_email_confirm() {
if (document.getElementsByName("no_email")[0].checked == false) {
return true;
} else {
var box= confirm("Sure?");
if (box==true)
return true;
else
document.getElementsByName("no_email")[0].checked == false;
}
}
</script>
And here is my HTML for the checkbox:
<input type="checkbox" id="no_email" name="no_email" onchange="no_email_confirm()"></input>
For some reason, this gives me the confirm pop up the first time I check the box, but not for any click after that. Also, even if I click "Cancel" it still checks the check box. I've searched on here and for some reason, no matter what I try, I can't get it to work properly.
It should confirm if they really want to check the box, if they select "Yes" then it checks it, if not, then it doesn't check it. I can get it to work without the name no_email, but I can't change that..
Anyone have any ideas?
Looks like you've got several errors in there, most notably using == when you probably meant =. Instead, add an event listener and make sure the assignment works:
var box = document.querySelector('#no_email');
box.addEventListener('change', function no_email_confirm() {
if (this.checked == false) {
return true;
} else {
var confirmation= confirm("This means that the VENDOR will NOT RECEIVE ANY communication!!!!");
if (confirmation)
return true;
else
box.checked = false;
}
});
http://jsfiddle.net/A3VGg/1/

Controlling Checkboxes in HTML

I am attempting to add a No Preference choice to my check box list and what I would like to happen is as follows:
All checkboxes that are selected become unchecked when "No Preference" is selected.
If "No Preference" is selected and another checkbox is selected, then "No Prefernece" becomes unselected.
Here is what I have so far: http://jsfiddle.net/VuS5R/1/
Thank you for your help.
My suggestion would be to put an ID on the ul element. Then you can use getElementByID and getElementsByTagName to identify the checkboxes. Since the "No preferences" checkbox is the first, bind an event on its click to uncheck all the checkboxes if it is checked.
var checkboxes = document.getElementById('list').getElementsByTagName('input');
checkboxes[0].onclick = function(){
if(checkboxes[0].checked){
for(var i = 1; i < checkboxes.length; i++){
checkboxes[i].checked = false;
}
}
}
Here is the jsfiddle.
The elegant solution from jQuery.
The "No preference" has "Nop" class, others "pref":
$(document).ready(function ()
{
$(".Nop").click(function()
{
if ($(this).is(":checked"))
{
$(".pref").attr("checked", false);
}
});
$(".pref").click(function()
{
if ($(this).is(":checked"))
{
$(".Nop").attr("checked", false);
}
});
});
First, you have to give each checkbox a unique ID (currently they all have an ID=1).
Then, you would change your "No Preference" checkbox declaration to this:
input type="checkbox" id="0" name="BT" title="No Preference" value="0" checked="checked" onclick="return NoPreference_ClientClick()"
You will add the following JavaScript to your page:
function NoPreference_ClientClick()
{
if ($get("0").checked)
{
$get("1").checked =
$get("2").checked =
$get("3").checked =
$get("4").checked =
$get("5").checked = false;
}
else
{
$get("1").checked =
$get("2").checked =
$get("3").checked =
$get("4").checked =
$get("5").checked = true;
}
return false;
}
...I hope you get the pattern!

jQuery if (x == y) not working

So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.

Categories

Resources