Toggle the visibility of a div and reset the input field when there is a change

In my form, I have two input fields named 'Apartment' and 'Bachelor'. Depending on the selected value, certain divs will be shown. If 'Apartment' is selected, related divs and select fields for apartments should show. The issue I'm encountering is that I can't clear the field values when selecting another option. For example, if I first select 'Apartment' and then 'Bachelor', the field value under Apartment should clear so that if I go back to selecting 'Apartment', the fields are reset to default or cleared.

<div id="residential" >
   <input type="radio" value="apartment" id="type_apartment" name="type"  >
   <label for="type_apartment" class="radio-inline"> Apartment/Flat </label>
   <input type="radio" value="bachelor" id="type_bachelor" name="type">
   <label for="type_bachelor" class="radio-inline"> Bachelor  </label>
</div>
<!-- show this when apartment select -->
<div class="form-group " id="tenant-flat">
   <select id="tenant-type" class="form-control" name="tenant">
      <option value="">Anyone</option>
      <option value="family">Family</option>
      <option value="bachelor" >Bachelor</option>
   </select>
</div>
<div class="form-group " id="flat-type">
   <div class="col-sm-12">
      <select id="" class="form-control" name="flat-type">
         <option value="">Select Flat Type</option>
         <option value="sublet" >Sublet</option>
         <option value="full-flat" >Full Flat</option>
      </select>
   </div>
</div>
<!-- show this when bachelor select -->
<div class="form-group " id="r-type">
   <div class="col-sm-12">
      <select id="room" class="form-control" name="room_type">
         <option value="">Select Room Type</option>
         <option value="seat">Seat</option>
         <option value="room" >Room</option>
      </select>
   </div>
</div>
<div class="form-group " id="tenant">
   <div class="col-sm-12">
      <select id="" class="form-control" name="tenant">
         <option value="">Select Member</option>
         <option value="family" >Family</option>
         <option value="student" >Student</option>
         <option value="job-holder" >Job Holder</option>
      </select>
   </div>
</div>
<script>
   $(document).ready(function(){
      $('#r-type').hide();
      $('#tenant').hide();
      $('#tenant-flat').hide();
       $('#flat-type').hide();
    
      $('.pretty input[type="radio"]').click(function(){
         if($(this).attr('value') == 'apartment'){
            $('#tenant-flat').show();
         }
         else{
            $('#flat-type').hide();
         }
      });
      
      var showDiv = document.getElementById("tenant-type");
      showDiv.onchange = function(){
            var hiddenDiv = document.getElementById("flat-type");
            hiddenDiv.style.display = (this.value == "family") ? "block":"none";
            var genderDiv = document.getElementById("gender");
            genderDiv.style.display = (this.value == "bachelor") ? "block":"none";
      };
   
      
   
      $('.pretty input[type="radio"]').click(function(){
         if($(this).attr('value') == 'bachelor' || $(this).attr('value') == 'sublet' || $(this).attr('value') == 'hostel' ){
            $('#r-type').show();
            $('#tenant').show();
          
            $('#tenant-type').hide();
   
         }
         else{
            $('#r-type').hide();
            $('#tenant').hide();
            $('#tenant-type').show();
           
   
         }
      });
   
   });
</script>

Answer №1

For resetting the dropdown options, you can effectively set the value of the select elements by using the selectIndex property and setting it to 0 with the following line of code:

$('.form-control').prop('selectedIndex', 0);
and within your existing code:

$(document).ready(function(){
    $('#r-type').hide();
    $('#tenant').hide();
    $('#tenant-flat').hide();
     $('#flat-type').hide();
     
     $('#residential input[type="radio"]').click(function(){
         if($(this).attr('value') == 'apartment'){
            $('#tenant-flat').show();
            $('#flat-type').show();
            $('#r-type').hide();
            $('#tenant').hide();
         }
         else{
            $('#r-type').show();
            $('#tenant').show();
            $('#flat-type').hide();
            $('#tenant-flat').hide();
         }

         $('.form-control').prop('selectedIndex', 0);
      });

    $('#tenent-type').on('change', function() {
      if($('#flat-type').val =='family') {
        $('#flat-type').show();
      } else {
        $('#flat-type').hide();
      }
      
      if($('#gender').val =='bechelor') {
        $('#gender').show();
      } else {
        $('#gender').hide();
      }
    });
 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="residential" >
   <input type="radio" value="apartment" id="type_apartment" name="type"  >
   <label for="type_apartment" class="radio-inline"> Apartment/Flat </label>
   <input type="radio" value="bachelor" id="type_bachelor" name="type">
   <label for="type_bachelor" class="radio-inline"> Bechelor  </label>
</div>
<!-- show this when apartment select -->
<div class="form-group " id="tenant-flat">
   <select id="tenant-type" class="form-control" name="tenant">
      <option value="">Anyone</option>
      <option  value="family">Family</option>
      <option value="bechelor" >Bechelor</option>
   </select>
</div>
<div class="form-group " id="flat-type">
   <div class="col-sm-12">
      <select id="" class="form-control" name="flat-type">
         <option value="">Select Flat Type</option>
         <option value="sublet" >Sublet</option>
         <option value="full-flat" >Full Flat</option>
      </select>
   </div>
</div>
<!-- show this when bechelor select -->
<div class="form-group " id="r-type">
   <div class="col-sm-12">
      <select id="room" class="form-control" name="room_type">
         <option value="">Select Room Type</option>
         <option value="seat">Seat</option>
         <option value="room" >Room</option>
      </select>
   </div>
</div>
<div class="form-group " id="tenant">
   <div class="col-sm-12">
      <select id="" class="form-control" name="tenant">
         <option value="">Select Member</option>
         <option value="family" >Family</option>
         <option value="student" >Student</option>
         <option value="job-holder" >Job Holder</option>
      </select>
   </div>
</div>

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

Tips for repositioning the color picker

Here's a straightforward example where I'm looking to adjust the location of the color picker so that it aligns with the button. function changeColor() { document.getElementById('test').click(); } <div> <h1> Colo ...

Obtaining an output from a function during an asynchronous Ajax request using the `then` method

Just started exploring these new techniques. Defining an async ajax request like this: async function makeAjaxRequest(email) { let response; try { response = await jQuery.ajax({ url: ajaxurl, type: 'POST' ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

What are the steps to setting up SystemJS with Auth0?

I am having trouble configuring SystemJS for Auth0 (angular2-jwt) and Angular 2.0.0-beta.6 as I keep encountering the following error message: GET http://localhost:3000/angular2/http 404 (Not Found)fetchTextFromURL @ system.src.js:1068(anonymous function) ...

Creating a dynamic TextField that updates on change using React JS

Hey there, I recently embarked on my React learning journey and encountered an issue while trying to dynamically pass data from a response to my TextField. It appears that the TextField is not editable as the onChange function does not seem to be working. ...

JavaScript: a single function and two calls to Document.getElementById() results in both returning "undefined"

Within my JavaScript file, I have a function that utilizes two variables: choice and courseChosen. The latter variable must be converted into an object first. In the HTML, the tags courseName and courseInfo are used for choice and courseChosen respectively ...

How can I correctly parse nested JSON stored as a string within a property using JSON.parse()?

I am having trouble decoding the response from aws secretsmanager The data I received appears as follows: { "ARN": "arn:aws:secretsmanager:us-west-2:0000:secret:token-0000", "Name": "token", "VersionId&qu ...

More efficient method for retrieving the auto-generated document ID to either create the document or update an array within the document in Firestore/Firebase

Currently, I am in the process of creating an individual document for each user to store their bookmark IDs. Utilizing addDoc allows Firebase to generate the ID for the created document. The challenge arises when trying to check if the document already exi ...

The output from the console.log consistently displays 'Incorrect login' instead of 'Successfully logged in'

After setting up a login page, I encountered an issue where entering the correct username and password in my database still resulted in 'Incorrect login' messages upon registration. Even after attempting to limit the data selected in the statemen ...

Stellar.js is malfunctioning

I've been attempting to implement a parallax effect using Stellar.js with two image tag elements, but I'm encountering issues. Despite trying various configurations, including following the Stellar.js creator's tutorial scripts closely, noth ...

Creating a secure login system with jQuery and PHP using AJAX

I'm in the process of setting up a blog-style page for my business and I'm pretty new to working with MySQL and PHP. I've managed to create this login system, but for some reason, the login is not working as expected. The code is supposed to ...

Improprove jQuery code to eliminate redundancy

Is there a better way to improve the appearance of this code? Here is a condensed snippet of the HTML: <div id="template" style="display:none;"> <div style="position:relative;"> <fieldset> <img class="sm_kont" ...

CordovaJS encountered an error due to a failed manifest merger: the minimum SDK version cannot be lower than version 19 as declared in the code

For the past 48 hours, I have been struggling to build my Cordova app for Android. Every time I attempt to open my project in Android Studio, I encounter an error during the gradle sync process in the run tasks phase: ERROR: Manifest merger failed : uses- ...

Creating multiple dynamic routes in Next.js based on specific IDs

Hey there! Currently tackling a challenge in my Nextjs project involving Events->Event->Schedule. My goal is to simply click on an event and be directed to the corresponding event details. Within the event, there should be a schedule that links to th ...

Issue with large date changes causing MUI DatePicker to freeze

The MUI DatePicker, whether from Labs or X, was functioning perfectly. However, I am now facing an issue where it hangs when trying to change the date by ten years. It appears that the code gets stuck in an endless loop, yet there are no errors displayed i ...

testing express router with several different handlers

I have been testing my guard middleware and everything appears to be functioning correctly, but my expect statement is failing. /// auth.test.js const request = require('supertest'); const express = require('express'); const app = req ...

jquery authentication issue persisting

Here is the header information to consider: Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Encoding:gzip, deflate, sdch Accept-Language:en-US,en;q=0.8 Authorization:Basic TWluZVN0YXI6TWluZVN0YXI= Cache-Contro ...

The usage of the enzyme shallow() function combined with the addition of event listeners

A specific component is causing some issues in my application: class ProblematicComponent extends Component { componentDidMount() { this.monitorForClicks(); } monitorForClicks() { this.elementRef.addEventListener('click', () => ...

Incorporating an additional CSS file into a BoilerplateJS setup

Currently, I am working on a BoilerplateJS project and looking to integrate UI components. Specifically, I am interested in adding the sample from [http://wijmo.com/wiki/index.php/Getting_Started_with_Wijmo] into a component within BoilerplateJS. Can any ...

Ways to extract all hyperlinks from a website using puppeteer

Is there a way to utilize puppeteer and a for loop to extract all links present in the source code of a website, including javascript file links? I am looking for a solution that goes beyond extracting links within html tags. This is what I have in mind: a ...