如果未选中复选框,则从url字符串中删除id?

时间:2016-04-22 17:12:40

标签: jquery url-rewriting

下面我有一个函数,当选中一个复选框时,它会将复选框parent id添加到url字符串,但是我得到的问题是,当取消选中它时,它不会从url中删除id。

var checkboxes = $('.all input[type="checkbox"]');
checkboxes.change(function() {
  var ser = '?' + checkboxes.serialize() + location.hash;
  history.pushState(null, null, ser);
});

$.each(location.search.replace('?', '').split('&'), function(i, seg) {
  $('[name=' + seg.split('=')[0] + ']').attr('checked', 'checked');   

});

更新 每个复选框父项中有两个具有相同的名称,(这只是以不同的方式显示信息。(网格和列表视图)所以我认为url字符串中的重复id号码令人困惑。

非常感谢任何建议。

2 个答案:

答案 0 :(得分:1)

实际上你所拥有的东西似乎没有过滤器。除非我遗漏了什么。



if var items = mainDictionary["items"] as? NSMutableArray {
    items.addObject(newItem)
    mainDictionary["items"] = items
}

var checkboxes = $('.all input[type="checkbox"]');
checkboxes.change(function() {
  var ser = '?' + checkboxes.serialize() + location.hash;
  console.log(ser);
});




答案 1 :(得分:1)

如果复选框包含在表单中,则序列化不会获取所有值。

根据serialize文档:复选框和单选按钮(“radio”或“checkbox”类型的输入)中的值仅在选中后才会包含。

要解决此问题,您必须自行序列化所有复选框,如:

$(function () {
  var checkboxes = $('.all input[type="checkbox"]');
  checkboxes.change(function(e) {
    var serialized = checkboxes.map(function() {
      return {'name': this.name + this.type, 'value': (this.checked) ? this.value : ' '};
    });
    var ser = '?' + $.param(serialized) + location.hash;
    // history.pushState(null, null, ser);
    $('<p>' +  ser + '</p>').appendTo('body');
  });
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>

<form action="demo_form.asp" class="all">
    <input type="checkbox" name="vehicle" value="Bike"> I have a bike<br>
    <input type="checkbox" name="vehicle" value="Car"> I have a car<br>
    <input type="checkbox" name="vehicle" value="Truck" checked> I have a truck<br>
    <input type="submit" value="Submit">
</form>