【问题标题】:Get value of previous element when checkbox is checked jqueryjquery选中复选框时获取前一个元素的值
【发布时间】:2022-11-24 23:37:54
【问题描述】:

当用户使用 jquery 检查复选框时,我这样做会获取 html 元素的值。我没有使用 id 因为这是重复行功能

我正在尝试这个

$(document).on('click', '.row_checkbox ', function() {
  if (this.checked) {
    console.log("checked");
    var unit_price = $(this).parent().prev().children().val();
    console.log(unit_price);
  } else {

  }
});
<table>
  <tr>
    <td>
      <input type="text" class="form-control row_price" name="order_innerprice[]">
    </td>
    <td>
      <label class="checkbox checkbox-custom-alt">
        <input type="checkbox" class="form-control row_checkbox" name="order_checkbox[]"><i></i>
     </label>
    </td>
  </tr>
</table>

【问题讨论】:

  • 我重新格式化了您的代码,以便您清楚地看到inputparent()label。所以没有 prevchildren。将 $(this).parent() 更改为 $(this).closest("td")
  • 我已经解决了我的问题
  • 使用.parent().parent() 也是一个坏主意,出于同样的原因 - 如果您将来更改布局,例如您选择不使用标签包装器并将标签作为输入的兄弟,您的代码将再次失败。

标签: html jquery


【解决方案1】:

我通过尝试这个来解决这个问题

$(document).on('click','.row_checkbox ',function(){
    if (this.checked){
        console.log("checked");
    var unit_price  =  $(this).parent().parent().prev().children().val();
    console.log(unit_price);
} else {
    
}
    
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-15
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多