简体   繁体   English

如何使用 JavaScript 验证单选按钮?

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

How do I validate a radio button?如何验证单选按钮? I want to make it so that if the user left the radio button unclicked the section background will turn a red colour/color.我想这样做,如果用户未单击单选按钮,该部分背景将变成红色/颜色。

Here is the HTML Page这是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>

So how do I turn the background red when they leave it unchecked?那么,当他们未选中背景时,我该如何将背景变成红色呢?

Use document.querySelector("input[name='f__project']:checked") .使用document.querySelector("input[name='f__project']:checked") If this returns null , none of the radio buttons were checked, and you can display the red background.如果这返回null ,则没有选中任何单选按钮,您可以显示红色背景。

If this is in a <form> you can add the required attribute to the radio buttons.如果这是在<form>中,您可以将required属性添加到单选按钮。 If they try to submit the form without selecting one of them, the browser will display a validation error.如果他们尝试在不选择其中一个的情况下提交表单,浏览器将显示验证错误。

You need to think of some event the user will fire which you want to trigger the function that makes the background go red.您需要考虑用户将触发的某些事件,您希望触发 function 使背景 go 变红。 That could be if the user clicks on the next form control.如果用户单击下一个表单控件,则可能会发生这种情况。 Then when that event fires you test whether they checked any radio buttons.然后当该事件触发时,您测试他们是否检查了任何单选按钮。 If they did not ( !checked ) then you set the style attribute of your p element to background:red:如果他们没有( !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>

Use document.getElementById('id').checked the statement returns True or False.使用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
}

You can use CSS to manipulate the colour depending on whether the radio input is checked or not.您可以使用 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;
}

Or else you can make a Javascript function to check或者你可以打一个 Javascript function 来检查

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

The idea of radio button is that it can not be unchecked.单选按钮的想法是它不能被取消选中。

EDIT:编辑:

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

will return element if it is checked如果选中,将返回元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM