jQuery,添加复选框后无法读取复选框值 [英] Jquery, cannot read checkbox value after checkbox is appended

查看:101
本文介绍了jQuery,添加复选框后无法读取复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的主要目标是,如果选中了旁边的复选框,则获取用户在文本框中键入的内容,并对所有选中的复选框求和.

My main goal is to get the amount that whatever the user has keyed in the textbox if the checkbox next to it is checked and sum all amount of the checked checkboxes.

但是我目前面临的问题是,追加复选框后,我什至无法获得该值.

But the current problem that I'm facing is, I can't even get the checkbox value after it is appended.

如何解决这个问题? 此处是Jsfiddle链接

How to solve this problem? Jsfiddle link here

$('#add_exercise').on('click', function() { 
    $('#exercises').append('<div class="exercise"><input type="text" name="amount"><input type="checkbox" name="exercise[]" class="boxes"><button class="remove">x</button></div>');
    return false; //prevent form submission
});

$('#exercises').on('click', '.remove', function() {
    $(this).parent().remove();
    return false; //prevent form submission
});

$('.boxes').on('change', function() {

    console.log('qwe')
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="#">

    <label>Exercises</label>

    <fieldset id="exercises">
        <div class="exercise">
            <input type="text" name="amount" value="">
            <input type="checkbox" name="exercise[]" class="boxes"><button class="remove">x</button>
        </div>
    </fieldset>

    <button id="add_exercise">add exercise</button>

</form>

推荐答案

您正在动态添加框,因此需要使用.on绑定更改或click事件,并迭代所有选中的复选框以获取其先前输入的值并将其添加得到总和.

You are adding boxes dynamically so need to bind change or click event using .on and iterate all checked checkboxes to get the value of it's previous input and add it to get the sum.

见下文

$('#add_exercise').on('click', function() { 
    $('#exercises').append('<div class="exercise"><input type="text" name="amount"><input type="checkbox" name="exercise[]" class="boxes"><button class="remove">x</button></div>');
    return false; //prevent form submission
});

$('#exercises').on('click', '.remove', function() {
    $(this).parent().remove();
    return false; //prevent form submission
});

$(document).on('click','.boxes', function() {
   var sum = 0;
   $('.boxes:checked').each(function(){
     //var val = $(this).prev('input').val();
     var val = $(this).siblings('input[name=amount]').val();
     sum += parseInt(val) || 0;
   });
   console.log("Sum = " + sum);
});

JSFiddle

这篇关于jQuery,添加复选框后无法读取复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆