Validation of Button Groups and Automatic Disabling after Initial Click with HTML, CSS, and JavaScript

Criteria:

  1. Upon clicking a button from the selection of four buttons, all other buttons should become disabled except for the Next button.
  2. An alert window must appear when the Next button is clicked without selecting any other buttons, preventing navigation to the next page and keeping the user on the current page.
  3. The transition to the next page is only allowed if one of the four buttons is selected first, followed by clicking the Next button.

Challenges faced with the provided codes:

  1. I cannot seem to adjust the alignment of the Next button to the right corner of the container.
  2. The alert window displays a message regardless of whether a button is chosen before clicking the Next button or not.
  3. After clicking the OK button in the alert window, it proceeds to the next page even without fulfilling the necessary conditions.

style.css

 h1
    {
        margin-top: 50px;
        text-align: center;
    }
    .container {
        margin: 50px;
      height: 200px;
      position: relative
    }
    .center {
      display: flex;
      justify-content: center;
      align-items: center;
      height: 300px;
      border: 3px solid green; 
    }

validation.js

function enable_disable()
{
    $("#formDisable :input").prop("disabled", true);
}
function optionValidation (element)
{
    if ((element.id != "optionA") && (element.id != "optionB") && (element.id != "optionC") && (element.id != "optionD"))
    {
        alert ("Please choose an option.");
    }
}

first_page.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>First</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script
    src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="validation.js"></script>
</head>
<body>
    <div class="container">
        <div class="center">
            <form id="formDisable">
                <div class="btn-group-vertical">
                    <button onclick="enable_disable()" type="button"
                        class="btn btn-primary" id="optionA">A</button>
                    <button onclick="enable_disable()" type="button"
                        class="btn btn-primary" id="optionB">B</button>
                    <button onclick="enable_disable()" type="button"
                        class="btn btn-primary" id="optionC">C</button>
                    <button onclick="enable_disable()" type="button"
                        class="btn btn-primary" id="optionD">D.</button>
                </div>
            </form> 
            <form action="second_page.html" method="post" onsubmit="optionValidation(this)">
            <button class="btn btn-primary" type="submit">Next</button>
            </form> 
        </div>
    </div>
</body>
</html>

second_page.html

<!DOCTYPE html>
<html lang="en">
<head>
<title>Second</title>
<meta charset="utf-8">
</head>
<body>
<h1>Welcome To Second Page</h1>
</body>
</html>

If anyone has any solutions to these issues, please share them!

Answer №1

Here is a step-by-step solution to address your issues:

  1. If you are facing an alignment problem with the "next button", you can resolve it using the following CSS code snippet. This code utilizes CSS-grid instead of flex for better alignment.

    h1 {
     margin-top: 50px;
     text-align: center;
    }
    .container {
     margin: 50px;
     height: 200px;
     position: relative;
    }
    /*--- Updated Code Starts Here ---*/
    .center {
     display: grid;
     grid-template-columns: 1fr 1fr;
     height: 300px;
     border: 3px solid green;
     }
    
    form {
      align-self: center;
      justify-self: end;
    }
    
  1. To disable all 4 buttons once one is clicked and implement the desired functionality, use the following JavaScript code:
document.addEventListener("DOMContentLoaded", () => {
  // Functionality 1
  let allBtnsDisabled = false;
  const btnGroup = document.querySelectorAll(".enable-disable");

  btnGroup.forEach((btn) => {
    btn.addEventListener("click", () => {
      console.log("Clicked Once");
      allBtnsDisabled = true;
      btnGroup.forEach((btnChild) => {
        btnChild.disabled = true;
      });
    });
  });

  // Functionality 2 and 3
  const formNext = document.querySelector(".form-next");
  formNext.addEventListener("submit", (e) => {
    e.preventDefault();

    if (allBtnsDisabled) {
      formNext.submit();
    }
    return;
  });

});
<html>
  <head>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="style.css" />
  </head>

  <body>
    <div class="container">
      <div class="center forms-wrapper">
        <form id="formDisable">
          <div class="btn-group-vertical">
            <button
              type="button"
              class="btn btn-primary enable-disable"
              id="optionA"
            >
              A
            </button>
            <button
              type="button"
              class="btn btn-primary enable-disable"
              id="optionB"
            >
              B
            </button>
            <button
              type="button"
              class="btn btn-primary enable-disable"
              id="optionC"
            >
              C
            </button>
            <button
              type="button"
              class="btn btn-primary enable-disable"
              id="optionD"
            >
              D.
            </button>
          </div>
        </form>
        <form action="second_page.html" method="get" class="form-next">
          <button class="btn btn-primary" type="submit">Next</button>
        </form>
      </div>
    </div>
  </body>

  <script src="./script.js"></script>
</html>

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

Is there a way I can invoke my function prior to the form being submitted?

For the last couple of days, I've been struggling to make this code function properly. My goal is to execute a function before submitting the form to verify if the class for each variable is consistent. You can access my code here. Any assistance you ...

Storing values from a content script into textboxes using a button press: a simple guide

I am new to creating chrome extensions and currently utilizing a content script to fetch values. However, I am facing difficulty in loading these values into the popup.html. Here is the code snippet: popup.html <head> <script src ...

Can Ajax and jQuery be utilized on a webpage in conjunction with a cron job?

These are the steps my page performs: Retrieve an array from a different server (first.php) Parse values using a PHP script Send parsed values using an AJAX call In the next page (second.php) that is called by AJAX, perform MySQL queries If values meet c ...

What is the most effective approach to integrating socket.io as a submodule into the ExpressJS framework?

In my current project, I am working on developing an application using ExpressJs and following the submodule architecture recommended by tjholowaychuk. Furthermore, I also want to incorporate real-time socket interactions into the app by integrating socke ...

Guide on adding a parent class to style all generated CSS rules in styled-components 5.3.5

When my application loads into a parent div with a specific class (for example, .my-app), is there a way to add the prefix .my-app to all classes generated by styled-components? For instance, consider a component like this: import React from 'react& ...

Modify the width measurement from pixels to percentage using JavaScript

Looking for some help with a content slider on my website at this link: . I want to make it responsive so that it adjusts to 100% width. I managed to make it responsive by tweaking some code in the developer tools, but now I'm stuck. The bottom two p ...

Adjusting or cropping strokes in a JavaScript canvas

I am working with a transparent canvas size 200x200. The object is being drawn line by line on this canvas using the solid stroke method (lineTo()). I'm in need of making this object full-width either before or after ctx.stroke();. ...

Sending data to a Bootstrap modal dialog box in an Angular application

Using span and ng-repeat, I have created tags that trigger a modal pop-up when the remove button is clicked. Within this modal, there is a delete button that calls a function. I am trying to figure out how to pass the id of the remove button to the modal ...

Ways to customize the appearance of CSS bootstrap 'col' elements?

I'm attempting to customize the styling of bootstrap CSS columns col-xl in order to display 5 or 6 cards/tiles on my webpage instead of just 4 (refer to attached image) without interfering with the other grid layouts. Unfortunately, I am currently str ...

What is the process for transferring selections between two select elements in aurelia?

I am attempting to transfer certain choices from select1 to select2 when a button is clicked. Below is my HTML code: <p> <select id="select1" size="10" style="width: 25%" multiple> <option value="purple">Purple</option> &l ...

Laravel has not been properly initialized

Recently, I've been exploring Laravel 5.3 and vue.js and I'm trying to make a GET request to fetch some user data from my database. I'm utilizing components in this project. Here is a snippet from my app.js file: require('./bootstrap ...

What is the best way to access HTML attributes within a JavaScript function when working with a dynamic element?

When a user interacts with an HTML element on my website, I aim to display the attributes of that specific element in a new browser tab. An example of such an HTML element is: <a id="d0e110" onclick="GetWordFile(this.id)" attr1="attr1_value" attr2="at ...

The rule "react/jsx-sort-props" does not have a valid configuration

I've been attempting to organize props names alphabetically using the eslint-plugin-react plugin but I keep encountering this error: [Error ] .eslintrc.json: Configuration for rule "react/jsx-sort-props" is invalid: Value {"callbacksLast":true,"shorth ...

Having trouble accessing the property 'top' of an undefined object in your Ruby on Rails project?

After thoroughly reviewing all the similar threads on SO regarding this error, none of them provided a solution that worked for me. Here is the flow of events: Go to the new Customer page, fill out the required fields, and click save Invoke a method in ...

Is it possible in AngularJS to use ui-router to redirect to a different state instead of

In my app.js, I am utilizing AngularJS along with ui-router. The code snippet below sets the default route: $urlRouterProvider.otherwise('/'); However, rather than redirecting to a URL, I need it to direct to a specific state: .state('404 ...

Executing a function by clicking on a DIV with the value of a textbox, instead of clicking directly on the textbox

Here is a function I have: $("#border-radius").click(function(){ var value = $("#border-radius").attr("value"); $("div.editable").click(function (e) { e.stopPropagation(); showUser(value, '2', this.id) $(this).css( ...

Having trouble getting Vue async components to function properly with Webpack's hot module replacement feature

Currently, I am attempting to asynchronously load a component. Surprisingly, it functions perfectly in the production build but encounters issues during development. During development, I utilize hot module replacement and encounter an error in the console ...

Using Bootstrap 3 with ResponsiveSlides.js

I've been struggling to center the ResponsiveSlides slider within a bootstrap column. Despite resizing my large images to 80% in the CSS, they still refuse to align properly since they're no longer fitting the entire screen at 100%. Can someone l ...

Having difficulty entering text into a "Search Input Field" that is a react component in testcafe

Struggling to input text in a "Type to search dropdown" that is a react component. While able to click on the component, typing any text seems to be an issue. Listed below is an example of the code: import { Selector } from 'testcafe'; test(&ap ...

Typescript Tooltip for eCharts

I'm working on customizing the tooltip in eChart v5.0.2 using Typescript, but I'm encountering an error related to the formatter that I can't seem to resolve. The error message regarding the function keyword is as follows: Type '(param ...