-3

I'm trying to style a checkbox with CSS, but my styles are not working, can someone help me?

I'm checking the checkbox using javascript, hence the "onclick: return false" code

input[type=checkbox] {
  margin: 5px 0 0 0;
  padding: 0;
}

.checkbox:checked {
  border: 2px solid #000;
  background-color: #000;
  height: 20px;
  width: 20px;
}
<input type="checkbox" id="checkbox1" class="checkbox" onclick="return false"/>
<label for="checkbox1" class="deactivated labels" id="label1">Lowercase letters</label>

6
  • 1
    Unless you are setting the checked state of this checkbox via JavaScript, it will of course never get checked, because onclick="return false" prevents that from happening. Is that was you mean by "not working", or - what exactly? Commented Apr 9 at 9:57
  • I’m setting the checked state via JavaScript with a specific, but simple, condition validation. How can I style it based on this? Commented Apr 9 at 10:02
  • Exactly as you are doing it now ...? jsfiddle.net/fwp4Lek7 If you have a problem with this not working as expected, then please provide a proper minimal reproducible example of the issue. Commented Apr 9 at 10:09
  • If the user shouldn't be able to interact with the checkbox make it readonly? Commented Apr 9 at 10:16
  • 2
    X/Y problem..... Commented Apr 9 at 11:55

1 Answer 1

2

Your onclick="return false" handler prevents the checkbox from being checked in the first place.

If you want more control over the click event and possible cancel it (and more), you should use addEventListener instead of inline javascript.

function check_condition() {
  var result = (Math.random() < 0.5)
  alert("result of condition: " + result)
  return result
}

document.querySelector("#checkbox1").addEventListener('click', function(ev) {
  if (ev.target.checked) {
    ev.preventDefault();
    setTimeout(function() {
      ev.target.checked = check_condition()
    }, 1)
  }
})
input[type=checkbox] {
  margin: 5px 0 0 0;
  padding: 0;
}

.checkbox:checked {
  border: 2px solid #000;
  background-color: #000;
  height: 20px;
  width: 20px;
}
<input type="checkbox" id="checkbox1" class="checkbox"/>
<label for="checkbox1" class="deactivated labels" id="label1">Lowercase letters</label>

Sign up to request clarification or add additional context in comments.

2 Comments

I understand, but my project verifies if a specific condition is valid and then checks the checkbox in JavaScript. How can I style it based on this?
you want when click on checkbox it will not be checked, unless a certain condition is met?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.