You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为子元素input值为空的父级li元素添加类?

Solution

To get this working, we can use jQuery's :has() selector to target the exact <li> element that contains an <input> with an empty value, then add the active class to it when the clear button is clicked. Here's how to adjust your code:

Modified JavaScript Code

$('#btn-modal-clear').on('click', function() {
  $('.select-name').multiselect('select', ['']);
  $('.select-name').multiselect('updateButtonText');
  
  // Target the li with an empty-value input and add the active class
  $('li:has(input[value=""])').addClass("active");
});

Breakdown of the Selector

  • li:has(input[value=""]): This finds every <li> element that has a descendant <input> with value="" — exactly the element we need to target.
  • .addClass("active"): Applies the active class to that matching <li>, which updates your HTML to match the expected result.

If you want to make sure no other <li> elements have the active class (to avoid multiple active items), add a line to remove the class first:

$('#btn-modal-clear').on('click', function() {
  $('.select-name').multiselect('select', ['']);
  $('.select-name').multiselect('updateButtonText');
  
  // Remove active class from all lis first
  $('li').removeClass("active");
  // Add active class to the target li
  $('li:has(input[value=""])').addClass("active");
});

Resulting HTML

<li>...</li>
<li class="active">
  <a class="myCheckboxLink" tabindex="0">
    <span class="myCheckboxSpan">
      <i class="fa fa-check fa-check-checkbox" aria-hidden="true"></i>
    </span>
    <label class="radio">
      <input value="" type="radio">Name
    </label>
  </a>
</li>
<li>...</li>

内容的提问来源于stack exchange,提问作者Philipp M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:38:03