"Using JavaScript to toggle a radio button and display specific form fields according to the selected

Currently, I am attempting to show specific fields based on the selected radio button, and it seems like I am close to the solution. However, despite my efforts, the functionality is not working as expected and no errors are being displayed.

I have defined all the necessary DOM elements, set up change event listeners, and called them accordingly. Additionally, I have set a default display property of none for a class that should work.

const intSelect = document.querySelector('#internal_form');
const extSelect = document.querySelector('#external_url');
const intForm = document.querySelector('.internal_form');
const extForm = document.querySelector('.external_form');

function show() {
  intSelect.addEventListener('change', showOne);
  extSelect.addEventListener('change', showOne);
}

let showOne = event => {
  event.preventDefault();
  showTheThings(event.currentTarget, intForm, extForm);
}

let showTheThings = (target, div) => {
  if (target.checked = true) {
    div.classList.remove('hide');
  } else {
    div.classList.add('hide');
    div.querySelectorAll('input[type="radio"]').forEach(function(el) {
      el.checked = false;
    });
  }
};
.external_form.hide,
.internal_form.hide{
display: none;
}
<form>
  <div class="form-group radio-format">
    <label>Method</label>
    <div class="col-sm-10">
      <input class="trigger form-check-input" type="radio" value="Internal Form" name="event[registration]" id="internal_form">
      <label class="form-check-label" for="internal_form">Internal Form</label>
      <input class="trigger form-check-input" type="radio" value="External URL" name="event[registration]" id="external_url">
      <label class="form-check-label" for="external_url">Internal Form</label>
    </div>
  </div>
  <div class="internal_form hide">
    <h2>Internal</h2>
  </div>
  <div class="external_form hide">
   <h2>External</h2>
  </div>
</form>

Despite my best efforts, nothing seems to be happening as intended. While testing in my browser, I noticed that changes are successfully applied when selecting the intSelect but not when clicking on extSelect (which raises some concern).

I also experimented with a more generic approach using JS:

function show(){
 if (intSelect.checked =true) {
  intForm.classList.remove('hide');
 } else {
  intForm.classList.add('hide');
 };
}

This function partially works by removing the 'hide' class, but it fails to trigger the add operation as desired.

I seem to be missing something crucial here. Any insights or assistance would be greatly appreciated.

Answer №1

This code snippet demonstrates how to toggle between two forms by utilizing IDs and adding/removing classes.

<!DOCTYPE html>
<head>
    <!-- <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> -->
    <style type="text/css">
        .external_form.hide,
.internal_form.hide{
display: none;
}
    </style>
</head>
<body >
<form>
  <div class="form-group radio-format">
    <label>Method</label>
    <div class="col-sm-10">
      <input class="trigger form-check-input" type="radio" value="Internal Form" name="event[registration]" id="internal_url">
      <label class="form-check-label" for="internal_url">Internal Form</label>
      <input class="trigger form-check-input" type="radio" value="External URL" name="event[registration]" id="external_url">
      <label class="form-check-label" for="external_url">external Form</label>
    </div>
  </div>
  <div id="internal" class="internal_form hide">
    <h2>Internal</h2>
  </div>
  <div id="external" class="external_form hide">
   <h2>External</h2>
  </div>
</form>
</body>
</html>
<script>
    var internal = document.getElementById("internal");
    var external = document.getElementById("external");

document.getElementById("internal_url").addEventListener("click", function(){
    internal.classList.remove("hide");
    external.classList.add("hide");
    console.log("internal" , internal);
});

document.getElementById("external_url").addEventListener("click", function(){
    internal.classList.add("hide");
    external.classList.remove("hide");
});


</script>

By analyzing the code above, you can easily grasp its functionality. Don't hesitate to reach out if you have any questions or need further clarification.

Answer №2

After testing your code locally, I made a few adjustments.

The first change I implemented was converting the show function into a self-calling function. This ensures that the event listener is attached to the radio buttons as soon as the page loads.

(function show() {
    intSelect.addEventListener("click", showOne);
    extSelect.addEventListener("click", showOne);
})();

Additionally, it's important to ensure that the script is loaded after the HTML DOM content by placing the script tag at the end of the body tag in the HTML document.

<body>
    <form>
        <div class="form-group radio-format">
            <label>Method</label>
            <div class="col-sm-10">
                <input class="trigger form-check-input" type="radio" value="Internal Form" name="event[registration]" id="internal_form">
                <label class="form-check-label" for="internal_form">Internal Form</label>
                <input class="trigger form-check-input" type="radio" value="External URL" name="event[registration]" id="external_url">
                <label class="form-check-label" for="external_url">External Form</label>
            </div>
        </div>
        <div class="internal_form hide">
            <h2>Internal</h2>
        </div>
        <div class="external_form hide">
            <h2>External</h2>
        </div>
    </form>
    <script src="index.js"></script>

</body>

With these changes, the updated js code looks like this:

const intSelect = document.querySelector("#internal_form");
const extSelect = document.querySelector("#external_url");
const intForm = document.querySelector(".internal_form");
const extForm = document.querySelector(".external_form");

(function show() {
    intSelect.addEventListener("click", showOne);
    extSelect.addEventListener("click", showOne);
})();

function showOne(event) {
    event.preventDefault();
    showTheThings(event.currentTarget, intForm, extForm);
}

function showTheThings(target, div) {
    if ((target.checked = true)) {
        div.classList.remove("hide");
    } else {
        div.classList.add("hide");
        div.querySelectorAll('input[type="radio"]').forEach(function(el) {
            el.checked = false;
        });
    }
}

I hope these modifications are helpful.

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

How to programmatically close a Bootstrap modal in a React-Redux application using jQuery

Hello everyone, I hope you're all doing well. I am currently working on a React application that utilizes Redux. I have run into an issue while trying to close a modal in Bootstrap programmatically. The versions I am using are Bootstrap 4 and jQuery 3 ...

A guide on retrieving values from programmatically created input elements in Java

Here's the HTML code that I am currently working with: <form method="get" action="#" id="startForm"> <input type="text" name="period" id="period" placeholder="The number of days"/> <input type="submit" name="submit" value="subm ...

Struggling to incorporate a logic in ajax using Cakephp2

I have a website built on CakePHP2 and I am looking to incorporate an Ajax function that will redirect to another URL if a specific PHP condition is met. Otherwise, it should display an error dialog. The tutorials I found on Google are quite complex for me ...

The implementation of Ajax beforeSend and complete functions is not possible at the moment

I’ve been attempting to implement a spinner image while loading ajax data, but I can't seem to get it to work. Here's my code : $.ajax({ url: '/Observer/GetInfoProfileByProfileId', type: 'POST', data: { ProfileId: ...

File reading and processing must be completed before attempting to write to a new file. This is a promise-related stipulation

Feeling completely lost and stuck in a rut. Promises seemed straightforward until I actually tried to implement them. Sharing my basic code here without any promise attempts for simplicity's sake. After taking a few months hiatus from this, I returned ...

Issue with Dynamic Image Path in Require Function: Unable to locate the relative module

I've been struggling with an error in VueJs require function for the past two days. I'm attempting to pass a prop to the Home component and then display the image. Home.vue <template> <BlogPost :post="welcomeScreen"/> <B ...

Error message: While running in JEST, the airtable code encountered a TypeError stating that it cannot read the 'bind' property of an

Encountered an error while running my Jest tests where there was an issue with importing Airtable TypeError: Cannot read property 'bind' of undefined > 1 | import AirtableAPI from 'airtable' | ^ at Object.&l ...

Vue: The function "priceFilter" is not defined in this context

function sanitizeInput(event) { event.target.value = event.target.value.replace(/[^\d.]/g, ""); event.target.value = event.target.value.replace(/^\./g, ""); event.target.value = event.target.value.replace(/\.{2,}/g, "."); event.targe ...

Is there a way for me to create a route similar to Instagram's setup, such as localhost:3000

I am looking to structure my routes similar to Instagram (instagram.com/username). Currently, I have implemented the following route: router.get('/:name', loggedin, function (req, res, next) { res.render('profile', {"Request name" ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

Struggling with adding headers in React application

When I try to include an h1 heading, either the heading doesn't show up if I comment out the buttons, or if I comment out the heading, then the buttons don't display. But when both are included, nothing is displayed. Any suggestions on how to fix ...

What is the best way to extract a JSON string from the login PHP response?

I am working on creating a basic website along with an Android application that both retrieve data from the same database. While I have no issues in dealing with Android, I am facing difficulty in handling JSON strings in HTML. How can I fetch the JSON res ...

What's the best way to incorporate mouseenter() and mouseleave() into several elements sharing the same class?

I have a vision for a fun game where players must navigate from one platform to another without falling off the edges. The game starts when you hover over the initial platform, and success is achieved by reaching the final platform. However, failure occurs ...

Tips for effectively handling unique properties of a React component (such as Redux integration and custom CSS) when sharing through NPM distribution

Question: How can custom Redux containers and CSS be effectively managed with NPM? It can be challenging to handle these custom files through traditional package distribution platforms like NPM, especially when they need to be edited in various projects. ...

Updating the default color of selected text within a webpage's content

Is there a way to modify the default blue color that appears when content is selected on a webpage? I am wondering how to change this selection color to a custom color of choice. ...

Expand or collapse Angular Material Accordion depending on selected Radio button choice

Is it possible to use a mat-accordion with radio buttons where each panel expands only when its corresponding radio button is selected? I have the radio buttons functioning correctly, but the panels are expanding and collapsing with every click rather than ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

What is the best way to retrieve the overall error status from the Material UI DataGrid?

I am currently utilizing the Material UI DataGrid element to display information from an EXCEL file. Each Excel document consists of numerous column titles with specific types assigned to them. As an example: const columns = [ { "field&quo ...

Using Typescript to create a Checkbox Grid that displays pipe-delimited values and implements a custom validation rule

I am currently working with a checkbox grid that contains pairs of AccountIds (consisting of x number of digits) and file names separated by a pipe delimiter. The file names are structured to always begin with either PRC or FE followed by a varying combin ...

Struggling to find the right strategy for obtaining real-time data while implementing customized filters

After spending a week scratching my head and experimenting with different approaches, I'm hoping to find some help here... I am working on an application that needs to provide real-time data to the client. I initially considered using Server-Sent-Eve ...