我正在尝试让一些js工作来检查我的html表单中是否选择了3个单选按钮中的一个,但我似乎无法让它工作。
目前,我正在使用
<label for="ctype"> Select Card Type:</label>
<br>
<label for="visa">Visa</label>
<input type="radio" name="ctype" id="visa" value="visa" ></input><br>
<label for="mastercard">Master Card</label>
<input type="radio" name="ctype" id="mastercard" value="mastercard"></input><br>
<label for="amex">American Express</label>
<input type="radio" name="ctype" id="amex" value="amex"></input>
if (document.forms[0].visa.checked == true){
}
else if (document.forms[0].mastercard.checked == true){
}
else if (document.forms[0].amex.checked == true){
}
else {
alert("Please select a credit card type.");
return false;
}
我也试过用document.getElementById(visa / mastercard / amex)运行它。检查但是也没有运气。
不幸的是,我不能只使用所需的html,因为它必须是js验证。
答案 0 :(得分:0)
JavaScript比较运算符为===
而不是==
。
答案 1 :(得分:0)
获取id为myForm的表单的选定ctype项的值:
$('input[name=radioName]:checked', '#myForm').val()
以下是一个例子:
$('#myForm input').on('change', function() {
alert($('input[name=ctype]:checked', '#myForm').val());
});
<form id="myForm">
<input type="radio" name="ctype" value="1" /> 1 <br />
<input type="radio" name="ctype" value="2" /> 2 <br />
<input type="radio" name="ctype" value="3" /> 3 <br />
</form>
答案 2 :(得分:0)
// alert(document.querySelector('input[type="radio"]:checked').outerHTML);
if (document.querySelector('input[type="radio"]:checked')==undefined){
alert("Please select a credit card type.");
// return false;
}
&#13;
<label for="ctype"> Select Card Type:</label>
<br>
<label for="visa">Visa</label>
<input type="radio" name="ctype" id="visa" value="visa" checked="true" ></input><br>
<label for="mastercard">Master Card</label>
<input type="radio" name="ctype" id="mastercard" value="mastercard"></input><br>
<label for="amex">American Express</label>
<input type="radio" name="ctype" id="amex" value="amex"></input>
&#13;