0

I write cause i see this answers are getting old and no longer works

How to style a checkbox using CSS?

I want to style checkbox box and to have it later in js script.

<label>Are you sure?
    <input type="checkbox">
</label>

Can someone tell me how to do this in 2018 ?

Freestyle09
  • 4,894
  • 8
  • 52
  • 83

2 Answers2

2

You can change the styling of a tickbox by using the :checked pseudo class.

input[type="checkbox"] {
  -webkit-appearance: none;
  border: 1px solid #0e0e0e;
  width: 20px;
  height: 20px;
  border-radius: 3px;
}

input[type="checkbox"]:checked {
  border: 1px solid red;
  position: relative;
}

input[type="checkbox"]:checked:after {
  content: "x";
}
<label>Are you sure?
  <input type="checkbox">
</label>
0

I found this really nice tutorial W3Schools You can go through it and it gives a step by step way of designing the checkbox.

For the JavaScript targeting

var checkbox = document.querySelector('input[type="checkbox"]')


checkbox.addEventListener('change',function () {

  if(document.querySelector('input[type="checkbox"]:checked')){
    //returns true if element is checked 
    alert("I am checked");
  }
})
  <label>Are you sure?
      <input type="checkbox">
  </label>

This will target the checkbox add the change event listener waiting to listen to the change of state from unchecked to checked then using the if statement to see if the value is checked or not.

Community
  • 1
  • 1
Kwabena Muriuki
  • 111
  • 1
  • 10