LoginSignup
1

More than 5 years have passed since last update.

checkboxをappendしてcheckedにつまった話

Posted at

個人用のメモとして。

やりたかったこと

  • jsonとかのデータに従って、特定の数 checkbox を作成する
  • 条件に従ってチェックボックスの on/off を変えておく必要がある

はじめにやったこと

  1. $().append(); を forで回す
  2. append()したやつに対してprop()でcheckどうのを変更する
  • ready()したり
  • .trigger('create')したり

はじめの結果

  • チェックボックスができたはいいが、checkにならない
  • readyの中に入ってconsole.log()も出るけど走ってなくて意味不明
  • trigger('create')君にいたっては仕事をしない

最終的な対応

  • 条件によって、checkedな要素とそうでない要素を切り替えて apeend()する

コード

(function() {
  var arr = [0,1,1,0,1,1,0,0,0,1]
  for (let i = 0; i < 10; i++) {
    let addedElem;
    // trueであれば、checkedの方作る
    if (arr[i]) {
      addedElem = $('<label><input type = "checkbox" name = 1 checked>チェック</label>');
    } else {
      addedElem = $('<label><input type = "checkbox" name = 1>チェック</label>');
    }
    $('#dokka-no-area').append(addedElem);
  }
})();

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
1