Home>
Thing I want to do

There are three input forms (A B C).
Enter A and the form B will be displayed.
I want the C form to be displayed when the B form is filled in.

I'm in trouble because I can't display as I want. If i could teach me, it'll helps a lot.

code
html
       
        
          hoge1
        <span>Required</span>
        
      <% = f.collection_select (: A_id, A.all,: id,: name, {}, {class: "select1", id: "item-A"})%>
        
          hoge2
        <span>Required</span>
        
      <% = f.collection_select (: B_id, B.all,: id,: name, {}, {class: "select2 hidden1", id: "item-B"})%>
        
          hoge3
        <span>Required</span>
        
      <% = f.collection_select (: C_id, C.all,: id,: name, {}, {class: "select3 hidden2", id: "item-C"})%>
    
css
 .hidden1 {
  display: none;
}
.hidden2 {
  display: none;
}
JS
Window.addEventListener ('load', function () {
  const itemA = document.getElementById ("item-A") ;
  const itemB = document.getElementById ("item-B");
  const itemC = document.getElementById ("item-C");
  itemA.addEventListener ('onchange', function () {
    if (itemA.value! = 1) {
      itemB.removeAttribute ("style", "display: none;")
    } else {
      itemB.setAttribute ("style", "display: block;")
    }
  });
});
version

ruby '2.6.5'

What we did to resolve the error

I added console.log ("Hello") to each line to see where it was stuck.
Processing can no longer be performed during the onchange event.

Currently, display: none;set in css is applied, and only input form A is displayed in the browser.
With no errors, I don't know what's different in the onchange event.

We would appreciate your cooperation. Thank you.

  • Answer # 1

    result
    For the time being, it behaved as expected.
    I would appreciate it if you could tell me if there is a part where the code can be shortened.

    JS
     window.addEventListener ('load', function () {
      const itemA = document.getElementById ("item-A");
      const itemB = document.getElementById ("item-B");
      const itemC = document.getElementById ("item-C");
      itemA.addEventListener ('input', function () {
        if (itemB.getAttribute ("style") == "display: block;" || itemA.value == 1) {
          itemB.removeAttribute ("style", "display: block;")
        } else {
          itemB.setAttribute ("style", "display: inline-block;")
        }
      });
        itemB.addEventListener ('input', function () {
        if (itemC.getAttribute ("style") == "display: block;" || itemB.value == 1) {
          itemC.removeAttribute ("style", "display: block;")
        } else {
          itemC.setAttribute ("style", "display: inline-block;")
        }
      });
    });