gpt4 book ai didi

javascript - 如何使用 javascript 或 jquery 存储复选框值?

转载 作者:行者123 更新时间:2023-11-30 12:07:08 26 4
gpt4 key购买 nike

我有多个复选框。我已将复选框值存储到本地存储,使用户能够刷新页面并仍然显示已选中或未选中的复选框。现在我需要将复选框值保存为 url 参数,以便页面可以作为保留所有未选中或选中值的链接发送。代码如下:

HTML:(复选框)

<input type="checkbox" class="faChkRnd" name="likebox" id="like">
<input type="checkbox" class="faChkRnd" name="likebox" id="like1">
<input type="checkbox" class="faChkRnd" name="likebox" id="like2">
<input type="checkbox" class="faChkRnd" name="likebox" id="like2">

更新:请注意我使用的是标签式导航菜单,并且已将标签哈希添加到 url。因此,一个 url 看起来应该是这样的: www.example.com/index.html#home

最佳答案

您可以使用 .serialize()但您必须更改 name 属性的值。

$('button').click(function(){
alert($('input').serialize());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" class="faChkRnd" name="likebox1" id="like">
<input type="checkbox" class="faChkRnd" name="likebox2" id="like1">
<input type="checkbox" class="faChkRnd" name="likebox3" id="like2">
<input type="checkbox" class="faChkRnd" name="likebox4" id="like2">
<button>getUrl</button>

下一步是从 QueryString 中获取值并设置复选框

它应该是这样的:

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

http://jsbin.com/hecora/edit?html,js

更新

当用户使用 hash 选中/取消选中复选框或执行 pushState 并将参数添加到 url 时,您可以执行“自动保存”(如果来自由于某些原因你不能为此使用 hash)。当然你需要检查browsers support首先。

示例(pushState):

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

$.each(location.search.replace('?', '').split('&'), function(i, seg) {
$('[name=' + seg.split('=')[0] + ']').attr('checked', 'checked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type="checkbox" class="faChkRnd" name="likebox1" id="like">
<input type="checkbox" class="faChkRnd" name="likebox2" id="like1">
<input type="checkbox" class="faChkRnd" name="likebox3" id="like2">
<input type="checkbox" class="faChkRnd" name="likebox4" id="like2">

http://jsbin.com/nofoto/edit?html,js

关于javascript - 如何使用 javascript 或 jquery 存储复选框值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34878569/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com