Can someone assist me in figuring out how to solve selecting multiple radio buttons at once

<script type="text/javascript">

let x = "1.html";
let y = "2.html";

function redirectPage(form){
   for(let i=0; i<form.length; i++) {
      if(form.answerq[i].checked && form.answerw[i].checked && form.answere[i].checked) {
         if (form.answerq[i].value == 'a' && form.answerw[i].value == 'a' && form.answere[i].value == 'a') {
            window.location = x;
         } else {
            window.location = y;
         }
      }
   }    
}
</script>
<form method="post" action="#">
    
*ARE YOU 18+ YEARS OLD?
<label><input type="radio" name="answerq" value="a"> Yes</label>
<label><input type="radio" name="answerq" value="b"> No</label>

*ARE YOU A U.S CITIZEN?
<label><input type="radio" name="answerw" value="a"> Yes</label>
<label><input type="radio" name="answerw" value="b"> No</label>

*ARE YOU MARRIED? 
<label><input type="radio" name="answere" value="a"> Yes</label>
<label><input type="radio" name="answere" value="b"> No</label>

<button type="button" class="btn btn-primary" value="Submit" onclick="redirectPage(this.form)">Submit!</button>

<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

 </form>

Selecting yes,yes,yes or no,no,no is working perfectly fine and redirect to the correct link. However, when selecting yes,yes,no, no,yes,no or yes,no,yes doesn't work after clicking the submit button.

And one more thing anyone here can help me put a validation if they do not select a radio button like an alert of prompt?

Answer №1

the method to achieve this is by using the required and name attributes within your <form

ensuring that the user selects a radio button for each of these questions

const
  myForm = document.forms['my-form']
, x = '1.html'
, y = '2.html'
  ; 
myForm.onsubmit = e =>
  {
  e.preventDefault(); // disable submit
  
  let val = Object.fromEntries(new FormData(myForm)); // get inputs
 
  // window.location =
  let window_location = (val.answerq === 'a' 
                      && val.answerw === 'a' 
                      && val.answere === 'a'
                        ) ? x : y ;
                    
  console.log( window_location );
  setTimeout( console.clear, 2500 );
  }
fieldset { border : none; }
<form name="my-form" >
    <fieldset>
      *ARE YOU 18+ YEARS OLD?
      <label><input type="radio" name="answerq" value="a" required> Yes</label>
      <label><input type="radio" name="answerq" value="b"> No</label>
    </fieldset>
    <fieldset>
      *ARE YOU A U.S CITIZEN?
      <label><input type="radio" name="answerw" value="a"  required> Yes</label>
      <label><input type="radio" name="answerw" value="b"> No</label>
    </fieldset>
    <fieldset>
      *ARE YOU MARRIED?
      <label><input type="radio" name="answere" value="a" required> Yes</label>
      <label><input type="radio" name="answere" value="b"> No</label>
    </fieldset>
   
    <button type="submit" class="btn btn-primary">Submit!</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

    <button type="reset"> reset </button>
  </form>

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

Ways to manage an excessive number of asynchronous calls?

As a newcomer to Node, I've learned that writing synchronous functions can negatively impact the event loop by causing it to lock up. It's generally better to write everything asynchronously. However, there are cases where using async for everyt ...

Is there a way to add an entire array of child nodes to a parent node in a single operation using JavaScript?

Is there a quick way in JavaScript to attach an array of child nodes to a parent node all at once? I'm looking for a method that will avoid triggering unnecessary repaints. So far, I attempted using parent.appendChild(arrayOfNodes), but it resulted ...

Stop an animation while it is in the hover state

Currently experimenting with CSS3 Animations to create a Panoramic view using only CSS and no JavaScript. I have managed to create a somewhat working demo: http://www.example.com/images/panoramic/ The concept is simple: when the user hovers over the blac ...

Stop the creation of new div elements once the minimum height has been reached or when text is past

Here is the HTML code I am working with: <div id='parent' align='right' dir='rtl' style=padding:0px;margin:0px;font-weight:bold;width:300px;height:auto;min-height:300px; "'<div align='right' dir='rt ...

Tool tips not displaying when the mouse is moved or hovered over

I have customized the code below to create a multi-line chart with tooltips and make the x-axis ordinal. However, the tooltips are not displaying when I hover over the data points, and I want to show the tooltips only for the data in the variable. https:/ ...

Determining the width of an element in terms of percentage

My issue involves input elements with widths set as percentages in CSS under the common class 'display-class' For example: input.test1 { width: 60% } In JavaScript, I am attempting to wrap a div around these input fields with the same width ...

Why is the type of parameter 1 not an 'HTMLFormElement', causing the failure to construct 'FormData'?

When I try to execute the code, I encounter a JavaScript error. My objective is to store the data from the form. Error Message TypeError: Failed to create 'FormData': argument 1 is not an instance of 'HTMLFormElement'. The issue arise ...

Media Queries seem to be unresponsive on Tablet and Desktop devices

I've been trying to resolve this issue for quite some time now, but I'm still unable to find a solution. My goal is to center the Wufoo Forms visually on different screen sizes using media queries, however, despite rewriting them multiple times a ...

Converting JSON object settings to a string causes an error as it is not a valid function

For my project, I have been provided with a JSON object that contains various settings, some being strings and others booleans. One thing I am struggling with is adding an animation name from the object that is stored in a variable. aniFx.move(inner, { ...

Extract information from a webpage using Selenium WebDriver

Currently, I am working on mastering Selenium, but I have hit a roadblock that I need assistance with. My task is to gather all the betting information for games from the following link and store it into an array. Given my limited experience with HTML an ...

Using Reactjs Material UI Table component results in grid expansion

I'm facing an issue with my Table component nested inside a Grid component. Whenever the Table component is rendered, it causes the Grid component to expand in width. I want the Grid component to maintain its original width when the Table component is ...

Vue.js error: Reaching maximum call stack size due to failed data passing from parent to child component

I'm having trouble passing data from a parent component to a child component. I tried using props and returning data, but with no success. The parent component is a panel component that contains the data, while the child component is a panelBody. Thi ...

Using `preventDefault()` will also block any text input from being entered

Note: I am looking for a way to clear the text box using the enter key after typing some text. My apologies for any confusion caused. Update 2: The missing event parameter was causing all the issues. I feel like a failure as a programmer. I am trying to ...

React-Leaflet continuously updates the map with the "MouseMove" event

I'm looking to implement a feature in my React app that displays the geographic coordinates as the mouse moves. However, I've noticed that using "Mousemove" causes the map to be continually redrawn with all objects each time, resulting in poor pe ...

Having trouble with adding the copy to clipboard feature

I'm having trouble implementing a copy to clipboard option on my color selector. The goal is to display the selected color on an h3 tag and create a background color generator. Each time a color is chosen, it should appear on screen for us to easily c ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

I am experiencing an issue with the checkbox in my React app where the state is not updating after it has been

I am currently building a todo app using React, but I'm encountering an issue where nothing happens when I click the checkbox. I've provided my code below: App.js import './App.css'; import React from 'react' import TodoItem ...

How does a JSONP request differ from an AJAX request?

I have searched extensively for a solution to the matter mentioned, yet I did not come across anything intriguing. Would you be able to clarify it in simple terms? ...

Unlock the secrets of recovering deleted data from a text area in Kendo UI Angular

Currently working with Kendo UI for Angular, I need to capture deleted content and remove it from another text area within the same component. My project is using Angular-13. I'm stuck on how to accomplish this task. Any suggestions would be greatly ...

In a jQuery project, WebStorm marks all $-operators as "unrecognized."

Just a quick question from a beginner: I'm facing an issue where my WebStorm IDE doesn't recognize any jQuery code, even though the webpage functions correctly in the browser. Here's what I've done so far: I have installed WebStorm V ...