【问题标题】:jQuery / CSS selection of checkbox label [duplicate]复选框标签的jQuery / CSS选择[重复]
【发布时间】:2018-05-02 14:45:35
【问题描述】:

我正在使用带有 2 个标签的复选框,第一个包含标签文本,第二个是样式复选框。

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>

如何编写 CSS 选择器,以便在复选框具有 .error 类时设置第一个标签的样式?

我已经尝试了此处包含的 sn-p 中的 CSS,但我似乎错了。我只是想在必要时将标签的背景设置为红色。

提前致谢

【问题讨论】:

  • :在.error之后检查
  • 你不能,错误类需要在容器上

标签: javascript jquery html css forms


【解决方案1】:

你不能用直接的 CSS 做到这一点,但你可以用一点 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>

【讨论】:

  • 简单地点击复选框时很容易,但是当与 jQuery .validate() 一起使用时这将如何工作?
  • @DavidG 我没有使用过那个插件,但我会假设,而不是在 click 事件处理程序中执行此操作,您只需将其放在提交处理程序中即可提供给validate() 方法。
  • 这是查看jqueryvalidation.org/validate的链接,它在单击提交按钮后运行,而不是在单击复选框后运行,因为会有其他表单元素
  • 因此,如果您将我的代码添加到submit 回调中,它将在提交表单时起作用,并且如果您按原样添加我的代码,它将在单击复选框时起作用。有什么问题?
猜你喜欢
  • 2010-11-14
  • 2020-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-07
  • 2013-07-15
  • 2011-11-16
  • 2012-06-24
相关资源
最近更新 更多