簡體   English   中英

如何找到無線電組檢查的屬性

[英]How to find radio group checked property

在這里,我在一個頁面中有三個廣播組。 但在整個頁面中,我只想選擇一個單選選項。 就像我選擇星期一一樣,星期二的選擇應該自動取消選中。 我該如何繼續進行邏輯,下面的邏輯沒有按預期工作。

示例 JSON:

{
report:[
{
day:'Monday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Tuesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Wednesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
}
]}

JS代碼

for(var I=0; I<reports.length; I++){
var radios = document.getElementsByTagName('input')
if(radios[I].type === 'radio' && radios[I].checked){
document.getElementById(radios[I].id).checked = false
}

您可以為所有這些單選按鈕指定相同的名稱,然后只檢查一個單選按鈕。

如果您能夠在 SurveyJS 中創建單選按鈕,您應該能夠為按鈕組命名,因此不需要任何額外的 JavaScript。 查看他們的文檔以獲取示例。

看起來像按鈕的那種嵌套結構可以通過像動態面板或 SurveyJS 中的級聯條件之類的東西來實現。 您應該能夠根據所選日期使用"visibleIf"動態呈現可用時隙。

我肯定會圍繞 SurveyJS 的文檔進行挖掘,以在那里找到解決方案,而不是繞開它。 但僅作為練習,您當前代碼中的問題可能是您正在按 ID 選擇一個按鈕,如果您嘗試為多個按鈕提供相同的 ID,它將無法正常工作。 畢竟,您已經將目標按鈕設置為radios[I] ,因此您可以只使用radios[I].checked = false 或者問題可能是您在做出新選擇之后取消選中所選按鈕,這實際上可能取消選中您剛剛單擊的按鈕。 很難說沒有額外的信息,但無論如何,根據可能不是實際輸入數量(您正在使用reports.length )的值循環輸入可能不是最好的主意,因為該值可能與表單中的輸入數量不同,這意味着並非所有輸入都包含在循環中。 以下是您可以做的幾個示例:

// Get all radio buttons
const radioButtons = document.querySelectorAll('input[type="radio"]')

// If you need to uncheck the previously selected one (don't do this if you can avoid it!)
radioButtons.forEach(radioButton => {
  // Use a mousedown event instead of click
  // This gives you time to uncheck the previous one before the new one gets checked
  radioButton.addEventListener('mousedown', () => {
    // Get the currently selected button and uncheck it
    const currentlySelected = document.querySelector('input[type="radio"]:checked')
    if (currentlySelected) currentlySelected.checked = false
  })
})

// You can add further options to the querySelector, such as [name]
// This gets the currently selected button in the specified group
const checkedRadioButton = document.querySelector('input[type="radio"][name="group-name"]:checked')

這是一個演示這種“假”單選按鈕功能的小提琴(沒有“名稱”屬性)。

暫無
暫無

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

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