我在HTML表单中有两个单选按钮。当其中一个字段为空时,将出现一个对话框。如何查看单选按钮是否被选中?


当前回答

该代码将在提交表单时提醒所选单选按钮。它使用jQuery来获取所选的值。

$("form").submit(function(e) { e.preventDefault(); $this = $(this); var value = $this.find('input:radio[name=COLOR]:checked').val(); alert(value); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input name="COLOR" id="Rojo" type="radio" value="red"> <input name="COLOR" id="Azul" type="radio" value="blue"> <input name="COLOR" id="Amarillo" type="radio" value="yellow"> <br> <input type="submit" value="Submit"> </form>

其他回答

Try

[...myForm.sex].filter(r=>r.checked)[0].value

函数检查() { 设 v= ([...myForm.].filter(r=>r.checked)[0] ||{}).value ; 控制台.log(v); } <表单 id=“我的表单”> <输入名称=“性别”类型=“无线电”值=“男人”>男人 <输入名称=“性别”类型=“无线电”值=“女人”>女人 </form> <br><button onClick=“check()”>Check</button>

一个例子:

if (!checkRadioArray(document.ExamEntry.level)) { 
    msg+="What is your level of entry? \n"; 
    document.getElementById('entry').style.color="red"; 
    result = false; 
} 

if(msg==""){ 
    return result;  
} 
else{ 
    alert(msg) 
    return result;
} 

function Radio() { 
    var level = radio.value; 
    alert("Your level is: " + level + " \nIf this is not the level your taking then please choose another.") 
} 

function checkRadioArray(radioButtons) { 
    for(var r=0;r < radioButtons.length; r++) { 
        if (radioButtons[r].checked) { 
            return true; 
        } 
    } 
    return false; 
} 

表单

<form name="teenageMutant">
  <input type="radio" name="ninjaTurtles"/>
</form>

这个脚本

if(!document.teenageMutant.ninjaTurtles.checked){
  alert('get down');
}

小提琴:http://jsfiddle.net/PNpUS/

HTML:

<label class="block"><input type="radio" name="calculation" value="add">+</label>
<label class="block"><input type="radio" name="calculation" value="sub">-</label>
<label class="block"><input type="radio" name="calculation" value="mul">*</label>
<label class="block"><input type="radio" name="calculation" value="div">/</label>

<p id="result"></p>

JAVAScript:

var options = document.getElementsByName("calculation");

for (var i = 0; i < options.length; i++) {
    if (options[i].checked) {
        // do whatever you want with the checked radio
        var calc = options[i].value;
        }
    }
    if(typeof calc == "undefined"){
        document.getElementById("result").innerHTML = " select the operation you want to perform";
        return false;
}
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)