简体   繁体   English

复选框上的表单更改事件单击

[英]Form change event on checkbox click

I really cant understand what is the problem here. 我真的不明白这是什么问题。 I want when checkbox in the form is clicked to get to the closest "h2" and to get its text. 我想要单击表单中的复选框以获取最接近的“ h2”并获取其文本。

HTML HTML

<form action="" method="get" id="productFilterForm">
  <h2 class="attribute-name">Brands</h2>
  <div class="option">
      <label>
          <input type="checkbox" name="Royal Canin" value="163">Royal Canin
      </label>
  </div>
  <div class="option">
      <label>
          <input type="checkbox" name="Brit" value="164">Brit
      </label>
  </div>
  <div class="option">
      <label>
          <input type="checkbox" name="Purina Pro Plan" value="165">Purina Pro Plan
      </label>
  </div>
</form>

JavaScript JavaScript的

$(document).ready(function(){
   $('#productFilterForm').on('change', 'input:checkbox', function () {
    let text = $(this).closest("h2").html(); <---- UNDEFINED
    //let text = $(this).find("h2").html(); <---- UNDEFINED
    console.log(text);
   }
});

I tried many things and methods, just cant find any element from the "input" up to the DOM tree. 我尝试了许多事情和方法,只是找不到从“输入”到DOM树的任何元素。

try this code 试试这个代码

$('#productFilterForm').on('change', function () {
let text = $(this).find("h2").html();
console.log(text);   
})

I found a solution: 我找到了解决方案:

$(document).ready(function(){
   $('#productFilterForm input:checkbox').on('change', function () {
      let text = $(this).closest('div.option').prevAll('h2.attribute-name').html();
      console.log(text);
   }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM