I am making a form with radio buttons in it. I am able to validate all other input except radio button. I got a accepted solution for this in this site
Using JQuery to check if no radio button in a group has been checked
but this is not working for me
http://jsfiddle.net/ghan_123/trr185L2/2/
my code
<input type='radio' name='datetime' value='1'>1
<input type='radio' name='datetime' value='2'>2
<input type='radio' name='datetime' value='3'>3
<input type='radio' name='datetime' value='4'>4
<input type='radio' name='datetime' value='5'>5
<br><button id='buttonnew'>validate</button>
jquery
$(document).ready(function(){
$("#buttonnew").click(function(){
var selection=document.querySelector('input[name="datetime"]:checked').value;
// my method
if(selection=='')
{
alert('please select a value');
}
else
{
alert('your selected value is '+selection);
}
// end my method
// other method ( given in this site link above)
if (!$("input[name='datetime']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
// end other method
});
});
when nothing is checked no alert message appears. else both give alert message on select one of these.
The problem here was you were trying to get value
of radio button when none was checked
and it used to you error on console
. So first you need to check whether anything is checked
and if yes then assign the value else assign empty value as below:
DEMO
$(document).ready(function(){
$("#buttonnew").click(function(){
var selection=document.querySelector('input[name="datetime"]:checked')!=null?
document.querySelector('input[name="datetime"]:checked').value:"";
//Conditional operator
if(selection!='')
{
alert('your selected value is '+selection);
}
else
{
alert('please select a time slot');
}
});
});
Try this one. I think you want something like this.
$(document).ready(function(){
$("#buttonnew").click(function(){
var chek=document.querySelector('input[name="datetime"]:checked');
if(chek!=null){
var selection=document.querySelector('input[name="datetime"]:checked').value;
console.log(selection);
// my method
if(selection=='')
{
alert('please select a time slot');
}
else
{
alert('your selected value is '+selection);
}
}
// end my mehod
// other method
if (!$("input[name='datetime']:checked").val()) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
// end other method
});
});
jsfiddle example: http://jsfiddle.net/ghan_123/trr185L2/2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With