jQuery Radio Button processing Example

To select a radio button in jQuery you have to use the selector $(':radio') or $('[type=radio]'). Because :radio is a jQuery extension and not part of the CSS specification, queries using :radio will be slower than [type="radio"] in modern browsers.

In this example we will learn the following
  • Find the Selected Radio Button and its Value
  • Reset the Radio Button Selection
  • Dynamically select a Radio Button by Relative Index Number
  • Dynamically select a Radio Button by the Value
jQuery Radio Button processing Example
jQuery Radio Button Check Selection

Source Code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="robots" content="noindex,nofollow" />
<title>jQuery Radio Button Example</title>
<link rel="stylesheet" href="/resources/themes/master.css" type="text/css" />
 DIV {
  margin-bottom: 10px;
 rel="stylesheet" type="text/css" />
<script src="/resources/scripts/mysamplecode.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function() {

  var $mySelection = $("input[name='yourCar'][type='radio']:checked");
  if($mySelection.length > 0){
   alert("You have selected: " + $mySelection.val()); 
  else {
   alert("Please select the car you Drive"); 
  //same result you can choose to use either one
  $("input[name='yourCar']:radio")[4].checked = true;
  var $radioButtons = $("input[name='yourCar']:radio");
  var $radioButtons = $("input[name='yourCar']:radio");
  $radioButtons.each(function() {
   if($(this).val() === "Lexus"){
    return false;
 <div id="allContent">
  <div id="myContent">
   <form id="samplecode" name="samplecode" method="POST" action="">
      <legend><b>&nbsp;&nbsp;&nbsp;Radio Button Processing&nbsp;&nbsp;&nbsp;</b></legend>
        <b>Select the Car you Drive ...</b>
       <input type="radio" name="yourCar" value="GMC" /> GMC
       <input type="radio" name="yourCar" value="Honda" /> Honda
       <input type="radio" name="yourCar" value="Hyundai" /> Hyundai
       <input type="radio" name="yourCar" value="Lexus" /> Lexus
       <input type="radio" name="yourCar" value="BMW" /> BMW
       <input type="radio" name="yourCar" value="Other" /> Other
       <input id="checkNow" type="button" value="Check Selected Car" />
       <input id="byIndex" type="button" value="Select BMW by Index" />
       <input id="reset" type="button" value="Reset any Selection" />
       <input id="byValue" type="button" value="Select Lexus by Value" />


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.