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

Using prevState in setState is not allowed by TypeScript

Currently, I am tackling the complexities of learning TypeScipt and have hit a roadblock where TS is preventing me from progressing further. To give some context, I have defined my interfaces as follows: export interface Test { id: number; date: Date; ...

What could be causing the issue with uglify not functioning properly with AngularJS content?

I've created some gulp tasks to assist in building my web project. One of the tasks involves minifying js files. Here is the task code snippet: gulp.task('minify' , function() { console.log('Copy minified js '); return gulp ...

“What is the process of setting a referenced object to null?”

Here is an example of the code I'm working with: ngOnInit{ let p1 : Person = {}; console.log(p1); //Object { } this.setNull<Person>(p1); console.log(p1); //Object { } } private setNull<T>(obj : T){ obj = null; } My objective is to ...

Show the id value of the event triggered by eventclick

I am currently attempting to retrieve the id of the event so that I can remove it from the database. My approach involves using eventClick, where a dialog pops up when the user clicks an event prompting them to remove it. In order to proceed with this oper ...

Experiencing issues with transferring JSON response from Axios to a data object causing errors

When I try to assign a JSON response to an empty data object to display search results, I encounter a typeerror: arr.slice is not a function error. However, if I directly add the JSON to the "schools" data object, the error does not occur. It seems like th ...

Using VueJS: Passing a variable with interpolation as a parameter

Is there a way to pass the index of the v-for loop as a parameter in my removeTask function? I'm looking for suggestions on how to achieve this. <ol class="list-group"> <li v-for="task in tasks" class="list-group-item"> ...

Having trouble retrieving returned data after refetching queries using Apollo and GraphQL

I am able to track my refetch collecting data in the network tab, but I am facing difficulty in retrieving and using that data. In the code snippet below where I am handling the refetch, I am expecting the data to be included in {(mutation, result, ...res ...

How can I use JavaScript to trigger a button click event inside an iframe element

Is there a way to retrieve the inner HTML contents of a clicked element in an iframe loaded content using JavaScript? This code uses jQuery: var elements = document.getElementsByTagName('iframe'); [].forEach.call(elements, function(elem ...

Automating testing with WebdriverIO in scenarios where JavaScript is turned off

Is it possible to launch the browser with JavaScript disabled in the WebdriverIO framework? I am looking to automate a scenario that requires JavaScript to be disabled. However, when I try to disable JavaScript manually in Chrome or Firefox and run WDIO s ...

Looking to place a global filter outside the primeNG table component?

I am currently utilizing primeNG in my project and I have a need to incorporate a global filter. The challenge I am facing is that I must add this filter in a different component. These two components are deeply nested within other components. My approach ...

What could be causing my Three.js code to fail during testing?

Recently, I decided to delve into the world of Three.js by following a thorough tutorial. While everything seemed perfectly fine in my code editor of choice (Visual Studio Code 2019), I encountered a frustrating issue when I attempted to run the code and n ...

Filter an array of objects based on a provided array

I have an array of objects that I need to filter based on their statuses. const data = [ { id:1, name:"data1", status: { open:1, closed:1, hold:0, block:1 } }, { id:2, name:"data2", ...

How do I dynamically incorporate Tinymce 4.x into a textarea?

I am encountering a small issue when trying to dynamically add tinymce to a textarea after initialization. tinymce.init({ selector: "textarea", theme: "modern", height: 100, plugins: [ "advlist autolink image lists charmap print p ...

Troubleshooting inactive CSS hover animation

Greetings! I'm facing an issue with a CSS hover animation. Here are two demos I've created: In the first DEMO, the animation works perfectly. However, in the second DEMO, it doesn't seem to be functioning. On the second demo, there are two ...

The AJAX request to fetch XML data resulted in a failure to redirect as intended

I'm encountering an issue with redirection after retrieving the XML data. The scenario involves a login process that fetches the ID values for username and password, verifies their existence, and then displays the alert "worked." However, despite show ...

Ways to retrieve information from a $$state object

Everytime I try to access $scope.packgs, it shows as a $$state object instead of the array of objects that I'm expecting. When I console log the response, it displays the correct data. What am I doing wrong? This is my controller: routerApp.controll ...

Can you help me convert this Mongoose code to use promises?

Using Mongoose's built-in promise support, I aim to streamline the process of a user sending a friend request to another user. However, even with careful error handling and sequencing in place, I find myself grappling with a slightly condensed pyramid ...

unable to call the anonymous inline onclick method of JavaScript

In my HTML file, I have the following code: <a onclick="getRestaurantTime({{ $afternoonTiming[$j]->id}});">Hello</a> Furthermore, I have an anonymous function in restaurant.js file: var Restaurant = (function ($) { function getRestaur ...

How to establish a session in CodeIgniter with the help of JavaScript

Currently, I am trying to save the session in jQuery. Specifically, I am attempting to store all the IDs that are checked via checkboxes in the export_type variable and then save them in the session. However, when running the following code snippet, I en ...

When the status is set to "Playing," the Discord Audio Player remains silent

So, I'm in the process of updating my Discord audio bot after Discord made changes to their bot API. Despite my best efforts, the bot is not producing any sound. Here's a snippet of the code that is causing trouble: const client = new Discord.Cl ...