0

I have a form which contains data that will be dynamically added to my form. Once the data has been added, I would like to verify the value (specifically if a radio button has been checked) of a radio button and then do different things based on which radio button is checked.

Currently, I am unable to do so as no matter the state of the radio button (i.e checked OR unchecked) I am always getting the alert ("Button is no checked").

Code:

<!DOTYPE HTML>
<html>

<head>
    <link type='text/css' rel='stylesheet' href='style.css'>
    <!--jQuery Validation-->
    <!--Loads JQuery and JQuery validate plugin-->
    <script src="//code.jquery.com/jquery-1.9.1.js"></script>
    <script type='text/javascript'>
        $(document).ready(function ()
        {


            function checkradio(radio)
            {

                if (radio.checked)
                {
                    alert("no is checked");
                }
                else
                {
                    alert("no is not checked");
                }

            }

            function radiocheck()
            {

                checkradio($('#no'));

            }

            $('#submit1').click(function ()
            {

                radiocheck();

            })


        });
    </script>
</head>

<body>    
    <input type='radio' id='yes' name='radiobutton' value='yes'>yes
    <input type='radio' checked='checked' id='no' name='radiobutton' value='no'>no
    <input type='button' id='submit1' name='submit' value='submit'>    
</body>    
</html>
HansUp
  • 95,961
  • 11
  • 77
  • 135
Kenneth .J
  • 1,433
  • 8
  • 27
  • 49
  • 1
    Check correct way to check with jQuery http://stackoverflow.com/questions/2272507/find-out-if-radio-button-is-checked-with-jquery – kuldeep.kamboj Nov 27 '13 at 05:00

4 Answers4

1

You are trying to use native DOM element checked property on a jQuery object.

Can use:

if(radio.is(':checked'));

Or pass the native DOM element to checkradio() rather than the jQuery object

checkradio($('#no')[0]);
charlietfl
  • 170,828
  • 13
  • 121
  • 150
0
function checkradio(radio){

    if(radio.prop('checked'))
    {
        alert("no is checked");
    }
    else
    {
        alert("no is not checked");
    }

}

OR

$('#submit1').click(function(){
    if($('#no').prop('checked')){
       alert("is checked");
    }else{
       alert("is not checked");
    }
})
Ankit Tyagi
  • 2,381
  • 10
  • 19
0

try this

 checkradio($("input:radio[name=radiobutton]"));
SHIN
  • 386
  • 2
  • 13
  • ID selector is more efficient. The selector has nothing to do with problem. This solution won't work either...passing same object to function. – charlietfl Nov 27 '13 at 05:05
0

change your code like

checkradio($("input[name='radiobutton']")); //This will give all radio buttons with name "radiobutton"

and in if()

add radio.is(':checked')

FIDDLE

yashhy
  • 2,856
  • 5
  • 31
  • 57