Home » Php » javascript – How to know which radio button is selected in jquery?

javascript – How to know which radio button is selected in jquery?

Posted by: admin April 23, 2020 Leave a comment

Questions:

here this is my code… here i am generating radio button dynamically using php code…

my problem is how to get which radio button selected on click of addForm() function…

<div class="modal-body">
    <div> <input type="radio" name="form" value="Form-Name">Form-Name</div>
    <div> <input type="radio" name="form" value="Kalpit-Contact">Kalpit-Contact</div>
    <div> <input type="radio" name="form" value="Kalpit-Contact test">Kalpit-Contact test</div>
</div>
<div class="modal-footer"> 
    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
    <button type="button" class="btn btn-primary" onclick="addForm()">Add Page</button> 
</div>

Thanks in advance

How to&Answers:
var selectedValue = $("input[name=form]:checked").val();

Answer:

You should do it like this:

var radio = jQuery('input[name="form"]:checked');

You can then retrieve your radio value or other attributes:

var value = radio.val();

It’s a good idea to see if any radio is checked before doing that:

if (radio != undefined)
{
    //do what you need to
}

Answer:

Alternatively, you can also try this –

    $(".modal-body input[type=radio]").each(function(){
        if (this.checked)
        {
            console.log(this.value+" is checked");
        }
    });

Answer:

var myval = $("#myForm input[type=form]:checked").val();

I would put in a div (id=myForm) and call it in the safety of the parent, just in case you have anything else on the page, like a newsletter signup or search box with options.