2

我正在使用来自 twitter bootstrap 的模态,我想制作一个模态,当用户单击按钮时,它会出现具有特定值的复选框,并且当模态隐藏添加到我的 html 的值时(在 a.btn 旁边) ..

这是html

<body>

<!-- Get the button problem  -->

<!-- Button to trigger modal -->

启动演示模式

<!-- Modal -->
<div id="myModal" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
    <h3 id="myModalLabel">Modal header</h3>
  </div>
  <div class="modal-body">
    <label for="value">
        <input type="checkbox" name="value1" value="1">value1
    </label>
     <label for="value">
        <input type="checkbox" name="value2" value="2">value2
    </label>
     <label for="value">
        <input type="checkbox" name="value3" value="3">value3
    </label>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary">Save changes</button>
  </div>
</div>

这是我的脚本:

<script type="text/javascript">
  jQuery(document).ready(function($) {
    $('#myModal .btn').last().on('click', function(){
        var checkbox_val = $('input:checkbox:checked').val();
        var MyModal = $('#myModal');
        function get_value() {
            var allVals = [];
            $('input:checkbox:checked').each(function() {
                allVals.push(checkbox_val);
            });

            $('a.btn').after("<p>" + allVals + "</p>");
        }
        MyModal.modal('hide').on('hidden', function(){
           get_value();

        })

    });
  });
</script>

编辑 这是我选择所有复选框 ["1", "1", "1"] 时 allVals 的值

我希望值为 ["1", "2", "3"]

4

2 回答 2

3

我认为问题在于,当您allVals.push(checkbox_val);.each循环内执行操作时,您一直在推动相同的值,这就是您得到 [1,1,1] 的原因。所以更新你的jQuery:

jQuery(document).ready(function($) {
    $('#myModal .btn').last().on('click', function(){
        var MyModal = $('#myModal');
        function get_value() {
            var allVals = [];
            $('input:checkbox:checked').each(function() {
                allVals.push($(this).val()); //Use the $('this') selector
            });

            $('a.btn').after("<p>" + allVals + "</p>");
        }
        MyModal.modal('hide').on('hidden', function(){
           get_value();

        })

    });
  });
于 2013-02-07T08:36:26.293 回答
0

在控制台中,数组返回 "1","1"

$('input:checkbox:checked').each(function() {
    allVals.push(checkbox_val);// it will return first checkbox value '1' alway
});

为此,将此行替换allVals.push(checkbox_val);allVals.push($(this).val());

于 2013-02-07T08:03:11.397 回答