$(document).on("turbolinks:load", () => {
  const setVisibility = (field) => { 
    const select = $(`[id $= ${field}_id]`);
    const option = $("option:selected", select);
    const show = (option.text() === "Other");

    if (show) {
      $(`[id $= ${field}_text`).show();
    } else {
      $(`[id $= ${field}_text`).val("").hide();
    };
  }

  const fields = ["applicable_medium", "territory", "term",  "restriction"]; 
  for (const field of fields) {
    setVisibility(field);

    $(document).on("change", `[id $= ${field}_id]`, (event) => {
      setVisibility(field);
    })
  }
});
