Rails JavaScript works fine only with direct URL

  Kiến thức lập trình

In my application I use javascript to manage the fields in the form. When I visit the website by entering the address directly in the browser eg http://IP:3000/admin/systems/new, the javascript scripts works fine. However, when I call this page from the menu, the scripts don’t work. After refreshing the page, the scripts work again.

I tried putting the scripts directly into the .html.erb file instead of application.js, hoping it would load every time, but it didn’t.

One of my javascript

document.addEventListener('DOMContentLoaded', function() {
        var optionSelect = document.getElementById('option-select');
        var dateInput1 = document.getElementById('date-input1');
        var dateInput2 = document.getElementById('date-input2');

        optionSelect.addEventListener('change', function() {
                if (optionSelect.value === '1') {
                        dateInput1.removeAttribute('readonly');
                        dateInput2.removeAttribute('readonly');
                        dateInput1.style.backgroundColor = '';
                        dateInput2.style.backgroundColor = '';
                } else {
                        dateInput1.setAttribute('readonly', true);
                        dateInput2.setAttribute('readonly', true);
                        dateInput1.style.backgroundColor = '#fbfbfe';
                        dateInput2.style.backgroundColor = '#fbfbfe';
                }
        });

        if (optionSelect.value === '') {
                dateInput1.setAttribute('readonly', true);
                dateInput2.setAttribute('readonly', true);
                dateInput1.style.backgroundColor = '#fbfbfe';
                dateInput2.style.backgroundColor = '#fbfbfe';

        }
});

application.js

import "@hotwired/turbo-rails"
import "./controllers"
import * as bootstrap from "bootstrap"
import "./select"
import "./working"

Menu link

<li class="nav-item dropdown">
              <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Systems
              </a>
                <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
                  <li><a class="dropdown-item" href="<%= new_admin_system_path %>">Add system</a></li>
                  <li><a class="dropdown-item" href="<%= admin_systems_path %>">List</a></li>
                </ul>
            </li>

How can I make it work also when I go to a page with a menu?

LEAVE A COMMENT