juan
juan

Reputation: 81954

How can I know which radio button is selected via jQuery?

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?

Upvotes: 3076

Views: 2546383

Answers (30)

Binh Ho
Binh Ho

Reputation: 4973

Using $('input[name="radioName"]').filter(":checked").val(); is the best way for me.

Tested, this works

Form

<form id="myForm">
  <input type="radio" name="radioName" value="Option1"> Option1
  <input type="radio" name="radioName" value="Option2" checked> Option2
  <input type="radio" name="radioName" value="Option3"> Option3
</form>

Jquery

$(document).ready(function() {
  $('input[name="radioName"]').on('change', function() {
     const val = $(this).filter(":checked").val();
     alert(val);
  })

  // First load check
  const val = $('input[name="radioName"]').filter(":checked").val();
  alert(val);
});

Example here: https://codepen.io/abinhho/pen/mdLrqbX

Upvotes: 7

Peter J
Peter J

Reputation: 57967

To get the value of the selected radioName item of a form with id myForm:

$('input[name=radioName]:checked', '#myForm').val()

Here's an example:

$('#myForm input').on('change', function() {
  alert($('input[name=radioName]:checked', '#myForm').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <fieldset>
    <legend>Choose radioName</legend>
    <label><input type="radio" name="radioName" value="1" /> 1</label> <br />
    <label><input type="radio" name="radioName" value="2" /> 2</label> <br />
    <label><input type="radio" name="radioName" value="3" /> 3</label> <br />
  </fieldset>
</form>

Upvotes: 4307

salman ifrahim
salman ifrahim

Reputation: 392

try this one. it worked for me

$('input[type="radio"][name="name"]:checked').val();

Upvotes: 23

Garrett
Garrett

Reputation: 3023

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.

Upvotes: 2

AuRise
AuRise

Reputation: 2452

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>

Upvotes: 1

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92627

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>

Upvotes: 2

Samir Lakhani
Samir Lakhani

Reputation: 743

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>

Upvotes: 0

Javed Khan
Javed Khan

Reputation: 395

**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>

Upvotes: 1

Alireza
Alireza

Reputation: 104870

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>

Upvotes: 1

Iyyappan Amirthalingam
Iyyappan Amirthalingam

Reputation: 324

JQuery to get all the radio buttons in the form and the checked value.

$.each($("input[type='radio']").filter(":checked"), function () {
  console.log("Name:" + this.name);
  console.log("Value:" + $(this).val());
});

Upvotes: 5

RedDragon
RedDragon

Reputation: 2138

Another option is:

$('input[name=radioName]:checked').val()

Upvotes: 58

fitorec
fitorec

Reputation: 4795

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>

Upvotes: 1

Matt Browne
Matt Browne

Reputation: 12429

If you already have a reference to a radio button group, for example:

var myRadio = $("input[name=myRadio]");

Use the filter() function, not find(). (find() is for locating child/descendant elements, whereas filter() searches top-level elements in your selection.)

var checkedValue = myRadio.filter(":checked").val();

Notes: This answer was originally correcting another answer that recommended using find(), which seems to have since been changed. find() could still be useful for the situation where you already had a reference to a container element, but not to the radio buttons, e.g.:

var form = $("#mainForm");
...
var checkedValue = form.find("input[name=myRadio]:checked").val();

Upvotes: 349

Code Spy
Code Spy

Reputation: 9964

DEMO : https://jsfiddle.net/ipsjolly/xygr065w/

	$(function(){
	    $("#submit").click(function(){      
	        alert($('input:radio:checked').val());
	    });
	 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
       <tr>
         <td>Sales Promotion</td>
         <td><input type="radio" name="q12_3" value="1">1</td>
         <td><input type="radio" name="q12_3" value="2">2</td>
         <td><input type="radio" name="q12_3" value="3">3</td>
         <td><input type="radio" name="q12_3" value="4">4</td>
         <td><input type="radio" name="q12_3" value="5">5</td>
      </tr>
    </table>
<button id="submit">submit</button>

Upvotes: 9

rmbianchi
rmbianchi

Reputation: 6531

In my case I have two radio buttons in one form and I wanted to know the status of each button. This below worked for me:

// get radio buttons value
console.log( "radio1: " +  $('input[id=radio1]:checked', '#toggle-form').val() );
console.log( "radio2: " +  $('input[id=radio2]:checked', '#toggle-form').val() );


    
<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>

Upvotes: 28

Mehdi Bouzidi
Mehdi Bouzidi

Reputation: 1995

Another way to get it:

 $("#myForm input[type=radio]").on("change",function(){
   if(this.checked) {
    alert(this.value);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
   <span><input type="radio" name="q12_3" value="1">1</span><br>
   <span><input type="radio" name="q12_3" value="2">2</span>
</form>

Upvotes: 4

user1585204
user1585204

Reputation: 977

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.

Upvotes: 1

Gautam Rai
Gautam Rai

Reputation: 2505

try it-

var radioVal = $("#myform").find("input[type='radio']:checked").val();

console.log(radioVal);

Upvotes: 4

JoshYates1980
JoshYates1980

Reputation: 3636

$(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();
    });
  })
});

Upvotes: 2

Nilesh
Nilesh

Reputation: 197

To retrieve all radio buttons values in JavaScript array use following jQuery code :

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();

Upvotes: 4

Ryan
Ryan

Reputation: 668

I've released a library to help with this. Pulls all possible input values, actually, but also includes which radio button was checked. You can check it out at https://github.com/mazondo/formalizedata

It'll give you a js object of the answers, so a form like:

<form>
<input type="radio" name"favorite-color" value="blue" checked> Blue
<input type="radio" name="favorite-color" value="red"> Red
</form>

will give you:

$("form").formalizeData()
{
  "favorite-color" : "blue"
}

Upvotes: 5

Patrick Roberts
Patrick Roberts

Reputation: 51946

From this question, I came up with an alternate way to access the currently selected input when you're within a click event for its respective label. The reason why is because the newly selected input isn't updated until after its label's click event.

TL;DR

$('label').click(function() {
  var selected = $('#' + $(this).attr('for')).val();

  ...
});

$(function() {
  // this outright does not work properly as explained above
  $('#reported label').click(function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="click event"]').html(query + ' at ' + time);
  });

  // this works, but fails to update when same label is clicked consecutively
  $('#reported input[name="filter"]').on('change', function() {
    var query = $('input[name="filter"]:checked').val();
    var time = (new Date()).toString();

    $('.query[data-method="change event"]').html(query + ' at ' + time);
  });

  // here is the solution I came up with
  $('#reported label').click(function() {
    var query = $('#' + $(this).attr('for')).val();
    var time = (new Date()).toString();

    $('.query[data-method="click event with this"]').html(query + ' at ' + time);
  });
});
input[name="filter"] {
  display: none;
}
#reported label {
  background-color: #ccc;
  padding: 5px;
  margin: 5px;
  border-radius: 5px;
  cursor: pointer;
}
.query {
  padding: 5px;
  margin: 5px;
}
.query:before {
  content: "on " attr(data-method)": ";
}
[data-method="click event"] {
  color: red;
}
[data-method="change event"] {
  color: #cc0;
}
[data-method="click event with this"] {
  color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="reported">
  <input type="radio" name="filter" id="question" value="questions" checked="checked">
  <label for="question">Questions</label>

  <input type="radio" name="filter" id="answer" value="answers">
  <label for="answer">Answers</label>

  <input type="radio" name="filter" id="comment" value="comments">
  <label for="comment">Comments</label>

  <input type="radio" name="filter" id="user" value="users">
  <label for="user">Users</label>

  <input type="radio" name="filter" id="company" value="companies">
  <label for="company">Companies</label>

  <div class="query" data-method="click event"></div>
  <div class="query" data-method="change event"></div>
  <div class="query" data-method="click event with this"></div>
</form>

Upvotes: 2

Alex V
Alex V

Reputation: 18306

Get all radios:

var radios = jQuery("input[type='radio']");

Filter to get the one thats checked

radios.filter(":checked")

Upvotes: 61

Manoj
Manoj

Reputation: 5071

This works fine

$('input[type="radio"][class="className"]:checked').val()

Working Demo

The :checked selector works for checkboxes, radio buttons, and select elements. For select elements only, use the :selected selector.

API for :checked Selector

Upvotes: 15

jeswin
jeswin

Reputation: 382

Use this:

value = $('input[name=button-name]:checked').val();

Upvotes: 11

Lafif Astahdziq
Lafif Astahdziq

Reputation: 3986

I use this simple script

$('input[name="myRadio"]').on('change', function() {
  var radioValue = $('input[name="myRadio"]:checked').val();        
  alert(radioValue); 
});

Upvotes: 12

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

(function ($) {

    function changeRadioButton(element, value) {
        var name = $(element).attr("name");
        $("[type=radio][name=" + name + "]:checked").removeAttr("checked");
        $("[type=radio][name=" + name + "][value=" + value + "]").attr("checked", "checked");
        $("[type=radio][name=" + name + "]:checked").change();
    }

    function getRadioButton(element) {
        var name = $(element).attr("name");
        return $("[type=radio][name=" + name + "]:checked").attr("value");
    }

    var originalVal = $.fn.val;
    $.fn.val = function(value) {

        //is it a radio button? treat it differently.
        if($(this).is("[type=radio]")) {

            if (typeof value != 'undefined') {

                //setter
                changeRadioButton(this, value);
                return $(this);

            } else {

                //getter
                return getRadioButton(this);

            }

        } else {

            //it wasn't a radio button - let's call the default val function.
            if (typeof value != 'undefined') {
                return originalVal.call(this, value);
            } else {
                return originalVal.call(this);
            }

        }
    };
})(jQuery);

Put the code anywhere to enable the addin. Then enjoy! It just overrides the default val function without breaking anything.

You can visit this jsFiddle to try it in action, and see how it works.

Fiddle

Upvotes: 17

Juan
Juan

Reputation: 1041

If you want just the boolean value, i.e. if it's checked or not try this:

$("#Myradio").is(":checked")

Upvotes: 81

Randy Greencorn
Randy Greencorn

Reputation: 3924

If you only have 1 set of radio buttons on 1 form, the jQuery code is as simple as this:

$( "input:checked" ).val()

Upvotes: 7

Rodrigo Dias
Rodrigo Dias

Reputation: 1340

To get the value of the selected radio that uses a class:

$('.class:checked').val()

Upvotes: 13

Related Questions