3068

I have two radio buttons and want to post the value of the selected one. How can I get the value with jQuery?

I can get all of them like this:

$("form :radio")

How do I know which one is selected?

39 Answers 39

1
2
2
$(function () {
// Someone has clicked one of the radio buttons
var myform= 'form.myform';
$(myform).click(function () {
    var radValue= "";
    $(this).find('input[type=radio]:checked').each(function () {
        radValue= $(this).val();
    });
  })
});
2

Try

myForm.myOption.value

function check() {
  console.log( myForm.myOption.value );
}
<form id="myForm">
  <input type="radio" name="myOption" value="1"> 1 <br>
  <input type="radio" name="myOption" value="2"> 2 <br>
  <input type="radio" name="myOption" value="3"> 3 <br>
</form>
<button onclick="check()">check</button>

2

This solution does not require jQuery.

const RADIO_NAME = "radioName";
const radios = Array.from(document.getElementsByName(RADIO_NAME));
const checkedRadio = radios.filter(e=>e.checked);

This uses jQuery:

const radios = Array.from($(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked);

jQuery adds an extra layer of abstraction that isn't needed here.

You could also use:

const radios = Array.from(document.querySelectorAll(`[name=${RADIO_NAME}`));
const checkedRadio = radios.filter(e=>e.checked)[0];

But getElementsByName is simple and clear enough.

1
  • Your vanilla solution seems a bit bloated. One could use document.querySelector('[name=radioName]:checked') instead. And document.querySelectorAll(':checked') for all the checked radios in the document. Commented Mar 19, 2021 at 12:01
1

What I needed to do was simplify C# code, that is do as much as possible in the front end JavaScript. I'm using a fieldset container because I'm working in DNN and it has its own form. So I can't add a form.

I need to test which text box out of 3 is being used and if it is, what's the type of search? Starts with the value, Contains the value, Exact Match of the value.

HTML:

<fieldset id="fsPartNum" class="form-inline">
<div class="form-group">
    <label for="txtPartNumber">Part Number:</label>
    <input type="text" id="txtPartNumber" class="input-margin-pn" />
</div>
<div class="form-group">
    <label for="radPNStartsWith">Starts With: </label>
    <input type="radio" id="radPNStartsWith" name="partNumber" checked  value="StartsWith"/>
</div>
<div class="form-group">
    <label for="radPNContains">Contains: </label>
    <input type="radio" id="radPNContains" name="partNumber" value="Contains" />
</div>
<div class="form-group">
    <label for="radPNExactMatch">Exact Match: </label>
    <input type="radio" id="radPNExactMatch" name="partNumber" value="ExactMatch" />
</div>

And my JavaScript is:

        alert($('input[name=partNumber]:checked', '#fsPartNum').val()); 
    if(txtPartNumber.val() !== ''){
        message = 'Customer Part Number';
    }
    else if(txtCommercialPartNumber.val() !== ''){

    }
    else if(txtDescription.val() !== ''){

    }

Just saying any containing tag with an ID can be used. For DNNers, this is good to know. The end goal here is pass to the mid-level code what is needed to start a parts search in SQL Server.

This way I don't have to copy the much more complicated previous C# code also. The heavy lifting is being done right here.

I had to look a bit for this and then tinker with it to get it to work. So for other DNNers, hopefully this is easy to find.

1

You need access with the :checked selector:

Check this doc:

a example:

$('input[name=radioName]:checked', '#myForm').val()
$('#myForm input').on('change', function() {
	$('#val').text($('input[name=radioName]:checked', '#myForm').val());
});
#val {
  color: #EB0054;
  font-size: 1.5em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h3>Radio value: <span id='val'><span></h3>
<form id="myForm">
  <input type="radio" name="radioName" value="a"> a <br>
  <input type="radio" name="radioName" value="b"> b <br>
  <input type="radio" name="radioName" value="c"> c <br>
</form>

1

How about this?

Using change and get the value of radio type is checked...

$('#my-radio-form').on('change', function() {
  console.log($('[type="radio"]:checked').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<form id="my-radio-form">
  <input type="radio" name="input-radio" value="a" />a
  <input type="radio" name="input-radio" value="b" />b
  <input type="radio" name="input-radio" value="c" />c
  <input type="radio" name="input-radio" value="d" />d
</form>

0
1

**Please try below example to check which radio button in selected **

<script>
    $('#form1 input').on('change', function() {
       alert($('input[name=age]:checked', '#form1 ').val()); 
    });
</script>
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    <form id="form1">
      <input type="radio" name="age" value="18" /> 18 <br />
      <input type="radio" name="age" value="20" /> 20 <br />
      <input type="radio" name="age" value="22" /> 22 <br />
    </form>
1

Along with the CSS selector :checked, you can also use the prop function (as of jQuery 1.6). I can't remember what project I was working on where simply using $('#something').is(':checked') only worked sometimes, and I resorted to also using $('#something').prop('checked') worked when it failed, but it led me to using both.

In my code snippet below, I've written two helper functions, is_checked and get_group_value. The function is_checked returns a boolean true/false value; true if the input passed in the parameter is checked (also checks with the prop() function) or false if it's not checked. The function get_group_value takes the name of the radio inputs and returns the value of the one that is checked, or an empty string if none are checked. These helper functions will also work with checkboxes, not just radio buttons.

Since the question did not define when they're retrieving the value(s), I've written a few listeners for four (3) different scenarios: when interacting with any radio button, when submitting the form, and when clicking one of these hard-coded buttons to do a one-time retrieval of the value of the group.

Please note that I'm using "click" to identify when the user interacts with the radio input element because "change" will never get triggered since the "value" attribute doesn't get changed when it's checked or not. I use this for checkboxes as well as radio buttons.

function is_checked(input) {
  var $input = $(input);
  return $input.is(':checked') || $input.prop('checked'); //Returns a boolean value. True if checked, false if not.
}
function get_group_value(group_name) {
  var $inputs = $('[name="' + group_name + '"]:checked');
  if ($inputs.length) { return $inputs.first().val(); } //If it exists, return the value of the first one found
  return ''; //If it doesn't exist, return nothing
}
$('form').on('submit', function(e) {
  e.preventDefault();
  var $form = $(this), results = {};
  $form.find('input[type=radio]').each(function() {
    var $input = $(this);
    if (is_checked(this)) {
      results[$input.attr('name')] = $input.val();
    }
  });
  console.info('Form Results', results);
});
$('form input[type=radio]').on('click', function(e) {
  var group_name = $(this).attr('name');
  console.info('Radio Button Click', group_name, get_group_value(group_name));
});
$('button.radio-button').on('click', function(e) {
  var group_name = $(this).attr('id');
  console.info('Button Click', group_name, get_group_value(group_name));
});
.my-test {
  background: #ffffff;
  color: #000000;
  padding: 16px;
}

form {
  padding: 8px;
  border: 1px solid #999999;
}

fieldset {
  border: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="my-test">
  <form>
    Group 1
    <fieldset>
      <label><input type="radio" name="example-1" value="Foo" required />Foo</label>
      <label><input type="radio" name="example-1" value="Bar" required />Bar</label>
    </fieldset>
    Group 2
    <fieldset>
      <label><input type="radio" name="example-2" value="Banana" required />Banana</label>
      <label><input type="radio" name="example-2" value="Apple" required />Apple</label>
    </fieldset>
    <button type="submit">Submit</button>
  </form>
  <p>Press this button to just get the value of the first group: <button class="radio-button" id="example-1">Foo or Bar?</button></p>
  <p>Press this button to just get the value of the second group: <button class="radio-button" id="example-2">Banana or Apple?</button></p>
</div>

0
0

jQuery plugin for setting and getting radio-button values. It also respects the "change" event on them.

 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <form id="toggle-form">
      <div id="radio">
        <input type="radio" id="radio1" name="radio" checked="checked" /><label for="radio1">Plot single</label>
        <input type="radio" id="radio2" name="radio"/><label for="radio2">Plot all</label>
      </div>
    </form>
    <script type="text/javascript">
    $( document ).ready(function() {
     //Get all radios:
     var radios = jQuery("input[type='radio']");
     checked_radios=radios.filter(":checked");
for(i=0;i<checked_radios.length;i++)
{
   console.log(checked_radios[i]);
}

    });
    </script>

or another way

<script type="text/javascript">
$( document ).ready(function() {
  //Get all radios:
  checked_radios=jQuery('input[name=radio]:checked').val(); 
for(i=0;i<checked_radios.length;i++)
{
   console.log(checked_radios[i]);
}

});
</script>
1
2

Not the answer you're looking for? Browse other questions tagged or ask your own question.