JavaScript form validation problem: Warning for identical responses in the MOST and LEAST sections

I've encountered a challenge while working on an HTML and JavaScript form for a personality test. The issue revolves around validation, particularly when the form includes multiple questions with both "MOST" and "LEAST" radio button options.

One specific issue I'm facing is how to alert users if they select the same answer (either "MOST" or "LEAST") for a question.

Despite trying various solutions, I continue to run into problems in this area.

My goal is to notify users if they have chosen the same answer (either "MOST" or "LEAST") for a question.

An image of the HTML layout for one question can be found here: HTML Question

Here is the corresponding Javascript code:

`var DiscModule = (function() {
    var d, i, s, c, d2, i2, s2, c2;
    
    function getScores() {
        d = i = s = c = 0;
        var inputs = document.querySelectorAll('input[type="radio"]');
        for (var count = 0, l = inputs.length; count < l; count++) {
            if (inputs[count].checked) {
                switch (inputs[count].value) {
                    case "d-most": d++; break;
                    case "i-most": i++; break;
                    case "s-most": s++; break;
                    case "c-most": c++; break;
                    case "d-least": d--; break;
                    case "i-least": i--; break;
                    case "s-least": s--; break;
                    case "c-least": c--; break;
                }
            }
        }

        // checks if all questions are answered
        return (d !== 0 && i !== 0 && s !== 0 && c !== 0);
    }
        // calculations for the test
    function calculateWeightedScores() {
        if (d >= 6) d2 = 7;
        else if (d >= -1) d2 = 6;
        else if (d >= -5) d2 = 5;
        else if (d >= -9) d2 = 4;
        else if (d >= -13) d2 = 3;
        else if (d >= -16) d2 = 2;
        else d2 = 1;
        
        if (i >= 8) i2 = 7;
        else if (i >= 5) i2 = 6;
        else if (i >= 2) i2 = 5;
        else if (i >= -1) i2 = 4;
        else if (i >= -4) i2 = 3;
        else if (i >= -8) i2 = 2;
        else i2 = 1;
        
        if (s >= 12) s2 = 7;
        else if (s >= 8) s2 = 6;
        else if (s >= 5) s2 = 5;
        else if (s >= 1) s2 = 4;
        else if (s >= -2) s2 = 3;
        else if (s >= -7) s2 = 2;
        else s2 = 1;
        
        if (c >= 6) c2 = 7;
        else if (c >= 3) c2 = 6;
        else if (c >= -1) c2 = 5;
        else if (c >= -3) c2 = 4;
        else if (c >= -7) c2 = 3;
        else if (c >= -11) c2 = 2;
        else c2 = 1;
    }
    
    function createCharts() {
        var total = 7;
        
        document.querySelector("#d-chart").style.width = (d2 / total * 100) + "%";
        document.querySelector("#i-chart").style.width = (i2 / total * 100) + "%";
        document.querySelector("#s-chart").style.width = (s2 / total * 100) + "%";
        document.querySelector("#c-chart").style.width = (c2 / total * 100) + "%";
    }
    
    function showResults() {
        document.querySelector("#d-score").innerHTML = d2;
        document.querySelector("#i-score").innerHTML = i2;
        document.querySelector("#s-score").innerHTML = s2;
        document.querySelector("#c-score").innerHTML = c2;
        document.querySelector("#scroll-down").classList.remove("hidden");

    
    }
    return {
        processForm: function() {
            if (getScores()) {
                calculateWeightedScores();
                createCharts();
                showResults();
            } else {
                alert("Please answer all questions before calculating results.");
            }
        }
    };
})();

document.querySelector("#submit").onclick = function() {
    DiscModule.processForm();
};`

The following snippet shows the HTML code:

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Triven - DISC Test</title>
  <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css'>
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Lato:400,700'><link rel="stylesheet" href="./style.css">

</head>
<body>

<!-- Questions-->

<div class="container"><div class="row">
    <div class="page-header col-xs-12">
        <h1>test</h1>
    </div>
    <div id="scroll-down" class="hidden">
    </div>    
    <div class="q col-xs-12 col-sm-6 col-lg-3">
        <div class="row">
            <div class="col-xs-6">
                <span class="badge">1</span><br><br>
                Enthusiastic<br>
                Daring<br>
                Diplomatic<br>
                Satisfied
            </div>
            <div class="col-xs-3 text-center">
                MOST<br><br>
                <input type="radio" name="q1most" value="i-most"><br>
                <input type="radio" name="q1most" value="d-most"><br>
                <input type="radio" name="q1most" value="c-most"><br>
                <input type="radio" name="q1most" value="s-most">
            </div>
            <div class="col-xs-3 text-center">
                LEAST<br><br>
                <input type="radio" name="q1least" value="i-least"><br>
                <input type="radio" name="q1least" value="d-least"><br>
                <input type="radio" name="q1least" value="c-least"><br>
                <input type="radio" name="q1least" value="s-least">
            </div>
        </div>
    </div>

Answer №1

It appears that the provided solution meets your requirements – if the user selects both "Most" and "Least" for a specific option within a particular question (which may be challenging to test with only one question), an alert will warn the user.

This functionality is implemented by using a global variable within the scope of the `DiscModule` function, initialized as an object literal with entries represented as arrays. These arrays store the selected "Most" or "Least" values per question – selecting the same value twice denotes an invalid pairing by the user.

This implementation seems like it could benefit from some refinements in the future.

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 power of Angular JS and Ionic by parsing data from a JSON

I'm currently developing an App with the IONIC framework and Angular JS, utilizing the Tinder cards feature recently introduced by Ionic (http://ionicframework.com/blog/tinder-for-x/). My goal is to read from a JSON file and use it as storage for my a ...

Tips for achieving full width with Bootstrap

Recently, I delved into the world of bootstrap and encountered some trouble setting my width to 100%. Despite trying to assign width:100%; in my container CSS, it didn't seem to work. The only workaround I found was using container-fluid no-padding in ...

The issue with ngFileUpload causing empty file posts on Safari

Currently, I am utilizing ngFileUpload to transmit images to the Cloudinary service. My application is constructed on Ionic and is meant to be functional on both iOS and Android platforms. The code snippet below showcases my image uploading process: .se ...

How can I arrange a specific array position in Vuejs according to the Id value?

<div v-for="(item, index) in gr" :key="space.id" class="val-name"> </div> After making a few modifications to the API call logic, I was able to achieve my desired outcome. However, the issue lies in the fact that ...

How can I use jQuery UI to slide a div, while also smoothly moving the adjacent div to take its place?

Wishing you an amazing New Year! I am looking to create a smooth sliding effect for a div when a button is clicked. I want the adjacent div to slide alongside it seamlessly, without any clunky motions or delays. Currently, the adjacent div only moves afte ...

The getElementByID function will return null in this instance, as it has not been loaded

Hello everyone, I am facing an issue while trying to access an element by its ID in JavaScript as it keeps returning null. This problem arises because the element is not fully loaded when the DOM is initially created, due to a plugin called Restrict Conte ...

What methods exist for creating visual representations of data from a table without relying on plotting libraries?

Is there a way to plot graphs directly from a Data Table without the need for external graph libraries like plotly or highcharts? Ideally, I am looking for a solution similar to ag-grid where the functionality comes built-in without requiring manual code ...

Discovering the server endpoint for the Star Wars SWAPI API: a step-by-step guide

I have been working on integrating a search query into the server-side endpoint, which interacts with swapi - the Star Wars API https://swapi.co/ to display a list of people by their names. Below is the fetch call made to the backend in App.js file using ...

Using a JavaScript variable to be displayed in a PHP code

Can someone please help me troubleshoot this code? I am attempting to display a JavaScript variable in PHP after applying a regex, but I keep getting the error Uncaught TypeError: document.getElementById(...).html is not a function $.post('display.ph ...

Issues with Bootstrap 5 navbar-light and font style rendering on Edge browser

My website seems to be having compatibility issues with Microsoft Edge. While everything works fine on Chrome, the navbar classes "navbar-light" and "bg-light" do not apply properly in Edge, and the font style defaults. I am using Bootstrap 5 and webfonts ...

Creating a competition schedule - pieces don't quite mesh

Having trouble getting my tournament bracket visuals to come together smoothly! Here is the CSS code I have: #tournament-holder{ width:708px; padding:20px 0 20px 15px; float:left; } .vertical-holder{ width:100px; padding-right:15px; float:left; } .horizo ...

safely sending different form inputs in a Ruby on Rails form

Within this snippet, you'll find a part of a table with a form. Each row has its own submit button, which means users have to click on each one individually. I'm currently working on changing this so there is just one button for submission. < ...

Ensuring IconButton is perfectly aligned with Text in one straight line

I want to display IconButtons alongside plain text in a single block of text, but the result didn't turn out as I had hoped. Here is what I attempted: JS(ReactJS): <div> <span> <h3>Title</h3> <IconButton className ...

Generate a separate div element for each row within a table structure

I currently have a table within my HTML code. My goal is to generate a new div for each row in the table. Each div should contain a <p> element corresponding to the data in the first and second columns of each row. Is there a way to accomplish this ...

DOM doesn't reflect changes to nested object when component prop is updated

I have a complex object structured in a multidimensional way that appears as follows: obj: { 1: { 'a' => [ [] ], 'b' => [ [] ] }, 2: { 'x' => [ [], [] ] } } This object is located in the r ...

What is the best way to ensure that consecutive if blocks are executed in sequence?

I need to run two if blocks consecutively in TypeScript, with the second block depending on a flag set by the first block. The code below illustrates my scenario: export class Component { condition1: boolean; constructor(private confirmationServic ...

Tips for embedding HTML content onto a clipboard for easy pasting into Gmail

Our application generates two URLs that users often want to copy and paste into Gmail. To make these links more visually appealing than the lengthy URLs, we implemented HTML code. We included a feature that places the HTML on the Windows clipboard for easy ...

JavaScript Transforming an Array into an Object

After working with node and redis for a while, I've encountered an issue. When using hgetall in redis, it returns an object. { uid: '6203453597', first_name: 'Name', last_name: 'Surname', gender: 'male& ...

Preserve selected option in select box after page refresh in JSP

I'm working on a jsp page that contains a simple select html element. Right now, when I select an option and click the Wyswietl button, the page refreshes, the table data is refreshed, but the selected option resets to default... How can I make it sta ...

Are there any better methods for creating div backgrounds and borders using CSS?

Within my application, there exists a multitude of div elements that share identical backgrounds and borders but vary in size. Having to utilize the same background image for each individual div proves to be highly inefficient, particularly in terms of ba ...