控制台输出选中的单选按钮

console out checked radio buttons

我正在尝试使用 JS 控制单选按钮以查看选中按钮的值。 Js似乎没有语法错误,但是returns undefined:

这是 HTML:

const firstName = document.querySelector('#FirstName');
const lastName = document.querySelector('#LastName');
const email = document.querySelector('#email');
const comments = document.querySelector('#comments');

let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');

let meeting;


if (meeting1.checked) {
  meeting = meeting1.value;
  console.log(meeting = "1");
} else if (meeting2.checked) {
  meeting = meeting2.value;
  console.log(meeting = "2")
} else if (meeting3.checked) {
  meeting = meeting3.value;
  console.log(meeting = "3")
} else if (meeting4.checked) {
  meeting = meeting4.value;
  console.log(meeting = "4")
}

const submitform = document.querySelector('#submitform');

submitform.addEventListener('click', function() {
  console.log(` Name: ${firstName.value}, Last Name: ${lastName.value}, Email: ${email.value}, Comment: ${comments.value} Type of meeting: ${meeting}`);
});
<fieldset>
  <legend>Would you like to meet for?</legend>

  <label><input type="radio" id="meetingtype1" name=meetingtype value="coffee" > A coffee</label>
  <label><input type="radio" id="meetingtype2" name=meetingtype value="zoom"> A zoom meeting</label>
  <label><input type="radio" id="meetingtype3" name=meetingtype value="drive"> A drive to Eilat</label>
  <label><input type="radio" id="meetingtype4" name=meetingtype value="chef"> A chef meal</label>

  <button id="submitform" type="submit">Submit</button>

非常感谢!

由于您想在单击按钮时将 value/log 检查到您的控制台,因此请确保在 EventListener 内部而不是在函数外部使用 if-else-statement .如果你按照自己的方式写if-else-statement,它会在页面第一次加载时执行。

要打印出所选会议的当前价值,请将您的 JavaScript 代码更改为此。我修改了你提供的代码。

let meeting1 = document.querySelector('#meetingtype1');
let meeting2 = document.querySelector('#meetingtype2');
let meeting3 = document.querySelector('#meetingtype3');
let meeting4 = document.querySelector('#meetingtype4');
let meeting;

const submitform = document.querySelector('#submitform');

submitform.addEventListener('click', function () {
    if (meeting1.checked){
        meeting = meeting1.value;
    } else if (meeting2.checked){
        meeting = meeting2.value;
    } else if (meeting3.checked){
        meeting = meeting3.value;
    } else if (meeting4.checked){
        meeting = meeting4.value;
    }
    console.log(`Type of meeting: ${meeting}`);
});