簡體   English   中英

如何獲取選中的單選按鈕的值

[英]How to get the value of checked radio button

我正在嘗試制作一種對用戶輸入的內容有反應的表單。 我有一個單選按鈕列表,現在,我只想記錄在控制台中選擇的任何按鈕的值(稍后我將實現更多邏輯)。 我知道如果用戶也更改了他們的選擇,我將需要某種事件偵聽器來記錄值。

我仍在學習,因此非常感謝任何帶答案的解釋。

這是我現在擁有的一個例子。

<input type='radio' value='value1' name='example' id='value1'>
<label for='value1'>Value 1</label>
<input type='radio' value='value2' name='example' id='value2'>
<label for='value2'>Value 2</label>
<input type='radio' value='value3' name='example' id='value3'>
<label for='value3'>Value 3</label>
let valueName = document.querySelector('input[name="example"]:checked').value;

當我將 valueName 記錄到控制台時。 我收到 TypeError: Cannot read properties of null (reading 'value'.

我不確定從這里去哪里。

要獲得即時值(即:在 DOM 就緒時),您需要在其中一個無線電輸入上checked屬性。
然后使用addEventListener()獲取更改值,例如:

 const getValue = () => document.querySelector('input[name="example"]:checked').value; console.log(getValue()) // Do something on change: document.querySelectorAll('input[name="example"]').forEach(elExample => { elExample.addEventListener("input", () => { console.log(getValue()) }); });
 <label><input type='radio' value='value1' name='example' checked> Value 1</label> <label><input type='radio' value='value2' name='example'> Value 2</label> <label><input type='radio' value='value3' name='example'> Value 3</label>

錯誤的原因是因為您在代碼運行時指定的選擇器為 NULL。

如果您正在執行document.querySelector('input[name="example"]:checked').value onload,則選擇器不存在,因為沒有具有name="example"且具有checked屬性的input 然而,有name="example"的三個input元素,但這不是您要告訴 JavaScript 選擇的內容。

要按照您的意願實現此功能,您需要使用您在問題中正確假設的事件偵聽器。

 // Select all inputs with name="example" var radios = document.querySelectorAll("input[name=\"example\"]"); // Use Array.forEach to add an event listener to each radio element. radios.forEach(function(radio) { radio.addEventListener('change', function() { let valueName = document.querySelector('input[name="example"]:checked').value; console.log(valueName) }) });
 <input type='radio' value='value1' name='example' id='value1'> <label for='value1'>Value 1</label> <input type='radio' value='value2' name='example' id='value2'> <label for='value2'>Value 2</label> <input type='radio' value='value3' name='example' id='value3'> <label for='value3'>Value 3</label>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM