Вызов функций из js, но это не работает

Я написал код внутри тега формы, когда пользователь нажимает переключатель, должны появляться курсы, и эти курсы связаны с их основным, он работал нормально, но когда я поставил тег формы, он больше не работает. Я использовал тег формы из-за PHP.

JavaScript:

<script>
  function cs() {
    if (document.getElementById("cs").checked == true) {
      document.getElementById("isco").style.display = "none";
      document.getElementById("cnco").style.display = "none";
    }
    document.getElementById("csco").style.display = "initial";
  }

  function is() {
    if (document.getElementById("is").checked == true) {
      document.getElementById("csco").style.display = "none";
      document.getElementById("cnco").style.display = "none";
    }
    document.getElementById("isco").style.display = "initial";
  }

  function cn() {
    if (document.getElementById("cn").checked == true) {
      document.getElementById("isco").style.display = "none";
      document.getElementById("csco").style.display = "none";
    }
    document.getElementById("cnco").style.display = "initial";
  }
</script>

div style = "background-color: white; text-align: left; padding-left:100px; padding-bottom: 10px">
<br><br><br>
<h3>Sign up</h3>

<form id = "sign" name = "sign" method = "POST" action = "sign.php">

  <label for = "major">Major:</label>
  <input type = "radio" name = "major" id = "cs" value = "cs" onclick = "cs()">CS
  <input type = "radio" name = "major" id = "is" value = "is" onclick = "is()">IS
  <input type = "radio" name = "major" id = "cn" value = "cn" onclick = "cn()">CN

  <div style = "display:  none;" id = "csco">
    <label for = "courses">Select the courses you finished or takes currently: </label>
    <br><br>
    <input type = "checkbox" name = "courses" value = "pr">Professional Responsibility
    <input type = "checkbox" name = "courses" value = "se">Software Engineering
    <input type = "checkbox" name = "courses" value = "alg">Analysis and Design of Algorithms
    <input type = "checkbox" name = "courses" value = "web">Web-based Systems
    <br>
  </div>
  <div style = "display: none;" id = "isco">
    <label for = "courses">Select the courses you finished or takes currently: </label>
    <br><br>
    <input type = "checkbox" name = "courses" value = "web">Web-based Systems
    <input type = "checkbox" name = "courses" value = "sad">System Analysis and Design(2)
    <br>
  </div>
  <div style = "display: none;" id = "cnco">
    <label for = "courses">Select the courses you finished or takes currently: </label>
    <br><br>
    <input type = "checkbox" name = "courses" value = "np">Introduction to Network Programming.
    <input type = "checkbox" name = "courses" value = "nd">Network Design or Network Simulation and Modeling.
    <br>
  </div>
  <br>

  <button name = "sig" id = "sig" style = "padding: 10px">Sign up</button>

</form>
</div>

есть ли способ заставить JavaScript работать?

Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
0
24
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Да, избегайте добавления слушателей прямо в html. Всегда старайтесь добавлять их по сценарию.

Код ниже работает. Посмотрите, я добавил прослушиватели onclick внутри JS-скрипта, используя
document.getElementById("elementId").onclick = functionToAssign
(в данном случае имя функции без круглых скобок).

Не забудьте удалить onclick из HTML.

Ваш текущий код не работает, вероятно, потому, что при отображении HTML функции еще не определены.

function cs() {
  if (document.getElementById("cs").checked == true) {
    document.getElementById("isco").style.display = "none";
    document.getElementById("cnco").style.display = "none";
  }
  document.getElementById("csco").style.display = "initial";
}
document.getElementById("cs").onclick = cs

function is() {
  if (document.getElementById("is").checked == true) {
    document.getElementById("csco").style.display = "none";
    document.getElementById("cnco").style.display = "none";
  }
  document.getElementById("isco").style.display = "initial";
}
document.getElementById("is").onclick = is

function cn() {
  if (document.getElementById("cn").checked == true) {
    document.getElementById("isco").style.display = "none";
    document.getElementById("csco").style.display = "none";
  }
  document.getElementById("cnco").style.display = "initial";
}
document.getElementById("cn").onclick = cn
<div style = "background-color: white; text-align: left; padding-left:100px; padding-bottom: 10px">
<br><br><br>
<h3>Sign up</h3>

<form id = "sign" name = "sign" method = "POST" action = "sign.php">

  <label for = "major">Major:</label>
  <input type = "radio" name = "major" id = "cs" value = "cs">CS
  <input type = "radio" name = "major" id = "is" value = "is">IS
  <input type = "radio" name = "major" id = "cn" value = "cn">CN


  <div style = "display:  none;" id = "csco">
    <label for = "courses">Select the courses you finished or takes currently: </label>
    <br><br>
    <input type = "checkbox" name = "courses" value = "pr">Professional Responsibility
    <input type = "checkbox" name = "courses" value = "se">Software Engineering
    <input type = "checkbox" name = "courses" value = "alg">Analysis and Design of Algorithms
    <input type = "checkbox" name = "courses" value = "web">Web-based Systems
    <br>
  </div>
  <div style = "display: none;" id = "isco">
    <label for = "courses">Select the courses you finished or takes currently: </label>
    <br><br>
    <input type = "checkbox" name = "courses" value = "web">Web-based Systems
    <input type = "checkbox" name = "courses" value = "sad">System Analysis and Design(2)
    <br>
  </div>
  <div style = "display: none;" id = "cnco">
    <label for = "courses">Select the courses you finished or takes currently: </label>
    <br><br>
    <input type = "checkbox" name = "courses" value = "np">Introduction to Network Programming.
    <input type = "checkbox" name = "courses" value = "nd">Network Design or Network Simulation and Modeling.
    <br>
  </div>
  <br>

  <button name = "sig" id = "sig" style = "padding: 10px">Sign up</button>

</form>
</div>

где я должен поставить тег скрипта? я пытаюсь ввести код в моем редакторе, он не работает, но когда я запускаю его здесь, он работает!

batla'a saleh 09.04.2019 22:22

Вам действительно нужен скрипт внутри html в качестве тега? Разве вы не можете использовать внешний файл JS? Если вы действительно хотите использовать скрипт внутри HTML, добавьте его так же, как вы добавляли раньше, просто замените текущий код на тот, который у меня есть выше, он должен работать. (попробуйте использовать <script> после HTML)

Calvin Nunes 09.04.2019 22:25

Другие вопросы по теме