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

Exploring Angular: How does Number.isNaN handle non-empty strings?

Within my component, there is a dropdown menu that allows users to choose a value. Upon selecting an item from the dropdown, a function called onDropdownChange is triggered. The parameter passed to this function can either be a string ("Please select an op ...

JSON only retrieve the corresponding data

I am looking to send a JSON object back to Postman without including a "title" like: { "name": { "name": "Three Rivers Campground", "lengthLimit": 25, "elevation": 6332, ...

Retrieve information from a deep array structure

How can I extract the `id` from each marker's `routes` array in this JavaScript object while still referencing `item.id`? { "markers": [ { "id": "77475", "smsCode": "77475", "name": "Abbey Sports Centre" ...

Encountering difficulties accessing functions from apollo-server-express

I have been following a tutorial and attempting to launch the node server, but I am unable to import these functions from the Apollo package const {graphqlExpress, graphiqlExpress} = require('apollo-server-express'); // importing functions here ...

Next.js React Hydration Issue - "Anticipated a corresponding <a> within the server HTML <a>"

Currently, I am encountering a hydration error while working on my Next.js project. The specific error message that keeps popping up is: Error: Hydration failed because the initial UI does not match what was rendered on the server. Warning: Expected serv ...

Get the XML element containing the desired value in the downloadURL

Seeking assistance from experienced individuals regarding XML usage. Admitting to my lack of knowledge in this area, I am a beginner and seeking patience. I have successfully implemented code that loads marker data from a MySQL database and displays it on ...

What is the best way to accomplish this using typescript/adonis?

While exploring some code examples on Bitbucket, I came across a sample that demonstrated how to paginate query results using JavaScript. However, as I attempted to apply it in my project, I encountered difficulties in declaring the types required for the ...

The issue with the NextJS Layout component is that it is failing to display the page content, with an error message indicating that objects cannot be used

I am embarking on my first project using Next JS and after watching several tutorial videos, I find the Layout component to be a perfect fit for my project! However, I am encountering an issue where the page content does not display. The Menu and Footer a ...

Nuxt - issue with updating window innerwidth getter

The class based components in our project utilize a getter to retrieve the window innerWidth. However, I've noticed that the value is only set once and doesn't update if the window width changes. get viewPortWidth() { if (process.client) { ...

Odd Behavior when altering button attribute using Jquery

After disabling a button with a click handler, I have noticed an interesting behavior where the button does not submit afterwards. The issue seems to vary between different browsers, with Firefox still allowing form submission after the button is disabled, ...

What is the best way to bring in the original files of a JavaScript library?

Currently I am utilizing a library called selection.js. Within my application, I am importing from node_modules with the following code: import * as Selection from '@simonwep/selection-js' However, what I am interested in doing is modifying the ...

Getting the jQuery selector result into the routevalues object for @Ajax.ActionLink: How can it be done?

Here is the code for an @Ajax.ActionLink I am working with: @Ajax.ActionLink("Assign Ownership", "AssignOwnership", new { techLogCode = Model.TechLog.Code, salesRepId ...

I am currently working on a website that offers different themes, and I am attempting to update the iframe to reflect the selected theme on the site

I'm feeling lost on how to accomplish this task. Despite my efforts, I have been unable to find a solution so far. Perhaps utilizing javascript might be the key here, yet I am uncertain about integrating it into the existing script that I use for modi ...

What is the reason behind AngularJS throwing an error related to bad augmentation?

Whenever I try to update the src link in my Angular code from version 1.2.2 to 1.5.0, I encounter an error. The code works perfectly fine with 1.2.2, but switching to 1.5.0 throws an error. I want to upgrade it to 1.5.0, so what changes do I need to make ...

Sorting feature fails to function properly when used in combination with pagination and

<table> <thead> <tr> <th class="col-md-3" ng-click="sortDirection = !sortDirection">Creation Date</th> </tr> </thead> <tbody> <tr dir-paginate="item in items | filter:itemFilter | items ...

Persuading on the Server-Side

After reading through the Google-Caja wiki, I became intrigued by its capabilities. From what I understand, with Caja we can send a snippet of HTML (such as a ) to Google-Caja's server (cajoling service) for processing. The HTML is cajoled and the Jav ...

phpmailer triggering CORS error on web servers

As a beginner mobile developer, I am utilizing phonegap as my framework and firebug for debugging purposes. The error message I encountered in firebug is: Cross-Origin Request Blocked: The Same Origin Policy disallows..... I suspect that the issue may ...

`Optimizing Django by using multiple room relationships to save formset related models`

I need help with saving a formset that involves two models in a many-to-many relationship. When I open the page, two forms are displayed but after filling them out and clicking "Add", the fields for "phone" and "client_name" get cleared and the form is not ...

What is the best way to navigate through an HTML node tree, including all of its sub elements, when walking through

Do you know of a way to iterate through the entire hierarchy of HTML elements and check each one for attributes and more without using JavaScript? We currently have a JavaScript solution that iterates through each child element and all their descendants. ...

What is the most effective way to loop and render elements within JSX?

Trying to achieve this functionality: import React from 'react'; export default class HelloWorld extends React.Component { public render(): JSX.Element { let elements = {"0": "aaaaa"}; return ( ...