LoginSignup
6
6

More than 3 years have passed since last update.

sessionStorageでcheckedの値を保持する

Last updated at Posted at 2019-02-18

ブラウザを閉じるまでcheckboxのcheckedの値を持っていたい。

index.html
<input type="checkbox" name="q1" data-question="q1-1" class="question_checkbox">
<input type="checkbox" name="q1" data-question="q1-2" class="question_checkbox">
<input type="checkbox" name="q1" data-question="q1-3" class="question_checkbox">
<input type="checkbox" name="q1" data-question="q1-4" class="question_checkbox">

クリック時にセッションを登録
ieでquerySelectorAllで取得した値をforeEachでループできない /(^o^)\
ie10でdataset使ってカスタムデータ属性取得できない /(^o^)\

script.js
var targets = document.querySelectorAll('.question_checkbox');
var checkboxClick = function(){
    var self = this;
    sessionStorage.setItem('input[data-question="' + self.getAttribute('data-question') + '"]', self.checked);
};
Array.prototype.forEach.call(targets, function(e){
    e.addEventListener('click', checkboxClick)
})

ページ読み込み時にセッションを確認して、'true'の場合、checkedをtrueにする。

script.js
var addSessionStorage = function() {
    var session = sessionStorage;
    Object.keys(session).forEach(function(key){
        if(key.indexOf('data-question') !== -1 && this[key] === 'true' && document.querySelector(key) !== null) {
            document.querySelector(key).checked = true;
        }
    }, session)
}

windowをloadしたタイミングで実行。

script.js
window.addEventListener('load', addSessionStorage);
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6