簡體   English   中英

如何使用 JavaScript 驗證單選按鈕?

[英]How do I validate a radio button with JavaScript?

如何驗證單選按鈕? 我想這樣做,如果用戶未單擊單選按鈕,該部分背景將變成紅色/顏色。

這是HTML頁面

<p id="caption_project">Project Selection
    <br/>
    <input type="radio" name="f__project" id="in_restaurant" value="restaurant"/>
    <label for="in_restaurant">LEGO Project</label>
    <br/>

    <input type="radio" name="f__project" id="in_humber" value="Humber News"/>
    <label for="in_humber">Humber Current Project</label>
                        <br/>

    <input type="radio" name="f__project" id="in_self" value="self-determined"/>
    <label for="in_self">Self-determined Project</label>
</p>

那么,當他們未選中背景時,我該如何將背景變成紅色呢?

使用document.querySelector("input[name='f__project']:checked") 如果這返回null ,則沒有選中任何單選按鈕,您可以顯示紅色背景。

如果這是在<form>中,您可以將required屬性添加到單選按鈕。 如果他們嘗試在不選擇其中一個的情況下提交表單,瀏覽器將顯示驗證錯誤。

您需要考慮用戶將觸發的某些事件,您希望觸發 function 使背景 go 變紅。 如果用戶單擊下一個表單控件,則可能會發生這種情況。 然后當該事件觸發時,您測試他們是否檢查了任何單選按鈕。 如果他們沒有( !checked ),那么您將 p 元素的樣式屬性設置為 background:red:

 const nextThing = document.querySelector('#next-thing'); const p = document.querySelector('p'); nextThing.addEventListener('click', function(){ const checked = document.querySelector("input[name='f__project']:checked"); if(.checked){ p,setAttribute('style': 'background;red'); } });
 <p id="caption_project">Project Selection <br/> <input type="radio" name="f__project" id="in_restaurant" value="restaurant"/> <label for="in_restaurant">LEGO Project</label> <br/> <input type="radio" name="f__project" id="in_humber" value="Humber News"/> <label for="in_humber">Humber Current Project</label> <br/> <input type="radio" name="f__project" id="in_self" value="self-determined"/> <label for="in_self">Self-determined Project</label> </p> <button id='next-thing'>Next form control</button>

使用document.getElementById('id').checked語句返回 True 或 False。

const checkedRadioButton = document.
   querySelector("input[name='f__project']:checked");

if (!checkedRadioButton) {
  // No values are selected
} else {
  // Some value is selected and the element is stored in checkedRadioButton
}

您可以使用 CSS 根據是否選中無線電輸入來操縱顏色。

input[type="radio"] {
  display: none;
}
input[type="radio"] + label {
  border: 5px solid lightblue;
  background-color: lightblue;
  cursor: pointer;
  display: block;
  height: 40px;
  width: 200px;
  text-align: center;
  line-height: 40px;
}
input[type="radio"]:checked + label {
  border: 5px solid blue;
  background-color: dodgerblue;
}

或者你可以打一個 Javascript function 來檢查

function checkRadioValidity() { 
            if(document.getElementById('in_restaurant').checked) {
                //change CSS here for the element
            }
}

單選按鈕的想法是它不能被取消選中。

編輯:

document.querySelector("input[name='f__project']:checked")

如果選中,將返回元素

暫無
暫無

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

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