[3 Ways] How to get the value of selected radio button by jQuery?
Today, I am going to answer this question to get the value of selected radio button by jQuery in 3 ways.
You might only need to use one of them as per your requirement. But I’ll cover the all 3 ways.
- When you need to get the value of selected radio button as just
onchange
event. - You can also achieve this on any button click.
- And maybe you want to get the selected radio button value when going to submit the form.
Example 1
<div class="container"> <form class="mt-5" id="saveForm"> <h4>User Role</h4> <div class="form-check"> <input onchange="userRole(this)" type="radio" name="user_role" value="editor" class="form-check-input" id="editor"> <label class="form-check-label" for="editor"> Editor </label> </div> <div class="form-check"> <input onchange="userRole(this)" type="radio" name="user_role" value="maintainer" class="form-check-input" id="maintainer"> <label class="form-check-label" for="maintainer"> Maintainer </label> </div> <div class="form-check"> <input onchange="userRole(this)" type="radio" name="user_role" value="developer" class="form-check-input" id="developer"> <label class="form-check-label" for="developer"> Developer </label> </div> <button type="button" class="btn btn-primary">Submit</button> </form> </div>
function userRole(element) { console.log('object :>> ', element.value); }
Or can be used by jQuery change event.
$(document).ready(function() { $("[type='radio']").change(function(){ console.log(this.value); }) })
Example 2
$(document).ready(function() { $("button").click(function(){ console.log('on button click :>> ', $("[type='radio']:checked").val()); }) })
Example 3
$(document).ready(function() { $("#saveForm").on("submit", function(e){ e.preventDefault(); console.log($("[type='radio']:checked").val()); }) })
That’s it.
Hope it will help.
If you have another way to get the value of selected radio button by jQuery, please share in the comment section below.
I’ll recommend w3school to learn about jQuery.