Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit.

My goal is to have the main button (Get Your New Rate) perform different actions based on whether the user selects YES or NO on the last of the 3 styled radio buttons.

Thank you for any assistance you can provide!

To view the current page layout, click here:

<div class="radioSelection">
    <input type="radio" id="radioLicenseYes" name="radioLicense"><label for="radioLicenseYes" class="radioYes">YES</label>
    <input type="radio" id="radioLicenseNo" name="radioLicense"><label for="radioLicenseNo" class="radioNo">NO</label>
</div>

<button class="getRate">Get Your New Rate</button>

<script type='text/javascript'>
function CheckLicense() {
    var licenseYes = document.getElementById("radioLicenseYes");
    var licenseNo = document.getElementById("radioLicenseNo");
    if(licenseYes.checked) {
        $(".getRate").click(function() {
            $("#questions").fadeOut(500);
            $("#loadingAnim").delay(500).fadeIn(1).delay(7000).fadeOut(500);
            $("#loading1").delay(500).fadeIn(500).delay(1500).fadeOut(500);
            $("#loading2").delay(3000).fadeIn(500).delay(1500).fadeOut(500);
            $("#loading3").delay(5500).fadeIn(500).delay(1500).fadeOut(500);
            $("#qualify").delay(8000).fadeIn(500);
            $("#redirecting").delay(8800).fadeIn(1);
            $("#loadingAnim2").delay(8800).fadeIn(1);
        });
    }
    else if(licenseNo.checked) {
        $(".getRate").click(function() {
            $("#questions").fadeOut(500);
            $("#noQualify").delay(500).fadeIn(500);
        });
    }
}

Answer №1

Check out this functional demo:

$(function() {

  $(".calculate").click(function() {

    var agree = document.getElementById("agreeYes");
    var disagree = document.getElementById("agreeNo");
    if (agree.checked) {

      console.log("agreed!");

    } else if (disagree.checked) {
      console.log("disagreed!");

    }
  });

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="agreeSection">
  <input type="radio" id="agreeYes" name="agreeChoice"><label for="agreeYes" class="yesLabel">AGREE</label>
  <input type="radio" id="agreeNo" name="agreeChoice"><label for="agreeNo" class="noLabel">DISAGREE</label>
</div>

<button class="calculate">Calculate Result</button>

By using jQuery, you can effortlessly trigger an event listener and execute conditional statements. One issue in your code is that you defined a JavaScript function but never invoked it! The jQuery snippet inside your function can handle the task effectively with some adjustments. You don't have to declare a named function like: function getBla(). jQuery performs that task automatically. I have simplified the code for illustrative purposes.

Answer №2

attempt:

function VerifyLicense() {        
    if ($('input[name=radioLicense]:checked').length !=0 ) {
       if ($('input[name="radioLicense"]:checked').val() == "YES"){

        $(".calculateRate").click(function() {
            $("#questions").fadeOut(500);
            $("#loadingAnim").delay(500).fadeIn(1).delay(7000).fadeOut(500);
            $("#loading1").delay(500).fadeIn(500).delay(1500).fadeOut(500);
            $("#loading2").delay(3000).fadeIn(500).delay(1500).fadeOut(500);
            $("#loading3").delay(5500).fadeIn(500).delay(1500).fadeOut(500);
            $("#qualify").delay(8000).fadeIn(500);
            $("#redirecting").delay(8800).fadeIn(1);
            $("#loadingAnim2").delay(8800).fadeIn(1);
        });
    } else {
        $(".calculateRate").click(function() {
            $("#questions").fadeOut(500);
            $("#noQualify").delay(500).fadeIn(500);
        });
      }
    }
}

$('.calculateRate').click(function() {
     VerifyLicense();
}

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 the World of React Variables

Recently, I've been diving into the world of React and encountered some challenges while styling my components. Personally, I find it more organized to style within the same JavaScript file instead of having a separate one. However, I'm curious a ...

Exploring the implementation of constructors and classes in JavaScript

I have a task to create a class named ShoppingCart with specific instructions: The class should have a constructor that initializes the total attribute to zero and creates an empty dictionary attribute called items. There should be a method named add_ite ...

Strange Behavior of HTML5 Audio Elements

I'm currently in the process of designing a shop website with a nostalgic Windows98 theme. On the product's page, I want to include a preview of audio. Here is the CSS code that I have used for the HTML5 audio element: audio::-webkit-media-contr ...

Population of the global namespace in JavaScript without the need for the 'new'

After watching the Douglas Crockford video on JavaScript, one thing that caught my attention was his explanation of what happens when you forget to use new for a class. He mentioned that doing so would populate the global namespace, which in the browser is ...

Server Error: Reactjs doesn't support posting images

I am experiencing an issue in my ReactJS project. When I attempt to upload an image using react-images-uploader, I encounter the following error: "Cannot POST /images error" Below is the code snippet for the image upload: <ImagesUploader ur ...

Creating a customizable date format feature in Spring MVC and jQuery

Exploring different methods to configure date formats for the application via a properties file. Considering implementing a conversion service in Spring along with a model serving as the date format property for jQuery datepicker. However, I encountered ...

Delete dynamic elements from an array once they are no longer present in the DOM

In this code snippet, I have implemented a button that adds a new object to both the document and an array. When you click on each object, it gets removed from the document. However, the challenge here is how can we also remove it from the array? You can ...

jQuery AJAX Concurrent Event

I have encountered a problem similar to ones discussed on SO, but none exactly match my specific issue. Here's the situation: var x = 5; if( some condition ){ $.ajax({ url:"...", success: function(response){ x = respo ...

Getting the chosen value from a dropdown menu on form submission using PHP

How to Populate a Combo Box from a Database in PHP? <td>Item Name:</td> <td><select name="items"> <option value="0" selected="selected"> Choose</option> <?php while($row = mysql_fetch_ass ...

Creating background color animations with Jquery hover

<div class="post_each"> <h1 class="post_title">Single Room Apartments</h1> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb" src="1.jpg"/> <img class="thumb last" ...

What is the best way to access the next-auth session using getStaticPaths and getStaticProps in dynamic routing scenarios?

I am currently working on implementing dynamic routing in a NextJS application. I need to retrieve the token from next-auth in order to make axios requests to an API and fetch data from getReport and getReports (located in /reports.js). However, I am facin ...

Chrome isn't showing the Background Image

I am currently working on coding a basic HTML/CSS page and I want to include a background-image within a div element that links to a URL. Interestingly, my code is functioning properly in Safari (Mac) and Firefox but unfortunately not showing the desired r ...

What causes <input> elements to vertically center when using the same technique for centering <span> elements? (The line-height of <input> does not match its parent's height)

Important: The height of <div> is set to 50px, and the line-height of <span> is also 50px When 'line-height' is not applied to the <span>, all elements align at the top of the parent. However, when 'line-height: 50px&apo ...

Storing Information in a File using Ajax POST and PHP

I'm having trouble saving JSON data (generated with JavaScript) in a file on the server. It seems even a simple string is not working: Here's my HTML File: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

ScriptManager is not accessible in the current ASP.Net Core Razor Page context

I'm facing an issue where I have a view (such as Index.cshtml) and a page model (like Index.cshtml.cs). In the view, there's a JavaScript function that I want to call from the OnPost() method in the page model. I tried using ScriptManager for thi ...

Executing a function within a worker thread in Node.js

This is the worker I am using: const Worker = require('worker_threads'); const worker = new Worker("function hello () { console.log('hello world');}", { eval: true }) worker.hello() // this is incorrect I want to invoke the hello() fu ...

When the if-else statement is executed, it showcases two strings:

Learning Experience: Unveiling My Lack of Cleverness Update: It appears that utilizing PHP in my current setup is not possible. As a result, I'll take some time to contemplate while banging my head against a wall. Despite that, thank you all for your ...

Customizing a material-ui theme with withStyles() in conjunction with withTheme()

After developing a series of reusable components, I started styling them by utilizing classes prop to override the MUI classnames. To streamline the process and prevent repetition in more intricate components, I consolidated common styles into a theme. Eac ...

Press the key to navigate to a different page

I have an input field for a search box. I want it so that when I enter my search query and press enter, the page navigates to another page with the value of the input included in the URL as a query string. How can I achieve this functionality? Thank you ...