J Seabolt
J Seabolt

Reputation: 2988

Custom checkbox - stop ability to check box by clicking label

I have a checkbox. It looks like this.

enter image description here

It works fine... except that you can check the box by clicking the label. This is problematic for two reasons:

  1. I don't like it
  2. I need the user to be able to click the blue link. Right now, it just checks the box

Here is my current HTML:

 <label className="container">I have read and do accept <a href={props.link}>{props.topic}</a>
    <input type="checkbox" onChange={event => props.onChange(event)}/>
    <span className="checkmark"></span>
 </label>

Here is my css, which came (roughly) from here: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_custom_checkbox

/* Hide the browser's default checkbox */
.container input {
    position: absolute;
    opacity: 0;
    cursor: pointer;
}

/* Create a custom checkbox */
.checkmark {
    position: absolute;
    top: -2px;
    left: 0;
    height: 21px;
    width: 21px;
    background-color: #eee;
}

/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
    background-color: #ccc;
}

/* When the checkbox is checked, add a blue background */
.container input:checked ~ .checkmark {
    background-color: rgb(29, 29, 29);
}

/* Create the checkmark/indicator (hidden when not checked) */
.checkmark:after {
    content: "";
    position: absolute;
    display: none;
}

/* Show the checkmark when checked */
.container input:checked ~ .checkmark:after {
    display: block;
}

/* Style the checkmark/indicator */
.container .checkmark:after {
    left: 8px;
    top: 4px;
    width: 4px;
    height: 9px;
    border: solid white;
    border-width: 0 2px 2px 0;
    -webkit-transform: rotate(45deg);
    -ms-transform: rotate(45deg);
    transform: rotate(45deg);
}

Any thoughts? You can actually play with it in the W3C pen I provided.

Upvotes: 1

Views: 454

Answers (2)

Simon G
Simon G

Reputation: 420

First, you can pull the checkbox into it's own container, then, if you want the label to semantically pertain to that specific input, you have to assign it a for attribute, and assign a corresponding id attribute to the input field. Now, you have the best of both worlds. Link is clickable, while the rest of the label checks the checkbox.

<div class="checkbox-container">
  <input type="checkbox" id="checkbox">
  <span className="checkmark"></span>
</div>
<label class="container" for="checkbox">
  I have read and do accept the <a href="#">terms and conditions</a>
</label>

Looks like you've figured out the custom checkbox UI part already, so I'll leave that to you.

Upvotes: 1

dave
dave

Reputation: 2936

.container {
    pointer-events: none;
}

.checkmark {
    pointer-events: auto;
}

.container a {
    pointer-events: auto;
}

Upvotes: 1

Related Questions