Page Content

Tutorials

Understanding the :Radio Selector in jQuery With Example

:Radio Selector in jQuery

To effectively target and control radio button input components within web forms, jQuery’s :radio selector is a useful tool. It is classified as a filter for form elements.

What is the selector?

With the :radio selector, all HTML elements with the type property set to “radio” are precisely identified and selected. This indicates that it offers a simple method of accessing every radio button in your HTML document for a variety of purposes, including determining their values, monitoring their status, and adding event handlers to them.

Syntax:

Using the :radio selector, like all jQuery selectors, requires the jQuery factory function ($()) and the dollar symbol and brackets ($).

Here is the syntax:

$(":radio")

This expression returns a jQuery object with all matching radio button elements in the Document Object Model (DOM). When many elements are selected, a value array is created. The.length attribute shows how many radio buttons were selected.

How it Works

An efficient and succinct JavaScript framework, jQuery was created to make basic web development tasks like event handling, HTML page traversal, animation, and Ajax interactions easier. One organisational principle is “Write less, do more”. By providing a high-level abstraction layer, it simplifies sophisticated JavaScript programming, specifically browser variant management, which is difficult and time-consuming in plain JavaScript.

The precise components from the DOM that meet the given criteria are retrieved by jQuery using its effective selector technique when you use a selector like :radio. The syntax of $(selector).action() is essential to jQuery, where the action() is the action to be carried out on HTML elements and the (selector) part is used to “query (or find)” those elements.

The underlying method for :radio effectively searches the DOM for tags and filters them according to the type property “radio.” The process is simpler than writing verbose, browser-specific JavaScript code.

Before using jQuery for events or DOM updates, ensure sure the page loads and the DOM is formed. Adding jQuery to $(document).ready() typically does this. By only running your script when the HTML document is ready, you can avoid accessing unrenderable components. It is more reliable than traditional windows.onload event handler, which may not work in all browsers.

After using :radio to pick the items, you may use a variety of jQuery functions on them. As an illustration:

  • Use.val() to retrieve or modify the value of the specified radio button or buttons.
  • Radio buttons’ checked properties can be obtained or set using the.prop() function.
  • To add event handlers, like a change or click event, that react to user interactions with the radio buttons, use the.on() or.click() functions.

Code Example

To showcase jQuery’s :radio selector, let’s look at a simple HTML form with numerous radio buttons.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>:radio Selector Example</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <style>
    body { font-family: Arial, sans-serif; margin: 20px; }
    #output { margin-top: 20px; font-weight: bold; color: #333; }
    label { margin-right: 15px; }
  </style>
</head>
<body>
  <h1>Choose Your Favorite Color</h1>
  <form id="colorSelectionForm">
    <fieldset>
      <legend>Select a Color:</legend>
      <input type="radio" name="favorite-color" id="radio-red" value="Red">
      <label for="radio-red">Red</label>
      <input type="radio" name="favorite-color" id="radio-blue" value="Blue" checked>
      <label for="radio-blue">Blue</label>
      <input type="radio" name="favorite-color" id="radio-green" value="Green">
      <label for="radio-green">Green</label>
    </fieldset>
  </form>
  <div id="output">Selected color: <span id="selectedColor">Blue</span></div>
  <script>
    $(document).ready(function() {
      // When any radio button is changed
      $('input:radio[name="favorite-color"]').change(function() {
        const selectedColor = $('input:radio[name="favorite-color"]:checked').val();
        $('#selectedColor').text(selectedColor);
      });
    });
  </script>
</body>
</html>

Output:

Choose Your Favorite Color

Select a Color:
 Red   Blue   Green
Selected color: Red

Explanation of the Code Example

$(document).ready(function() { … });: This basic jQuery approach makes sure that before any JavaScript code tries to interact with any DOM elements, they are all loaded and prepared. This strengthens your code and guards against possible mistakes.

var allRadioButtons = $(“:radio”);: var allRadioButtons All input type=”radio”> components in the HTML document are selected by this line using the :radio selector. The allRadioButtons jQuery object is where the outcome is kept.

numberOfRadios = allRadioButtons.length;: The selector then retrieves the total number of radio buttons it discovered using the.length attribute. The output div on the page has this attached to it.

var checkedRadioButton = $(“input:radio:checked”);: radio selector is coupled with the :checked filter. You may precisely choose only the radio button that is now selected (checked) inside its group with this potent combo. To obtain the value of this selected radio button (for example, “blue” in the initial state), the.val() method is then utilised.

$(“:radio”).on(‘change’, function() { … });: All radio buttons selected by :radio can have an event handler attached to them, as shown in this line. Commonly used for form elements like as radio buttons, the change event is triggered when the user chooses an alternative. Within the function, $(this) denotes the particular radio button that set off the event, along with its.Using val(), the newly chosen value is obtained and shown in the output div.

$(“#radio-green”).prop(“checked”, true).trigger(“change”);: This section demonstrates programmatic interaction. The radio button with id=”radio-green” is selected directly, checked programmatically using.prop(“checked”, true), and the change event is manually triggered using.trigger(“change”), making sure that any event handlers that are attached—like the one mentioned above—are run.

Conclusion

In conclusion, the :radio selector makes it much easier to recognise and work with radio buttons, which enables developers to create code for dynamic web interfaces that is clearer, shorter, and compatible with multiple browsers.

Kowsalya
Kowsalya
Hi, I'm Kowsalya a B.Com graduate and currently working as an Author at Govindhtech Solutions. I'm deeply passionate about publishing the latest tech news and tutorials that bringing insightful updates to readers. I enjoy creating step-by-step guides and making complex topics easier to understand for everyone.
Index