0

I'm using a checkbox with 2 labels, 1st contains the label text and the 2nd is the styled checkbox.

form div.confirm label:first-of-type {
  background: rgba(82, 65, 65, 1);
  color: #FFF;
}

form div.confirm [type=checkbox]:checked.error+label::before {
  background: #4caf50 !important;
}
  <form method="post" id="entryform">
    <div class="w2">
      <label for="addr">Address*:</label>
      <input type="text" name="addr" id="addr" />
    </div>
    <div class="w1 confirm">
      <label for="confirmfinal">I can confirm that...</label>
      <div class="checkcheck">
        <input type="checkbox" value="1" id="confirmfinal" name="confirmfinal" />
        <label for="confirmfinal"></label>
      </div>
    </div>
<div id="submitBlock" class="w1 confirm">
        <input type="submit" name="Submit entry form" class="formbutton" value="Submit entry form">
      </div>
</form>

How do i write a CSS selector so that it styles the first label when the checkbox has a .error class?

I've tried the CSS from the snippet included here but i appears to be wrong. I simply want to set the background of the label to become red when necessary.

Thanks in advance

David G
  • 202
  • 3
  • 14

1 Answers1

1

You can't do this with straight CSS, but you can with a little JavaScript/JQuery:

$(".error").on("click", function(){
  if(this.checked){
    $("label[for='confirmfinal']").addClass("error");
  } else {
    $("label[for='confirmfinal']").removeClass("error");  
  }
});
form div.confirm label:first-of-type {
  background: rgba(82, 65, 65, 1);
  color: #FFF;
}

form div.confirm [type=checkbox]:checked.error+label::before {
  background: #4caf50 !important;
}

.error {
 font-weight:bold; color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="w1 confirm">
  <label for="confirmfinal">I can confirm that...</label>
  <div class="checkcheck">
    <input type="checkbox" value="1" id="confirmfinal" name="confirmfinal" class="error">
    <label for="confirmfinal"></label>
  </div>
</div>
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
  • Easy when simply clicking on the checkbox, but how would this work when using with jQuery .validate() ? – David G May 02 '18 at 16:57
  • @DavidG I haven't used that plug-in, but I would assume that, instead of doing this in the `click` event handler, you'd simply place this in the submit handler that is supplied to the `validate()` method. – Scott Marcus May 02 '18 at 17:05
  • Here's the link to see the https://jqueryvalidation.org/validate/, it runs after clicking a submit button not after clicking the checkbox as there will be other form elements – David G May 02 '18 at 18:20
  • So, if you add my code to the `submit` callback it will work when the form is submitted and if you add my code, as is, it will work when the checkbox gets clicked. What's the problem? – Scott Marcus May 02 '18 at 18:30