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

时间:2019-02-09 14:32:11

标签: javascript jquery checkbox dom-events

我真的不明白这里是什么问题。我想要单击表单中的复选框以获取最接近的“ h2”并获取其文本。

  

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

$(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);
   }
});

我尝试了很多事情和方法,只是找不到从“输入”到DOM树的任何元素。

2 个答案:

答案 0 :(得分:0)

尝试此代码

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

答案 1 :(得分:0)

我找到了解决方法:

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