Attempting to automatically change the selected input radio button every 3 seconds using HTML

Hey there, I'm just starting out with coding and StackOverflow. I'm attempting to create a basic slider but for some reason, the images are not changing. My goal is to cycle through checked input radio buttons every 3 seconds, but something seems to be off.

 <div class="slider">
        <div class="slides">
              
            <input type="radio" name="radio-btn" id="radio1">
            <input type="radio" name="radio-btn" id="radio2">
            <input type="radio" name="radio-btn" id="radio3">
           
            <div class="slide first">
                <img src="ad_1.jpg" alt="" >
            </div>
            <div class="slide">
                <img src="ad_2.jpg" alt="" >
            </div>
            <div class="slide">
                <img src="ad_3.jpg" alt="" >
            </div>

            <div class="navigation-auto">
                <div class="auto-btn1"></div>
                <div class="auto-btn2"></div>
                <div class="auto-btn3"></div>
            </div>
        </div>
    </div>

    <script>
        let count='1';
        count.toString();
        setInterval(function() {
            document.getElementById('radio'+count).checked = true;
            count++;
            if (count > 3) {
                count = '1';
            }
        },3000);
    </script>

Answer №1

JavaScript allows for implicit type coercion on the string count, converting it to a number when using count++. Despite this, your example functions as intended even without directly changing the type. To synchronize the images with each radio button, additional code will be necessary.

let count = 1;
setInterval(function() {
    document.getElementById('radio'+count).checked = true;
    count++;
    if (count > 3) {
        count = 1;
    }
},3000);
<div class="slider">
        <div class="slides">
              
            <input type="radio" name="radio-btn" id="radio1">
            <input type="radio" name="radio-btn" id="radio2">
            <input type="radio" name="radio-btn" id="radio3">
           
            <div class="slide first">
                <img src="ad_1.jpg" alt="" >
            </div>
            <div class="slide">
                <img src="ad_2.jpg" alt="" >
            </div>
            <div class="slide">
                <img src="ad_3jpg" alt="" >
            </div>

            <div class="navigation-auto">
                <div class="auto-btn1"></div>
                <div class="auto-btn2"></div>
                <div class="auto-btn3"></div>
            </div>
        </div>
    </div>

Answer №2

You may encounter an error when you declare `count` as a string ['1'] and then check conditions as if it's a number. It is recommended to declare it as a number, like this:

 let count = 1;

OR

 if ( parseInt(count) > 3 ) {
count = '1';
} 

 <div class="slider">
            <div class="slides">

                <input type="radio" name="radio-btn" id="radio1">
                <input type="radio" name="radio-btn" id="radio2">
                <input type="radio" name="radio-btn" id="radio3">

                <div class="slide first">
                    <img src="ad_1.jpg" alt="" >
                </div>
                <div class="slide">
                    <img src="ad_2.jpg" alt="" >
                </div>
                <div class="slide">
                    <img src="ad_3.jpg" alt="" >
                </div>

                <div class="navigation-auto">
                    <div class="auto-btn1"></div>
                    <div class="auto-btn2"></div>
                    <div class="auto-btn3"></div>
                </div>
            </div>
        </div>

        <script>
            let count='1';
            count.toString();
            setInterval(function() {
                document.getElementById('radio'+count).checked = true;
                count++;
                if ( parseInt(count) > 3) {
                    count = '1';
                }
            },3000);
        </script>

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

JEST: Troubleshooting why a test case within a function is not receiving input from the constructor

When writing test cases wrapped inside a class, I encountered an issue where the URL value was not being initialized due to dependencies in the beforeAll/beforeEach block. This resulted in the failure of the test case execution as the URL value was not acc ...

The DiscordAPIError occurred due to the incorrect placement of required options in the form body. In order to resolve this issue, ensure that required

Hey everyone! So, I've been trying to solve an issue I encountered after posting my initial question without receiving any answers. I've searched extensively online, formatted the code, but unfortunately, I still haven't been able to find a ...

Using Ajax to call a PHP function within a WordPress website

I am looking to trigger a PHP function using AJAX. Below is the code snippet of my form: <form class="woocommerce-form woocommerce-form-login login" method="post"> <p class="woocommerce-form-row woocommerce-form-row--wide form-row form-ro ...

Submitting Forms Using Jquery Lightbox Technology

I've encountered a problem with a form that allows users to enter information and submit it to a PHP script for database storage. However, not all of the data is being sent. Here is the code snippet: $(document).on("click", ".save_new_user", functio ...

Is there a way to perfectly align a left-aligned drawable with a hint in a TextInputEditText and position them closer to the bottom of the text input field?

Struggling to align the drawableLeft horizontally with the hint and bring them closer to the bottom of the TextInputEditText. I have experimented with various attributes but haven't been successful so far. Wondering if I might be overlooking something ...

Minifying Angular using grunt leads to 'Error initializing module' issue

Currently, I have multiple controllers, models, and services set up as individual files for preparation before minification. My goal is to combine and minify all these files into one JS file for production. To illustrate how my files are structured, here ...

A guide to adjusting the size of an iframe within a bootstrap modal

I am currently facing an issue where I am trying to display an iframe inside a bootstrap modal. The challenge is that the content within the iframe is dynamic, so the size may vary each time the modal is opened. As seen here, the modal appears too big and ...

What is the best method to eliminate a "0" entry from a javascript event array?

Hello, I've got an array structured as follows: let test = ["testOne:,O,U,0","testTwo:R,C,0","testTree:1.334","testFour:r,z"]; I'm looking to iterate through the array and remove any occurrences of the cha ...

Stop the hover state from being deactivated in Firefox's DevTools

My current issue is with the persistence of the hover state on an element when clicking on another element. Unfortunately, the Firefox DevTools seem to remove the hover state. Take a look at the following animated image: https://i.sstatic.net/DFE5H.gif H ...

Just starting to learn jquery and I'm struggling with this code, can someone help?

I am trying to move the .icon element to the right and animate it based on its position().left value. Unfortunately, my code is not working as expected and I can't figure out why. It seems like such a simple task! <script> $("li.menu-item").ho ...

Receiving NaN in javascript when attempting to calculate the sum using a text input field

I am trying to calculate the total value by adding a fixed price with another value entered in a text input field. Here is the HTML code snippet: <%= f.text_field :hoursclass, id:"txt_hours" %> And here is the JS code snippet: $(function() { va ...

I have noticed that the share buttons on Sharethis.com only show up after I resize the viewport

After integrating share buttons from Sharethis.com, I noticed that they do not appear when the page is refreshed. However, when I resize the viewport, they suddenly show up. <!DOCTYPE html> <html lang="en"> <head> <script t ...

Incorporating an external .htm file using javascript into a designated div element

I've been attempting to load an external .htm file into a div on my main page using the code below: <a href="#file.htm" onclick="$('#content').load('file.htm')">Link</a> While this works in Firefox, it doesn't se ...

Apply a new CSS class to supersede any current font styling

I am facing an issue with my HTML and CSS. The HTML code I have looks like this: <div id="main" class="ui-tabs ui-widget ui-widget-content ui-corner-all"> <div id="main-top"> <select id="entity" name="entity" class="monospace" > ...

What is the best way to use React to display all user post images on a webpage in real

I'm currently working on a React web application where I want to display images in all user posts on my Discover component. The JSON objects look like this: https://i.stack.imgur.com/ZM6Lu.png This is the current state of my discover component. Dis ...

What is the best approach to accumulate model data in an Angular JS service or controller through a series of consecutive calls?

I am facing a challenge where I need to display the results of multiple REST server calls on a single page using AngularJS. The initial call retrieves details about a specific product, including the IDs of other related products. My goal is to not only s ...

What causes the map function to behave differently when I use an array as the return value rather than a primitive in the callback function?

Program var corporations=[ {name:'Vicky',category:'Devdas',start:1993,end:2090}, {name:'Vikrant',category:'Devdas',start:1994,end:2019}, {name:'Akriti',category:'mental',start:1991,end:2021}, { ...

What is the process to showcase a database value in a particular index of an HTML table?

I am looking for assistance with displaying selected data values from a database into specific positions in an HTML table. I have managed to write the code that displays the data, but it only shows up at index 0 on the table. Does anyone know how to make ...

Vue JS: Toggling Checkbox Selections

I'm attempting to create a functionality where checking one checkbox will uncheck another, similar to how radio buttons work. I'm relatively new to Vue.js, so I may be missing something in my code. Here are the two input elements: <label for=& ...

Unable to access API due to CORS Policy issues in a Node.js application

I encountered a CORS policy error while attempting to link my React web application to my Node.js server due to different endpoints. To address this issue, I attempted to utilize CORS, a Node.js package that provides a Connect/Express middleware for enabl ...