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?
This code will alert the selected radio button when the form is submitted. It used jQuery to get the selected value.
$("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>
The form
<form name="teenageMutant">
<input type="radio" name="ninjaTurtles"/>
</form>
The script
if(!document.teenageMutant.ninjaTurtles.checked){
alert('get down');
}
The fiddle: http://jsfiddle.net/PNpUS/
There is very sophisticated way you can validate whether any of the radio buttons are checked with ECMA6 and method .some()
.
Html:
<input type="radio" name="status" id="marriedId" value="Married" />
<input type="radio" name="status" id="divorcedId" value="Divorced" />
And javascript:
let htmlNodes = document.getElementsByName('status');
let radioButtonsArray = Array.from(htmlNodes);
let isAnyRadioButtonChecked = radioButtonsArray.some(element => element.checked);
isAnyRadioButtonChecked
will be true
if some of the radio buttons are checked and false
if neither of them are checked.
HTML Code
<input type="radio" name="offline_payment_method" value="Cheque" >
<input type="radio" name="offline_payment_method" value="Wire Transfer" >
Javascript Code:
var off_payment_method = document.getElementsByName('offline_payment_method');
var ischecked_method = false;
for ( var i = 0; i < off_payment_method.length; i++) {
if(off_payment_method[i].checked) {
ischecked_method = true;
break;
}
}
if(!ischecked_method) { //payment method button is not checked
alert("Please choose Offline Payment Method");
}
Here is the solution which is expanded upon to not go ahead with submission and send an alert if the radio buttons are not checked. Of course this would mean you have to have them unchecked to begin with!
if(document.getElementById('radio1').checked) {
} else if(document.getElementById('radio2').checked) {
} else {
alert ("You must select a button");
return false;
}
Just remember to set the id ('radio1','radio2' or whatever you called it) in the form for each of the radio buttons or the script will not work.
Give radio buttons, same name but different IDs.
var verified1 = $('#SOME_ELEMENT1').val();
var verified2 = $('#SOME_ELEMENT2').val();
var final_answer = null;
if( $('#SOME_ELEMENT1').attr('checked') == 'checked' ){
//condition
final_answer = verified1;
}
else
{
if($('#SOME_ELEMENT2').attr('checked') == 'checked'){
//condition
final_answer = verified2;
}
else
{
return false;
}
}