如果选中单选按钮,如何转到另一个功能?(Javascript)

How to get to another function if a radio button is checked? (Javascript)

本文关键字:功能 另一个 Javascript 何转 单选按钮 如果      更新时间:2023-09-26

当选中一个单选按钮时,我想点击一个按钮进入另一个功能,如果没有选中,我想告诉用户"你需要选择其中一个选项"。

这是我代码的一部分:

function activeSection2(){
//montre la section2 - #Perso
document.getElementById("Accueil").style.display="none";
document.getElementById("Perso").style.display="block";

document.forms[1].elements[0].addEventListener("click",activeSection3,false)

当检查其中一个收音机时,我想激活代码的最后一行。

这是我的收音机:

<form>
                    <fieldset>
                    <legend>Humains</legend>
                       <input type="radio" id="aRadGUE" name="rGroupe1"><p id="GUE">Guerrier</p>
                       <input type="radio" id="aRadVOL" name="rGroupe1"><p id="VOL">Voleur</p>
                       <input type="radio" id="aRadCLE" name="rGroupe1"><p id="CLE">Clerc</p>
                       <input type="radio" id="aRadMAG" name="rGroupe1"><p id="MAG">Magicien</p>
                    </fieldset>
                   <fieldset>
                   <legend>Demi-humains</legend>
                       <input type="radio" id="aRadNAI" name="rGroupe1"><p id ="NAI">Nain</p>
                       <input type="radio" id="aRadELF" name="rGroupe1"><p id ="ELF">Elf</p>
                       <input type="radio" id="aRadHAL" name="rGroupe1"><p id="HAL">Halfelin</p>
                    </fieldset>
                </form>

function fnA() {
  alert("fn A is doing stuff...");
}
function fnB() {
  alert("fn B is doing stuff...");
}
document.getElementById("testBtn").addEventListener("click", function() {
  
  // Get the currently selected radio value
  var checked = document.querySelector("[name='fn']:checked");
  
  if(!checked) {
    // No radios checked
    alert("Please select one option...");
  } else {
    // Use the checked radio value as a function name - and trigger it!
    window[checked.value]();
  }
}, false);
<input type="radio" name="fn" value="fnA"> Use fn A<br>
<input type="radio" name="fn" value="fnB"> Use fb B<br>
<input type="button" value="TEST" id="testBtn">