Validation with Javascript can trigger the display of a hidden element

Hello there, I could really use some assistance with the JavaScript part of this code. I have two JavaScript functions: one for validating if a radio checkbox is selected, and another for revealing the "answer". Currently, an alert pops up if no selections are made (which is good), but then the answer remains unrevealed regardless of the selection.

My ideal scenario would be for the "answer" to only be revealed if at least one checkbox is selected; otherwise, if nothing is selected, an alert should be triggered on the page.

Below are the two JavaScript functions:

<script>
document.getElementById("answer").style.display ="none";
function validateForm() {
    var choices = document.getElementsByName("Question");
    for(var i = 0; i < choices.length; i++) {
        if(!(choices[i].checked)){
            alert("Please select an answer choice");
            return false;
        }
    }
}

function openTest() {
        document.getElementById("answer").style.display = "block";
}
document.getElementById('button').addEventListener('click', openTest);
</script>

...

Answer №1

I reviewed your code and implemented some changes in the JavaScript section:

  • Added return false at the end of the function to prevent errors when called on the form submit event.
  • Modified the for loop condition by replacing '3' with choices.length to ensure it loops through all checkboxes (4 times).
  • Removed the openTest function and moved its functionality inside the validateForm function.
  • Introduced a new flag named noAnswerSelectedFlag to correctly detect if an answer is selected or not. The previous logic was flawed, as it always showed an alert even if any answer was unchecked. This flag now determines whether an answer is selected; if not, it displays the correct answer, otherwise, it shows an alert message.
document.getElementById("answer").style.display = "none";
function validateForm() {
    var choice = document.getElementsByName("Question");
    var noAnswerSelectedFlag = false;
    
    for(var i = 0; i < choice.length; i++) {
        if (!(choice[i].checked)) {
            noAnswerSelectedFlag = true;
        } else {
            noAnswerSelectedFlag = false;
            break;
        }
    }

    if (!noAnswerSelectedFlag) {
        document.getElementById("answer").style.display = "block";
    } else {
        alert("Please select an answer.");
    }

    return false;
}

Below is the updated working code snippet:

document.getElementById("answer").style.display = "none";
function validateForm() {
    var choice = document.getElementsByName("Question");
    var noAnswerSelectedFlag = false;
    
    for(var i = 0; i < choice.length; i++) {
        if (!(choice[i].checked)) {
            noAnswerSelectedFlag = true;
        } else {
            noAnswerSelectedFlag = false;
            break;
        }
    }

    if (!noAnswerSelectedFlag) {
        document.getElementById("answer").style.display = "block";
    } else {
        alert("Please select an answer.");
    }

    return false;
}
#test {
    width: 100px;
    height: 50px;
    background-color: lightblue;
}
<h1>Poll Question</h1><br>

<table>
    <form onsubmit="return validateForm()">
        {% for questions in question_list %}
        <tr>
            <th> {{ questions[2] }} </th>
        </tr>
        <tr>
            <td> <input type="radio" id="UserResponse1" name="Question" value="question1">
                <label for="UserResponse1">{{ questions[3] }}</label><br> </td>
        </tr>
        <tr>
            <td>   <input type="radio" id="UserResponse2" name="Question" value="question2">
                <label for="UserResponse2">{{ questions[4] }}</label><br></td>
        </tr>
        <tr>
            <td>  <input type="radio" id="UserResponse3" name="Question" value="question3">
                <label for="UserResponse3">{{ questions[5]}}</label><br> </td>
        </tr>
        <tr>
            <td>   <input type="radio" id="UserResponse4" name="Question" value="question4">
                <label for="UserResponse4">{{ questions[6] }}</label><br> </td>
        </tr>
        <tr>
            <td>
                <br><button id="button">see answer </button>

                <div id="answer">The correct answer is: {{ questions[7] }}</div>
            </td>
        </tr>
    </form>
    {% endfor %}
</table><br><br>

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

Problems encountered with operating the Bootstrap burger menu

After following the Bootstrap navbar documentation and implementing the code in my bs-navbar.component.html file, I encountered an issue with the hamburger menu. Despite everything being set up correctly, clicking on the hamburger icon did not display the ...

Tips for Controlling an Absent Search Bar in the HTML Source Code with Selenium

I'm attempting to automate searches using Selenium in Java. Upon inspecting the search bar on the page, I noticed that it has an id of searchBox and a name of q, which could be helpful. However, these properties are not visible in the HTML when viewi ...

What is the reason behind the Chrome icon flickering momentarily while loading certain web pages?

I recently put together a basic html document, here it is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8> <title>Just a test.</title> </head> <body> <svg ...

An effective approach to automatically close an Expansion Panel in an Angular Mat when another one is opened

I am attempting to implement functionality where one expansion panel closes when another is opened. By default, the multi attribute is set to "false" and it works perfectly when using multiple expansion panels within an accordion. However, in this case, I ...

Guide on setting up a Redirect URL with React Router

I am aiming to trigger a redirect URL event using ReactJS. Is there a way to achieve this? I have already attempted the following: successRedirect(){ this.transitionTo('/'); } as well as successRedirect(){ this.router.transitionTo ...

An error of type TypeError has been encountered due to an invalid argument type. This occurred in the file located at {mypath}Desktop eddit ode_modules@redisclientdistlibclientRESP2encoder.js on line

Currently, I am diving into Ben's TypeScript GraphQL Redis tutorial for the first time. As a newcomer to TypeScript, I decided to give Redis a shot. However, when I added the property req.session.userId= user.id;, things took a turn. An error popped ...

Executing a function from another reducer using React and redux

My application consists of two main components: the Market and the Status. The Status component manages the user's money, while the Market component contains buttons for purchasing items. My goal is to decrement the user's money when a button in ...

Organize elements with precision using html and css properties

I am struggling to get the buttons on the card to align properly. I have set a minimum height to ensure they are consistent in size regardless of content, but the alignment of the buttons is off. Take a look at the photo attached for reference - I want the ...

Are extra parameters in the URL causing issues with AngularJS routing?

When I receive password reset instructions in my app, the URL I use to go to the server looks like this: /changepass?key=1231231231212312 In the controller, I have the following code: if (typeof $routeParams.key !== 'undefined') { $scope ...

Using AJAX in PHP to submit checkbox values in a form without reloading the page

Recently, I delved into learning ajax and found it to be truly amazing and a major time-saver. However, I encountered a roadblock when attempting to send form data without having the page reload. Here is an excerpt of my HTML code. <form id="form ...

Can you show me the method to retrieve the value of client.query in Node JS using PG?

I have been working with node.js to establish a database connection with postgresql. Here is what my dbConfig.js file looks like: var pg = require('pg'); var client = new pg.Client({ host:'myhoost', port:'5432', ...

Filter Observable based on object array property

I am trying to filter an Observable and only keep the stream that has a specific property value in an array of objects inside it. For example, consider this Observable: const observable = of({name: 'agency', year: '2010', job: [ ...

What could be the reason for the modal-side modal-top-right class not functioning properly in Bootstrap modals

Here is the code snippet: <div class="modal fade right" id="basicModal" tabindex="-1" role="dialog" aria-labelledby="basicModal" aria-hidden="true"> <div class="modal-dialog modal-side modal-bottom-right"> <div class="modal-content"&g ...

Effortlessly update value changes in ReactJs when Checkbox is checked

I've been stuck on this issue for a whole day now. I'm trying to make it so when the checkbox is checked, the value of 'Done' changes as intended. I've tried using useState but it's not working. The approach I used below is mu ...

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

What causes my Excel file to become corrupted when inputting new data?

My intention with this code is to insert "ABC" into cell B3 of an existing Excel document. However, when the file is written, its size decreases significantly and Excel is unable to open it. const excel = require("exceljs"); const template = "./myexcel.xl ...

Tips for utilizing a .node file efficiently

While attempting to install node_mouse, I noticed that in my node modules folder there was a .node file extension instead of the usual .js file. How can I execute node_mouse with this file format? After some research, it seems like node_mouse may be an a ...

Issue with the loop function

When I try to loop through my code, I keep getting the same "y" value (5) and it doesn't change. What I actually want is to make the ajax call repeat X times [all], passing both the response and the current call number through an anonymous function. A ...

An easy way to activate a toggle function when the page loads in React

I want to create a nice slide-in effect for my sidebar when the user loads the page. My goal is to toggle the state of the Sidebar component from open: false to open: true on load in order to achieve this effect. Unfortunately, it seems that the way I&apo ...

PHP disregards the starting 202

Currently, I am developing a PHP API Client to interact with an ASP.net (C#) API. By employing the following Javascript function, I am successfully able to retrieve the data: $.ajax({ type: "POST", url: "https://www.eastmidlandstrains.co.uk/s ...