Learn how to automatically set the checked state of a radio button by toggling another radio button

I have two sets of radio buttons, each with four options.

The first set has no default selection (unchecked) using jQuery, while the second set has the first option checked by default.

What I'm looking to achieve is that when a radio button in the first set is checked, it should automatically check the corresponding one in the second set.

Here's the HTML structure:

<p class="form-row form-row-wide validate-required" id="billing_piegadatajs_field"><label for="billing_piegadatajs" class="">Delivery Method <abbr class="required" title="required">*</abbr></label><br>

<input type="radio" name="billing_piegadatajs" value="Post Office" class="radio" style="width:10%" checked="checked"><span for="billing_piegadatajs">Post Office</span><br>
<input type="radio" name="billing_piegadatajs" value="Post24" class="radio" style="width:10%"><span for="billing_piegadatajs">Post 24</span><br>
<input type="radio" name="billing_piegadatajs" value="Courier Service" class="radio" style="width:10%"><span for="billing_piegadatajs">Courier Service</span><br>
<input type="radio" name="billing_piegadatajs" value="Pickup" class="radio" style="width:10%"><span for="billing_piegadatajs">Pickup (Location: Saldū)</span>
</p>

<br>        

<tr class="shipping">
<th>Shipping Costs</th>
<td>
    <ul id="shipping_method">
        <li>
            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_flat_rate" value="flat_rate" checked="checked" class="shipping_method">
            <label for="shipping_method_0_flat_rate">Post Office: <span class="amount">€&nbsp;3.50</span></label>
        </li>
        <li>
            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_international_delivery" value="international_delivery" class="shipping_method">
            <label for="shipping_method_0_international_delivery">Post 24: <span class="amount">€&nbsp;3.50</span></label>
        </li>
        <li>
            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_apg_shipping" value="apg_shipping" class="shipping_method">
            <label for="shipping_method_0_apg_shipping">DLW Courier: <span class="amount">€&nbsp;9.00</span></label>
        </li>
        <li>
            <input type="radio" name="shipping_method[0]" data-index="0" id="shipping_method_0_local_pickup" value="local_pickup" class="shipping_method">
            <label for="shipping_method_0_local_pickup">On-site Pickup - Saldū (Free)</label>
        </li>
   </ul>
</td>

</tr>

I am using this jQuery script to uncheck the radio buttons in the first set when the page loads:

jQuery(document).ready(function(){
jQuery('#billing_piegadatajs_field')
jQuery('#billing_piegadatajs_field').find('input[name="billing_piegadatajs"]').each(function() {
jQuery(this).prop('checked', false);
});
});

Here is a link to jsfiddle

Answer №1

There are numerous ways to accomplish this task.

One method involves utilizing two sets of radio buttons.

You currently have two sets:

The first set shares the class name 'radio.'

The second set shares the class name 'shipping_method.'

Here is the logic:

1) Add a click event to all radio buttons in the first set.

2) Determine the order rank of the clicked radio button.

3) Trigger a click event on the radio button in the second set with the same index.

// Track the click on the first set of radio
jQuery('.radio').on('click',function(){

    // Get the element index of the clicked radio button
    var indx = jQuery(this).index('.radio');

    // Trigger a click event on the radio button at the same index in the second set

    jQuery('.shipping_method')[indx].click();
})

Here is the link to the jsfiddle: http://jsfiddle.net/MMJRk/21/

Answer №2

To determine which checkbox is selected, start by identifying the checked box. This helpful link provides guidance on this in jQuery. Next, iterate through the remaining checkboxes, comparing their values to the desired value for each. Once you find the correct one, mark it as checked. Refer to this resource for information on how to check a checkbox using jQuery.

Answer №3

Although unconventional, this method gets the job done: http://jsfiddle.net/veritas87/MMJRk/25/

jQuery('p.form-row input[type=radio]').on('change', function () {
        var radioNumber = $(this).index('.radio');
        $("ul#shipping_method input[type=radio]:eq(" + radioNumber + ")").prop('checked', true);
    });

To simplify, when a radiobutton in p.form-row changes, it will select and check the corresponding radiobutton in the second list.

Answer №4

Your jsfiddle has been successfully updated and is now functioning correctly.

To make this work, I utilized custom data attributes (data-index) to assign an index to each input and its corresponding element. An event handler was then attached to the first set of inputs, which checks the relevant radio button in the second set based on the index of the selected input:

$('#billing_piegadatajs_field input[type="radio"]').on('change', function() {
   if (!this.checked) return;
   var index = this.getAttribute('data-index');
   $('#shipping_method input[data-index="' + index + '"]').prop('checked', true);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason for my failing express test?

I'm in the process of configuring a server using Node/Express and I want to write ES6 code, so I've incorporated babel into my setup. Currently, the server is operational, and I can successfully make the necessary requests. However, I am facing ...

Uploading and previewing multiple images on a canvas

After successfully creating single upload for images and placing them on canvas as seen in http://jsfiddle.net/StJnY/, I am now looking to adapt the script for multiple image uploads. Here is how I plan to modify the script: JS : $(function () { $(&a ...

Automated line wrapping within a div

My goal is to showcase images within a unique div structure. Currently, the arrangement appears as follows: It seems that the green divs are extending beyond their parent div (the black one). This is how it's structured: <div class="photoView c ...

Tips for ensuring a consistent highlight for an active link in Bootstrap

Does anyone have a solution for maintaining highlighted links on a web page? <div id="productnav"> <nav> <ul class="nav"> <li><a href="<?php echo $prefix; ?>pages/one.php?category=1" id="navelement1"<?php if ($c == 1) e ...

"Figuring out a way to include a link with each image in a react-s

I am currently working on a project in Gatsby and encountering some issues with the homepage banner. I am using react-slick which seems to be functioning fine, but when I try to add content on top of each image, it causes some problems. Specifically, setti ...

The announcement will not be made as a result of the utilization of a private name

I've been working on transitioning a project to TypeScript, and while most of the setup is done, I'm struggling with the final steps. My goal is to use this TypeScript project in a regular JavaScript project, so I understand that I need to genera ...

Sending a string via jQuery AJAX to an MVC controller results in a null parameter issue

I'm currently struggling with a straightforward AJAX call where I need to pass a search string value to a controller using POST method. $.ajax({ url: '/ResultsProcessing/AthleteLookup/n', type: 'POST', data: searchstrin ...

Centering all td elements except for those with a specific class

Consider the following code snippets: <tr> <td class="foo">chuchu</td> <td>chuchu</td> <td>chuchu</td> <td>chuchu</td> <td>chuchu</td> </tr> Is there a way to center align thes ...

Alter certain terms in HTML and update background using JavaScript

I want to create a filter that replaces inappropriate words and changes the background color using JavaScript. Here is what I have so far: $(document).ready(function () { $('body').html(function(i, v) { return v.replace(/bad/g, &apos ...

Tips for populating class attributes from an Angular model

Suppose there is a Class Vehicle with the following properties: public id: number; public modelId: number; public modelName: string; Now consider we have an object that looks like this {id: 1, modelId: 1, modelName: "4"} What is the best way to assign e ...

ExpressJS route handler encounters an error due to undefined 'this' reference

teamList.js class teamListCtrl { constructor() { this.data = "example"; } fetch(response, request) { console.log("DISPLAY ! ", JSON.stringify(this)); } } module.exports = new teamListCtrl(); //singleton router.js var express = require( ...

Discover the position of a chosen element using jQuery

Greetings! I am looking to retrieve the index of the column of a selected item in a table in order to create a color indicator in the header of the table. As the mouse moves, I want the header of the table containing the element to change color. Below is ...

Is it possible to update the content page without having to refresh the master page?

Our website features a Master page with main menu options and corresponding sub menus. When a user clicks on a main menu item, the relevant sub menus should be displayed. After clicking on a sub menu, the content page should update without having to refr ...

I am experiencing difficulties in accessing the DOM

I have implemented jQuery $.ajax to dynamically load data into table rows as shown below: <table id='row-data'> <tr><td>1001</td></tr> <tr><td>1322</td></tr> <tr><td>15 ...

Following the submission of the ajax form, the page is reloading unexpectedly

I need the voting form on index.php to submit without refreshing the page and display results from an external page within index.php. HTML <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script&g ...

Leveraging jquery to retrieve the value of a selected element

Why is this code not functioning properly? Here is the HTML snippet: <img src='picture.jpg'> <select name='blah[0]' onchange='changePicture();'> <option value='default.jpg'>Default</option> ...

Let's discuss how to include the scrollTop option

I am new to coding and I need help adding a scrollTop margin of +100px to my code. The page already has some top margin but I can't seem to locate it. I'm also having trouble finding where the margin-top is being set in the JavaScript file. /*** ...

The d3.js Time Scale Chart is facing issues when rendering with Array object values, unlike static values which render the chart perfectly

Generating an Array Dynamically with N objects from a JSON File var taskArray = []; d3.json("input.json", function(error, json) { if (error) return console.warn(error); for ( var i = 0; i < json.length; i++) { ...

Maintain position:relative while adding child elements to the div

I am currently working on creating a div that includes a small circle on the right side with an X inside it. Here is my progress so far: https://i.sstatic.net/3r2Nl.png Although the X is not yet placed inside the circle as intended, overall it looks good ...

What is the best way to replace a CSS Background that is already marked as important?

Attempting to change the background of a website using Stylish, but encountering issues. The existing background css on the website includes an !important rule which is preventing Stylish from taking effect. Here is my code: body { background-image: n ...