Utilizing JavaScript for selecting a radio button on click event

I have implemented a feature with four radio buttons to select a country. Upon clicking on any of the radio buttons, I utilize Ajax to retrieve the states corresponding to that specific country. To indicate to the end user that data processing is ongoing, a loading spinner image (gif) is displayed.

Upon clicking on a country radio button, within the loadStates() method (onclick event of radio), I make the loading spinner visible by setting its display property to 'inline'. Following this, an Ajax request is sent to the server (for demonstration purposes, I have replaced the actual code with a "sleep" function to show time delay). Once the results are obtained, the display property is reverted back to 'none'.

Unfortunately, this setup is not functioning as expected. Can anyone provide guidance on resolving this issue?

Note: At present, I prefer to use only JavaScript and not jQuery.

<html>
<head>
 <script type="text/javascript">

    window.onload = init;

    function init() {
       countryFunctions();
    }//init

    function countryFunctions() {
       var inputElems = document.forms[0].getElementsByTagName('input');
       for (var i = 0, j = inputElems.length; i < j; i++) {
          var elemName = inputElems[i].name;
          if ( typeof elemName != 'undefined' && elemName === 'country' ) {
             //inputElems[i].onmouseup = showRoller;
             inputElems[i].onclick = loadStates;
          }//if
       }//for
       return;
    }

   function loadStates() {
       var action = 'get_states';
       document.getElementById("fSpinner").style.display = "inline";
       //alert("hi........");
       var result = doLoad(action);
       document.getElementById("countryStates").innerHTML = result;
       document.getElementById("fSpinner").style.display = "none";
   }

   function doLoad(action) {//A dummy function just show what it returns (actually it is Ajax)
      sleep(7000);
      var value = "\
        <p>\
           Which state of the country would you like to go?\
        </p>\
        <select name=\"state\">\
            <option value=\"1362\">Delhi</option>\
            <option value=\"481\">Kerala</option>\
            <option value=\"666\">Punjab</option>\
            <option value=\"668\">Kashmir</option>\
       </select>";
      return(value);
   }

   function sleep(ms) {
      var unixtime_ms = new Date().getTime();
      while(new Date().getTime() < unixtime_ms + ms) {}
   }
 </script>
 <style type="text/css">
   #fSpinner { display:none; }
 </style>
</head>
<body>
  <form>
    <p>What country do you belong to?</p>
    <p>
       <input name="country" value="in" type="radio">&nbsp;India&nbsp;&nbsp;&nbsp;
       <input name="country" value="au" type="radio">&nbsp;Australia&nbsp;&nbsp;&nbsp;
       <input name="country" value="nz" type="radio">&nbsp;New Zealand&nbsp;&nbsp;&nbsp;
       <input name="country" value="my" type="radio">&nbsp;Malaysia&nbsp;&nbsp;&nbsp;
       <span id="fSpinner">
           <img style="vertical-align:text-bottom;" src="http://107.20.148.146/shak/images/roller.gif">
       </span>
    </p>
    <div id="countryStates"></div>
  </form>
</body>
</html>

Answer №1

When the sleep function is utilized, it essentially "blocks" the browser causing no page refresh until the function is completed.

If you want to replicate an asynchronous process, such as an AJAX call, it is recommended to use setTimeout instead:

 function fetchDetails() {
   var task = 'fetch_data';
   document.getElementById("loadingSpinner").style.display = "inline";

   setTimeout( function() {
     var content = "\
       <p>\
          What particular information are you looking for?\
       </p>\
       <select name=\"details\">\
           <option value=\"12\">Product Info</option>\
           <option value=\"34\">User Reviews</option>\
           <option value=\"56\">FAQs</option>\
           <option value=\"78\">Contact Us</option>\
      </select>";
      document.getElementById("displayInfo").innerHTML = content;
      document.getElementById("loadingSpinner").style.display = "none";
   }, 5000) ;
 }

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

Issue with Vue.js: document.querySelector is returning a null value even though the element clearly exists

I'm currently working on implementing a responsive navbar following Kevin Powell's tutorial, but I've run into an issue. For some reason, when I try to select the element with the class 'primary-navigation' using 'const primar ...

Updating the content of newly added elements using AJAX without refreshing the page

In the process of creating a real-time display of Twitter posts, I have managed to successfully fetch new tweets at regular intervals of 10 seconds. These new tweets instantly appear on the feed. However, I also want to continuously update the displayed t ...

What is the process for creating a linked TreeNode in the Ant tree design?

After completing a tree design utilizing Ant Design, I encountered an issue where certain nodes within the tree needed to act as links. Despite my attempts to directly assign links, they were not functioning properly. array.map((node) => { if(node.t ...

Creating a component in Vue to showcase Axios, based on a straightforward example from the documentation

I apologize in advance for what may seem like a trivial question, but I assure you that I have put in a considerable amount of effort to solve this problem without success. In my appService.js file, I am making an API call as follows: import axios from &a ...

Enhancing AJAX store in ExtJS with custom headers

Despite configuring the headers of my store, I keep encountering an error message like this: No 'Access-Control-Allow-Origin' header is present on the requested resource. Below is my proxy configuration for Ext.data.Store: proxy : { ...

Tips for guiding users to a different page based on whether a linkid is associated with a specific Cat

I created this script, but I am facing an issue with the redirect. Can someone please assist me as soon as possible? <?php include('config.php'); $number = intval($_POST['catid']); $query = mysql_query("SELECT * FROM sound ...

Bringing in Sequentially Arranged HTML Content using Asynchronous JavaScript Integration

I have a collection of separate HTML files with small content snippets that are loaded through AJAX and .get(). I want to display the content in an orderly fashion without relying on async: false in my AJAX call, as it is no longer recommended. With the si ...

Storing HTML elements in a database using jQuery's html() method

I have encountered a dilemma that has left me stumped after extensive online research. I have a dynamically generated webpage and need to save the entire appended body of the page to a database using PHP and MySQL. My current approach involves using the fo ...

What is the best way to execute tests in different environments with Protractor?

Is it possible to execute specifications in various environments? Maybe by adjusting the protractor-config file? Could we do something along the lines of specs: ['../tests/*.js', server1], ['../more_tests/*.js', server2] within the ...

Error encountered in jQuery's addClass and removeClass functions: Unable to read the property 'length' of an undefined value

Upon loading my page, I aim to have some of the div elements hidden initially and display only one. Here is a script that accomplishes this goal: <script> $(document).ready(function () { $(".total").click(function () { $("#pi ...

There is an issue with my HTML due to a MIME type error

I am currently facing an issue with my project. I have developed a node js server and now I want to display an HTML file that includes a Vue script loading data using another method written in a separate JS file. However, when I attempt to load the HTML f ...

What is the reason for the lack of arguments being passed to this Express middleware function?

I have been developing a middleware that requires the use of `bodyParser` to function, however I do not want to directly incorporate it as a dependency in my application. Instead, I aim to create a package that includes this requirement and exports a middl ...

Select a different radio button to overwrite the currently checked one

I am facing a situation where I have two radio buttons. The default checked state is one of them, but I want to change that and make the other one checked by default instead. Here is the HTML code: <div class="gui-radio"> <input type="radio" v ...

How do I set the initial state to a specific node in xstate?

I'm currently working on a multi-step form that guides users through selecting services, providing contact information, and entering billing details. I have implemented a progress bar and event emissions to track the user's current step using xst ...

Create a full-width slider using Materialize CSS framework

When using materializecss to create a slider, I encountered an issue where the image is full width but not full height, causing scrollbars to appear. What changes can I make to ensure the slider fills out my screen without any scrollbars? Additionally, I ...

Transferring PHP array data to JavaScript without being exposed in the source code

In the process of creating a historical database, I am currently handling over 2,000 photos that require categorization, out of which approximately 250 have already been uploaded. To efficiently store this data, I have set up a MySQL database with 26 field ...

ngPrime table column selection and data extraction

I am looking to extract multiple columns from a table. Can anyone suggest the best approach for this? Does NGPrime offer any functionality for achieving this task? Appreciate your help! ...

Unable to successfully reset the validity status to true

After implementing server-side validation using the OnBlur event in a form, I encountered an issue where setting the validity of a field to false does not remove the error messages even after setting it back to true. I expected $setValidity true to clear e ...

Automatic Full-Screen Switching Upon Video Playback in HTML5

Currently, I have a video clip set to play when the timer reaches a certain point. My goal is for the video to automatically enter full-screen mode when it starts playing and return to its original position when it stops, as the timer will continue ticking ...

Revise a catalog when an object initiates its own removal

When rendering a card in a parent component for each user post, all data is passed down through props. Although the delete axios call works fine, I find myself having to manually refresh the page for updates to be displayed. Is there a way to have the UI ...