coltonOP
@coltonOP (こるとんくん)

Are you sure you want to delete the question?

If your question is resolved, you may close it.

Leaving a resolved question undeleted may help others!

We hope you find it useful!

ラジオボタンにonclick属性を付与できない

解決したいこと

Djangoをつかっていると formを使ってラジオボタンをhtmlにかくとき、

<ul class="mendantime">
          <a class="font">{{ form.mendantime.label }}</a>
          <form name="RadioForm" action="">
          {% for radio in form.mendantime|add_class:"ff" %}
              {{ radio.tag }}
              <label for="id_mendantime_{{ forloop.counter0 }}">{{ radio.choice_label }}</label>
          {% endfor%}
          </form>
      </ul>
      <script>
          document.querySelector('ul.mendantime')?.addEventListener('click', e => e.target.type === 'radio' && formSwitch());
      </script>

<div class="taisyodaimei">
          <a class="bigfont">対象者</a>
      </div>
      
      <div class="taisyo">
      
      <ul class="treeview 1" id="1">
        <li class="expandable">
           <dt><label><input type="checkbox">総務部</label></dt>
            <ul>
                 {% for record in Soumu %}
                  <li> <dd><label><input type="checkbox">{{ record.name }}</label></dd> </li>
                 {% endfor %}
            </ul>
        </li>        
    </ul>
    
    <ul class="treeview 2" id="2">
      <li class="expandable">
         <dt><label><input type="checkbox">設計部</label></dt>
          <ul>
               {% for record in Sekkei %}
                <li> <dd><label><input type="checkbox">{{ record.name }}</label></dd> </li>
               {% endfor %}
          </ul>
      </li>        
   </ul>
  
   <ul class="treeview 3" id="3">
    <li class="expandable">
       <dt><label><input type="checkbox">HONDA勤務</label></dt>
        <ul>
             {% for record in Honda %}
              <li> <dd><label><input type="checkbox">{{ record.name }}</label></dd> </li>
             {% endfor %}
        </ul>
    </li>        
   </ul>
   
   <ul class="treeview 4" id="4">
    <li class="expandable">
       <dt><label><input type="checkbox">SUBARU勤務</label></dt>
        <ul>
             {% for record in Subaru %}
              <li> <dd><label><input type="checkbox">{{ record.name }}</label></dd> </li>
             {% endfor %}
        </ul>
    </li>        
   </ul>
  
  
  
            
      </div>



となるんですが、

これだと  {{ radio.tag }} がラジオボタンを書く表記になります。
しかしこのままだと onclick="formSwitch()" がつけられません。 どうしたらいいでしょうか?

jsファイル

function formSwitch() {

    //どのラジオボタンがチェックされているか。(条件分岐で使用)
    check0 = document.RadioForm.id_mendantime_0.checked;  
    check1 = document.RadioForm.id_mendantime_1.checked;  
    check2 = document.RadioForm.id_mendantime_2.checked;  

    //表のところで指定したクラスを取得しています。(表示・非表示の切替で使用)
    var sanju = document.querySelectorAll('.treeview 1, treeview 2');
    var ichi = document.querySelectorAll('.treeview 3');
    var niju = document.querySelectorAll('.treeview 4');

    //チェックされているラジオボタンにより分岐させていきます。
      //すべてにチェックがtrueなので、すべてにチェックされているときに表示したいコードを書きます。
    if (check0 == true) {
    //取得したクラスをforEachで展開して、それぞれのクラスのdisplayスタイルを指定します。
        sanju.forEach(function(elem){
            elem.style.display = "";
        });
        
        
        ichi.forEach(function(elem){
            elem.style.display = "none";
        });
        
        
        niju.forEach(function(elem){
            elem.style.display = "none";
        });
        
        
        
        
    }
    //上記と同様ですね。
    else if (check1 == true) {
        
        sanju.forEach(function(elem){
            elem.style.display = "none";
        });
        
        
        ichi.forEach(function(elem){
            elem.style.display = "";
        });
        
        
        niju.forEach(function(elem){
            elem.style.display = "none";
        });
        
    }
    
    
    else if (check2 == true) {
        
        sanju.forEach(function(elem){
            elem.style.display = "none";
        });
        
        
        ichi.forEach(function(elem){
            elem.style.display = "none";
        });
        
        
        niju.forEach(function(elem){
            elem.style.display = "";
        });
        
    }
    
    
}


エラー

Uncaught DOMException: Failed to execute 'querySelectorAll' on 'Document': '.treeview 1, treeview 2' is not a valid selector.
    at formSwitch (http://127.0.0.1:8000/static/js/sakusei.js:138:26)
    at HTMLUListElement.<anonymous> (http://127.0.0.1:8000/sakusei/:65:112)
formSwitch @ sakusei.js:138
(匿名) @ (インデックス):65

まったくわかりません(泣き)

0

2Answer

これではどうでしょう。

window.addEventListener('DOMContentLoaded', () => {
  const parent = document.querySelector('[name=RadioForm]');

  parent.addEventListener('click', e => {
    if (e.target.type !== 'radio') return;
    formSwitch(parent.querySelectorAll('[type=radio]'));
  });
});

function formSwitch(radioElements) {

  const displayAssign = [
    [1, 2],
    [3],
    [4],
  ];

  const treeviewElements = document.querySelectorAll('.treeview');

  radioElements.forEach((radioElem, index) => {
    displayAssign[index].forEach(v => {
      treeviewElements.forEach(elem => {
        if (elem.classList.contains(v)) elem.style.display = radioElem.checked ? 'block' : 'none';
      });
    });
  });
}
1Like

Comments

  1. @coltonOP

    Questioner

    ありがとうございます! どうやら teeview 1 のクラスの書き方が悪かったみたいです。
    treeview1 treeview2 のように クラスに空白を入れるのをやめたら1つ目の回答の方でうまく動作しました。 ありがとうございます。

</ul>のあとに

<script>
  document.querySelector('ul.mendantime')?.addEventListener('click', e => e.target.type === 'radio' && formSwitch());
</script>

を追記するとかでは駄目でしょうか。

0Like

Comments

  1. @coltonOP

    Questioner

    追加して動かしてみましたがエラーがでました 投稿内容にかいておきますので参照下さい。

Your answer might help someone💌