Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar topics and tried various solutions, but none seem to work for me. To illustrate my use case, I have created a jsfiddle: http://jsfiddle.net/yZejX/2/.

Here is the HTML:

<input type="radio" name="test" id="radio-choice-1" value="3">Test1</input>
<br>
<input type="radio" name="test" id="radio-choice-2" value="4">Test2</input>
<br>
<input type="radio" name="test" id="radio-choice-3" value="5">Test3</input>

And here is the JS code I've tried:

// Attempting to set attribute directly
$("#radio-choice-1").attr('data-icon','radio-on');
$("#radio-choice-2").attr('data-icon','radio-off');
$("#radio-choice-3").attr('data-icon','radio-off');

// Trying to set via click event
$("#radio-choice-2").click();

// Attempting to set via changing attribute and calling change event to update
$("#radio-choice-2").attr('checked','checked').change();

// Trying to set via resetting checked element and changing attribute
$("input[name='test']:checked").removeAttr('checked');
$("input[name='test'][value='3']").attr('checked',true).change();
$("input[name='test'][value='3']").attr('checked','checked').change(); 

If anyone has any insights on what mistake I might be making or where the issue lies, I would greatly appreciate your feedback.

Thank you for your assistance.

Answer №2

Changing the status of a radio button can be accomplished in JavaScript by following these steps:


let radioButton = document.getElementById("radio-choice-1");
radioButton.checked = true;

Answer №3

To display it as checked, you can use the following code snippet:

document.getElementById('radio-choice-1').checked=true;

Alternatively, if you'd rather utilize jQuery:

$('#radio-choice-2').prop('checked', true);

Answer №4

Thank you so much for your prompt response and providing all the solutions. Each of them works perfectly. I managed to solve my issue by refreshing after changing the radio button selection:

Here is the HTML code snippet:

<input class="rbgroup1" type="radio" name="test" id="radio-choice-1" value="3" checked>Test1</input>
<br>
<input class="rbgroup1" type="radio" name="test" id="radio-choice-2" value="4">Test2</input>
<br>
<input class="rbgroup1" type="radio" name="test" id="radio-choice-3" value="5">Test3</input>

And here is the JavaScript part:

$(".rbgroup1").checkboxradio("refresh");

I'm glad to report that everything is working as expected now. It turns out simply changing the checked attribute wasn't sufficient in my case.

Wishing you a wonderful day ahead.

Best regards, Thomas

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

Ways of accessing an array within an if statement

I have a dashboard with admin privileges for my application. In this dashboard, the admin can select a user from a dropdown list. Once a user is selected, I make an AJAX call to retrieve the user's data and store it in a variable named $result. Howeve ...

Exploring the implementation of the meta robots tag within Joomla 2.5's global settings

Encountering a peculiar issue with Joomla 2.5 and the Meta robots tag. Joomla seems to have a flaw where regardless of the URL, as long as there is a valid article id, it will generate a page. For instance: The id '61' is valid but leads to a ...

Attempting to create a login and registration form

Hello, I am attempting to create a form that can generate new user accounts and passwords. These values should be stored from the input tag when the user clicks on the register button. Unfortunately, I am encountering an issue where clicking the register ...

What's the best way to align divs vertically in a compact layout?

Update The reason I require this specific behavior is to ensure that all my content remains in chronological order, both on the web page and in the HTML structure. This way, even if the layout collapses into a single column on smaller screens, the content ...

Conceal the menu when tapping anywhere else

I am working on a project that involves implementing HTML menus that can be shown or hidden when the user interacts with them. Specifically, I want these menus to hide not only when the user clicks on the header again but also when they click outside of th ...

Sending blank AJAX data to a PHP function

I am facing a challenge where I need to utilize AJAX to send the ID of an element and a specific value (1,2,3) to a PHP document for validation. Despite successfully logging both values in the console, the PHP file always returns that the data is empty. ...

What is the best way to implement a Cascading Async Select feature using @atlaskit/select library?

I recently delved into React and I'm currently exploring how to create a Cascading Async Select (for example, selecting Country then City) using @atlaskit/select. As per the documentation, I utilized the option loadOptions in the initial Async Select ...

ng-grid automatically resizing columns based on content width

I am currently utilizing AngularJS ng-grid and endeavoring to accomplish the following tasks: 1. Adjust column width dynamically based on the content within each column. 2. Automatically resize the last column to fill the remaining space when hiding column ...

concealing the date selection feature on the data picker

$('.year').datepicker({ changeMonth: true, changeYear: true, showButtonPanel: true, dateFormat: 'MM yy', onOpen: function(dateText, inst) { $("table.ui-datepicker-calendar").addClass('hide') }, onClos ...

Differences Between APP_INITIALIZER and platformBrowserDynamic with provide

I've discovered two different approaches for delaying an Angular bootstrap until a Promise or Observable is resolved. One method involves using APP_INITIALIZER: { provide: APP_INITIALIZER, useFactory: (configService: ConfigurationService) => ( ...

Issue with sync-request when using post data doesn't seem to be functioning

I am currently working on a Node.js application where I need to make synchronous requests. After some research, I came across the sync-request npm package for making these requests. However, when I tried using the code below, I encountered an error with th ...

How to iterate through an array of objects in Javascript and extract an array of strings

I am dealing with an array of objects that looks like this: [{"key":"aaa","value":true},{"key":"bbb","value":false},{"key":"ccc","value":true}] My goal is to iterate through it and extract an array containing only the keys: ["aaa", "bbb", "ccc"] I am u ...

Looking to retrieve the value of a selected checkbox within a horizontally laid out HTML table

Trying to extract values from a table with a horizontal header when checkboxes are selected. The goal is to retrieve the values of the selected column for all rows. Code snippet provided below. <script src="https://ajax.googleapis.com/ajax/libs/jquer ...

The overlappingmarkerspidifier is throwing an error because it is unable to access the property '__e3_' of an undefined variable

I am attempting to implement the overlapping marker spidifier feature in my code. I followed the instructions provided in this link: functioning code of oms However, upon creating the OverlappingMarkerSpiderfier object, I encounter the error: Uncaught Typ ...

How to handle an unexpected token error when using a function within another function in

I'm encountering an issue where the function below is placed above my render function. It doesn't seem to allow me to nest a function within another function. Can you help me identify what's causing this problem? onSelected(i){ this.st ...

What is the process for creating a three-dimensional Bezier curve using JavaScript, specifically with three.js and WebGL?

I have a good grasp on creating a simple bezier curve, but I am curious about how to transform the curve into 3D. Additionally, I am wondering if it is possible to plot multiple curves to form an image like a cone. Any advice or guidance on this matter wou ...

Adding an external JavaScript library file to a specific component in Angular 7 is a straightforward process. Let's walk through the

As a beginner in Angular framework, I've encountered an issue while working on creating a custom HTML template using Angular version 7. My template consists of various pages like home, about, product, etc. Specifically, on the home page, I am trying t ...

Display the date that is 3 days after the selected date from the Date Picker in the text field

This is the date picker code I am currently using: var d = new Date(); $(function () { $("#datepicker").datepicker({ minDate: d, dateFormat: 'mm-dd-yy' }); }); I want to enhance this functionality so that when a date is ...

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

Value in any array matches

I need help finding a match array within an input value: var values = new Array('stackoverflow', 'google', 'yahoo'); var userInput = $('#txtAddress').val(); if ($.inArray(userInput, values) != -1) { alert(&apos ...