添加和删​​除复选框值到数组不起作用

时间:2015-05-26 00:45:04

标签: javascript jquery arrays checkbox

之前我已经这样做了,但由于某种原因,我当前的实现无效。

我有一些复选框,点击后,我希望将该值放入数组中。再次单击该复选框时,我想删除该值。

HTML:

<div class="fieldwrap form-filters">
  <label for="filter0" class="icon-text checkbox">
      <input type="checkbox" id="filter0" name="filter0" value="Coast" class="hidden" />
    Coast</label>
  <label for="filter1" class="icon-text checkbox">
      <input type="checkbox" id="filter1" name="filter1" value="Great views" class="hidden" />
    Great views</label>
  <label for="filter2" class="icon-text checkbox">
      <input type="checkbox" id="filter2" name="filter2" value="Historic" class="hidden" />
    Historic</label>
  <label for="filter3" class="icon-text checkbox">
      <input type="checkbox" id="filter3" name="filter3" value="Moorland" class="hidden" />
    Moorland</label>
  <label for="filter4" class="icon-text checkbox">
      <input type="checkbox" id="filter4" name="filter4" value="Wildlife" class="hidden" />
    Wildlife</label>
  <label for="filter5" class="icon-text checkbox">
      <input type="checkbox" id="filter5" name="filter5" value="Woodland" class="hidden" />
    Woodland</label>
</div>

JS:

var filter_options = [];

$('.form-filters input:checkbox').click(function() {

    var name = $(this).val().trim();
    var index = filter_options.indexOf(name);
    if (index > -1) {
        filter_options = filter_options.slice(index, 1);
        console.log('Remove: '+name+' at index: '+index);
    } else {
        filter_options.push(name);
        console.log('Add: '+name);
    }

    $('#result').html(filter_options.join('; '));
    console.log(filter_options);

});

DEMO: http://jsfiddle.net/WTzKR/873/

出于某种原因,它似乎随机删除了值,但似乎总是添加它们。

我做错了什么?

4 个答案:

答案 0 :(得分:1)

简单地改变:

filter_options = filter_options.slice(index, 1);

filter_options.splice(index, 1);

if区块中。

splice正是您要找的。

答案 1 :(得分:0)

试试这个:

public static class RichTextBoxExtensions
{
    public static void AppendText(this RichTextBox box, string text, Color color)
    {
        box.SelectionStart = box.TextLength;
        box.SelectionLength = 0;
        box.SelectionColor = color;
        box.AppendText(text);
        box.SelectionColor = box.ForeColor;
    }
}

答案 2 :(得分:0)

尝试input:checkbox:checked选择器只获取已选中的选项:

var filter_options = [];

$('.form-filters input:checkbox').click(function() {
    filter_options = $('.form-filters input:checkbox:checked').map(function(){
      return this.value; //get the checkbox value
    }).get();//get all values as array
    $('#result').html(filter_options.join('; '));
    console.log(filter_options);
});

答案 3 :(得分:0)

var filter_options = [];

$('.form-filters input:checkbox').click(function() {
	filter_options = [];
	$('.form-filters input:checkbox').each(function(idx, obj) {
        if($(obj).is(":checked"))
            filter_options.push($(obj).val());
    });
	$('#result').html(filter_options.join('; '));
	console.log(filter_options);
	
});