背景:

  <input type="radio">,该标签表示的是单选按钮,这个类型相对于其他类型的获取,比较特殊,特此记录一下。

获取方式:

  1. 使用选择器直接获取(注意选择器这种方式的使用);

 1 <html>
 2 <head>
 3   <title>标题示例</title>
 4   <meta charset="UTF-8">
 5   <style>
 6   </style>
 7 </head>
 8 <body>
 9 <form>
10   <p>Please select your preferred contact method:</p>
11   <div>
12     <input type="radio" id="contactChoice1"
13            name="contact" value="email">
14     <label for="contactChoice1">Email</label>
15 
16     <input type="radio" id="contactChoice2"
17            name="contact" value="phone">
18     <label for="contactChoice2">Phone</label>
19 
20     <input type="radio" id="contactChoice3"
21            name="contact" value="mail">
22     <label for="contactChoice3">Mail</label>
23   </div>
24   <div>
25     <button type="button">Submit</button>
26   </div>
27 </form>
28 <script>
29   let ele = document.querySelector('button')
30   let form = document.querySelector('form')
31   ele.addEventListener('click', function () {
32       let x = form.querySelector("input[name='contact']:checked")
33       console.log(x.value)
34   })
35 </script>
36 </body>
37 </html>

 

  2. 使用FormData对象获取;

 1 <html>
 2 <head>
 3   <title>标题示例</title>
 4   <meta charset="UTF-8">
 5   <style>
 6   </style>
 7 </head>
 8 <body>
 9 <form>
10   <p>Please select your preferred contact method:</p>
11   <div>
12     <input type="radio" id="contactChoice1"
13            name="contact" value="email">
14     <label for="contactChoice1">Email</label>
15 
16     <input type="radio" id="contactChoice2"
17            name="contact" value="phone">
18     <label for="contactChoice2">Phone</label>
19 
20     <input type="radio" id="contactChoice3"
21            name="contact" value="mail">
22     <label for="contactChoice3">Mail</label>
23   </div>
24   <div>
25     <button type="button">Submit</button>
26   </div>
27 </form>
28 <script>
29   let ele = document.querySelector('button')
30   let form = document.querySelector('form')
31   ele.addEventListener('click', function () {
32       var data = new FormData(form);
33       var output = "";
34       for (const entry of data) {
35           output = entry[0] + "=" + entry[1] + "\r";
36       };
37       console.log(output)
38   })
39 </script>
40 </body>
41 </html>

 

参考地址:

  1. MDN:https://developer.mozilla.org/zh-CN/docs/Web/HTML/Element/input#%E8%A1%A8%E5%8D%95_%3Cinput%3E_%E7%B1%BB%E5%9E%8B

  2. https://blog.csdn.net/qq_39822451/article/details/82753282