JavaScript form with radio buttons

I'm completely new to JavaScript and I'm attempting to create a basic script that will show one form when a radio button is checked, and another form when the second radio button is clicked (with no form displayed when neither is selected). I know my JavaScript code is likely incorrect as I have very little experience with JavaScript. I tried to use some logic and did some Googling to come up with this code, but I can't pinpoint where I made a mistake.

var ele1 = document.getElementsByClassName("form1");
var ele2 = document.getElementsByClassName("form2");

    if (document.getElementById('button1').checked)
    {
        ele1.style.display = "block";
    }

    if (document.getElementById('button2').checked)
    {
        ele2.style.display = "block";
    }
.form1 {
    display: none;
    background-color: red;
    width: 100px;
    height: 100px;
}

.form2 {
    display: none;
    background-color: blue;
    width: 100px;
    height: 100px;
}
<input type="radio" name="role" id="button1">
<input type="radio" name="role" id="button2">
<div class="form1">
</div>
<div class="form2">
</div>
<script src="/scripts/form.java"></script>

Answer №1

Although the code may not be incorrect, it currently only runs once - when the page initially loads. Ideally, you would want the forms to toggle visibility each time the inputs are altered.

To achieve this functionality, the code for toggling visibility is enclosed within a function. This function is then set as an event handler on the <input> elements so that it triggers whenever changes are made to these elements. As the selected radio button changes, either through clicking or keyboard navigation, an 'input' event will be fired on the elements, subsequently managed by the function.

Additionally, some modifications have been made:

  • Utilization of only ids as this functionality applies specifically to a few designated elements.
  • Inclusion of <form> elements for improved semantics. It is recommended for all forms to be enveloped within a <form> element at any level.
  • Replacement of .java with
    .js</code - despite their similar names, JavaScript and Java are distinct languages.</li>
    <li>Adjustment of the <code>name
    attribute on the <input> elements to better represent their purpose.
<input type="radio" name="formID" id="input1">
<input type="radio" name="formID" id="input2">

<form id="form1">
  <!-- fields -->
</form>

<form id="form2">
  <!-- fields -->
</form>

<script src="/scripts/form.js"></script>
// form.js

// Obtain references to crucial elements.
var elInput1 = document.getElementById('input1');
var elInput2 = document.getElementById('input2');
var elForm1 = document.getElementById('form1');
var elForm2 = document.getElementById('form2');

// Define an event handler function.
function updateFormVisibility(event) {
  var elSelectedInput = event.target;

  if (elSelectedInput.id === 'input1') {
    elForm1.style.display = 'block';
    elForm2.style.display = '';
  } else {
    elForm1.style.display = '';
    elForm2.style.display = 'block';
  }
}

// Register the function as a handler for any `'input'` events that take place on the
// two radio button elements.
elInput1.addEventListener('input', updateFormVisibility);
elInput2.addEventListener('input', updateFormVisibility);

Answer №2

As mentioned in a response by @Mehdi Brillaud at this link: , you have the option to experiment with JQuery using the following code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="red" data-id="a" checked> red</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="green" data-id="b"> green</label>
<label><input type="radio" class="form-switch" name="colorCheckbox" value="blue" data-id="c"> blue</label>

<div class="form form-a active"> form a </div>
<div class="form form-b"> form b </div>
<div class="form form-c"> form c</div>
.form {
  display: none;
}
.form.active {
  display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
  $('.form-switch').on('change', function() {
    $('.form').removeClass('active');
    var formToShow = '.form-' + $(this).data('id');
    $(formToShow).addClass('active');
  });
});
</script>

Answer №3

Is this what you desire?

For more recent web browsers (not the best choice):

<input type="radio" name="role" id="btn1" onchange = "setForm('formA')">
<input type="radio" name="role" id="btn2" onchange = "setForm('formB')">
<div class="formA" id ="formA" style="display:none">Form A
</div>
<div class="formB" id ="formB" style="display:none">Form B
</div>
<script src="/scripts/forms.js"></script>

Update:

Highly recommended approach:

<input type="radio" name="role" id="btn1" onchange = "displayForm('formA')">
<input type="radio" name="role" id="btn2" onchange = "displayForm('formB')">
<div class="formA" id ="formA" style="display:none">Form A
</div>
<div class="formB" id ="formB" style="display:none">Form B
</div>
<script src="/scripts/forms.js"></script>

<script>
var current = document.getElementById("formA");

function displayForm(selected_form) {
    current.style.display = "none";
    current = document.getElementById(selected_form);
    current.style.display = "block";
}
</script>

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

Incorporate duration into date using angular

In my Firebase database, I store the following information: Timestamp for the day a record was created in Firebase. Terms entered by the user at the time of creation. For instance, it may look like this: 1439612582756 // converts to: Aug 14, 2015 15 / ...

How can you check the varying font renderings on your phone?

https://i.sstatic.net/z7HcQ.png https://i.sstatic.net/1tH5d.png Having some trouble with the font display on my website. Currently using: font-family: 'Fredoka One', cursive; It's working well on PCs and desktops, but when viewed on a pho ...

Reveal the CSRF token to the client located on a separate domain

Utilizing the module https://www.npmjs.com/package/csurf to safeguard my public routes from cross-site request forgery. Due to the server and client being on separate domains, a direct method of passing the generated token to the client is not feasible. I ...

Tips on how to patiently wait until the database connection is established and all queries are successfully executed for every database specified in an array

A file containing JSON data with database details needs to execute a series of queries for each database connection. The map function is currently waiting for the database connection. Below is the start function function start() { console.log('func ...

Ensuring User Data is Current in the UI with Firebase Auth Callbacks

Below is the standard method for setting the user state to currentuser that is returned from onAuthStateChanged. I am looking for a useEffect hook that will be triggered whenever there is an update to the user's information. Unfortunately, I am unable ...

Reorganize containers without relying on bootstrap styling

Is there a method to rearrange the order of two divs without using the bootstrap library? <div class='parent'> <div class='child-1'>Abc..</div> <div class='child-2'>Xyz..</div> </div> I ...

Using a custom TypeScript wrapper for Next.js GetServerSideProps

I developed a wrapper for the SSR function GetServerSideProps to minimize redundancy. However, I am facing challenges in correctly typing it with TypeScript. Here is the wrapper: type WithSessionType = <T extends {}>( callback: GetServerSideProps&l ...

Extract the chosen document from an input within the Electron application form

Need help with this form <form> <input type="file" name="idp" id="idp" onchange="uploadFiles();"/> </form> Once a user selects an image, I want to move it to a specific folder and save its full name in a variable for database storage. ...

Decode array in JavaScript

Hello, I'm currently trying to deserialize this array in JavaScript using the PHPunserialize module: a:7:{s:13:"varPertinence";a:4:{i:0;s:5:"REGLT";i:1;s:2:"13";i:2;s:2:"15";i:3;s:2:"16";}s:10:"varSegment";N;s:12:"varSSegment1";N;s:12:"varSSegment2"; ...

In order to determine if components linked from anchor elements are visible on the screen in Next.js, a thorough examination of the components

Currently, I am in the process of developing my own single-page website using Next.js and Typescript. The site consists of two sections: one (component 1) displaying my name and three anchor elements with a 'sticky' setting for easy navigation, a ...

Error message: "Maximum width header anomaly"

I've been working on a full-width header tumblr theme and everything looks great until I resize the screen to a smaller size, like on a mobile or tablet. The header ends up cutting off and no longer maintains its full width. You can see an example of ...

Impeccable method to safeguard element from external css interference

Currently, I am working on a script that will be utilized across various pages and I want to ensure that the elements it generates are not affected by the CSS styles of those pages. Some individuals suggest using CSS like this: body>*{min-height:200px; ...

Implementing Jquery tabs into the code causes the vertical auto-scroll to smoothly glide beyond anchor points

I recently implemented a smooth autoscroll feature on my webpage using the CSS-Tricks code found here: http://css-tricks.com/snippets/jquery/smooth-scrolling/ Everything was working perfectly until I added jQuery tabs to display some of the content. Now, ...

Is it possible to implement sticky sessions with Node.js and pm2?

Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...

Uniform widths of table cells when resizing and overflowing

I am working with a table that looks like the one below: +-----+-----+-----+-----+-----+-----+ | | | | | | | +-----+-----+-----+-----+-----+-----+ | | | | | | | +-----+-----+-----+-----+-----+-----+ | | ...

Retrieve PHP variable from a PHP CSS file

I'm facing an issue where I am unable to retrieve a PHP variable from a CSS file that is loaded in this manner from my index.php: <link href="css/style.php" rel="stylesheet"> Within the style.php file, the code looks like this: <?php heade ...

JavaScript Navigation Bar Error: The value of 'undefined' is not recognized as an object

Having just started learning HTML, CSS, and JavaScript, I encountered an error message that reads: TypeError: 'undefined' is not an object. Despite my best efforts to troubleshoot the issue, I have been unable to resolve it. Is there anyone who c ...

Uncaught TypeError: Cannot create new instances of User - Node.js server not recognizing User as a constructor

I encountered an issue while attempting to save a user to MongoDB database using a post request. The error message "TypeError: User is not a constructor" keeps popping up despite the straightforward setup of my code. I have double-checked but can't se ...

Listening for a click event on a newly added element using JQuery

I am relatively new to using JQuery and I have encountered an issue with adding a click event listener for a dynamically created button. When the user clicks on the first button, my function successfully adds a second button to a div. However, I am facing ...

"Integrating Associated Models with Sequelize: A Step-by-Step Guide

I am attempting to retrieve all transactions along with their associated stripePayments, but I keep encountering the error include.model.getTableName is not a function. In my database schema, there is a table for transactions that has a one-to-many relati ...