[英]How to keep checkbox in page 1 checked when click back from page 2 to page 1, and clear the checked button after refresh page
首先,當我從頁面2回到頁面1時,我希望保持頁面1中的復選框處於選中狀態。然后,當我刷新頁面時,我想取消選中所有復選框。
我已經完成了第一部分,即保持復選框處於選中狀態。 但是刷新頁面后,我無法清除已選中的復選框。 有什么建議么?
在這里,我提供了第1頁的HTML和jQuery代碼:
.on('click', '#btnCancel', function() { $('#indexContent').show(); $('#mainContent').empty(); $.each(radioValues, function(key, value) { $("#" + key).prop('checked', false); }); $.each(checkboxValues, function(key, value) { $("#" + key).prop('checked', false); }); }) var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#myTable :checkbox"); $checkboxes.on("change", function(){ $checkboxes.each(function(){ checkboxValues[this.id] = this.checked; }); localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues)); }); // On page load $.each(checkboxValues, function(key, value) { $("#" + key).prop('checked', value); }); var radioValues = JSON.parse(localStorage.getItem('radioValues')) || {}, $radios = $("#myTable :radio"); $radios.on("change", function(){ $radios.each(function(){ radioValues[this.id] = this.checked; }); localStorage.setItem("radioValues", JSON.stringify(radioValues)); }); // On page load $.each(radioValues, function(key, value) { $("#" + key).prop('checked', value); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table class="striped" id="myTable"> <thead> <tr> <th>Primary</th> <th>Tag / Untag</th> <th>Accounts</th> </tr> </thead> <tbody> <tr> <td><input class="with-gap" name="group1" type="radio" id="tes1" value="1" /> <label for="tes1"></label></td> <td><input type="checkbox" class="filled-in" id="filled-in-box1" value="1" /> <label for="filled-in-box1"></label></td> <td><span class="account" id="acc1">123456789</span></td> </tr> <tr> <td><input class="with-gap" name="group1" type="radio" id="tes2" value="2" /> <label for="tes2"></label></td> <td><input type="checkbox" class="filled-in" id="filled-in-box2" value="2" /> <label for="filled-in-box2"></label></td> <td><span class="account" id="acc2">147852369</span></td> </tr> </tbody> </table> <div class="col-button form-footer"> <button id="btnCancel" type="button" name="action" > Cancel </button> <button id="btnNext" type="button" name="action"> Next </button> </div>
你好我的朋友。
在您的btnCancel函數中嘗試以下操作:
$("#btnCancel").click(function(){
$('#indexContent').show();
$('#mainContent').empty();
$('input[type=checkbox]').prop('checked',false);
$('input[type=radio]').prop('checked',false);
});
這是示例代碼:
我不確定您是否錯過了粘貼某些代碼的步驟,但是您的第一個腳本行( .on('click' ...
)無效。
更改為
$('#btnCancel').on('click', function() {
$('#indexContent').show();
$('#mainContent').empty();
$.each(radioValues, function(key, value) {
$("#" + key).prop('checked', false);
});
$.each(checkboxValues, function(key, value) {
$("#" + key).prop('checked', false);
});
})
它應該工作
這是根據JSFiddle
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.