I have two radio buttons within an HTML form. A dialog box appears when one of the fields is null. How can I check whether a radio button is selected?
With jQuery, it'd be something like
if ($('input[name=gender]:checked').length > 0) {
// do something here
}
Let me break that down into pieces to cover it more clearly. jQuery processes things from left to right.
input[name=gender]:checked
If you want to avoid this altogether, mark one of the radio buttons as checked (checked="checked"
) in the HTML code, which would guarantee that one radio button is always selected.
if(document.querySelectorAll('input[type="radio"][name="name_of_radio"]:checked').length < 1)
Try
[...myForm.sex].filter(r=>r.checked)[0].value
function check() {
let v= ([...myForm.sex].filter(r=>r.checked)[0] || {}).value ;
console.log(v);
}
<form id="myForm">
<input name="sex" type="radio" value="men"> Men
<input name="sex" type="radio" value="woman"> Woman
</form>
<br><button onClick="check()">Check</button>
I just want to ensure something gets selected (using jQuery):
// html
<input name="gender" type="radio" value="M" /> Male <input name="gender" type="radio" value="F" /> Female
// gender (required)
var gender_check = $('input:radio[name=gender]:checked').val();
if ( !gender_check ) {
alert("Please select your gender.");
return false;
}
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;
}
Just trying to improve on Russ Cam's solution with some CSS selector sugar thrown in with the vanilla JavaScript.
var radios = document.querySelectorAll('input[type="radio"]:checked');
var value = radios.length>0? radios[0].value: null;
No real need for jQuery here, querySelectorAll is widely supported enough now.
Edit: fixed a bug with the css selector, I've included the quotes, although you can omit them, in some cases you can't so it's better to leave them in.