The ultimate guide to resizing a div using radio buttons!

I've managed to create a functionality that allows for showing and hiding a div based on radio button selection. However, I am facing an issue where the main div grows infinitely when the "yes" option is clicked multiple times, and shrinks to nothing when the "no" option is clicked repeatedly.

My goal is to implement a boolean variable that will control the growth of the form only once when "yes" is clicked, and the shrinkage once when "no" is clicked. Below is an example code snippet:

toggle();

function toggle() {
  var optionA = document.getElementById("yes");
  var optionB = document.getElementById("no");
  var question = document.getElementById("moreQuestions");
  var form = document.getElementById("form");
  var height = form.offsetHeight;
  var newHeight = height + 200;
  var oldHeight = height - 200;

  if (optionA.checked) {
    question.style.display = "";
    form.style.height = newHeight + 'px';
  } else if (optionB.checked) {
    form.style.height = oldHeight + 'px';
    question.style.display = "none";
  } else {
    question.style.display = "none";
  }
}
.form {
  width: 400px;
  height: 400px;
  position: relative;
  margin: 5% auto;
  background: rgba(255, 255, 240, 0.733);
  padding: 0px;
  overflow: hidden;
  border-radius: 30px;
}

.radio {
  margin-left: 18px;
  margin-top: 3px;
  font-weight: normal;
}

.select-box {
  margin-left: 18px;
  margin-top: 3px;
  margin-bottom: 3px;
}
<div class="page"></div>
<div class="form" id="form">
  <div class="radio"><label>Show More?</label><br>
    <label><input id="yes" name="radio1" type="radio"  value="yes" onclick="toggle()" required="" />Yes</label><br>
    <label><input id="no" name="radio1" type="radio" value="no" onclick="toggle()" required="" />No</label><br><br>
  </div>
  <div id="moreQuestions">
    <select class="select-box">
      <option value="0">0</option>
      <option value="0.5">0.5</option>
      <option value="1">1</option>
      <option value="1.5">1.5</option>
      <option value="2">2</option>
      <option value="2.5">2.5</option>
      <option value="3">3</option>
      <option value="3.5">3.5</option>
      <option value="4">4</option>
      <option value="4.5">4.5</option>
      <option value="5">5</option>
    </select><br><br>
  </div>
</div>

<script>
</script>

Answer №1

To accomplish this, you must switch the onclick() event to onchange(). I encountered an error while trying to replicate your code, so I created two functions to make it easier: one for adding heights and one for removing heights.

const optionA = document.getElementById('yes');
const optionB = document.getElementById('no');
const form = document.getElementById('form');
const question = document.getElementById('moreQuestions');
const expandHeight = 200;

const adding = () => {
  // Get current form height
  const formHeight = form.offsetHeight;
  question.style.display = '';
  // Set style with added height
  form.style.height = `${formHeight + expandHeight}px`;
};

const removing = () => {
  // Get current form height
  const formHeight = form.offsetHeight;
  question.style.display = 'none';
  // Set style with removed height
  form.style.height = `${formHeight - expandHeight}px`;
};

optionA.addEventListener('change', adding);
optionB.addEventListener('change', removing);
.form {
  width: 400px;
  height: 400px;
  position: relative;
  margin: 5% auto;
  background: rgba(253, 167, 141, 0.733);
  padding: 0px;
  overflow: hidden;
  border-radius: 30px;
}

.radio {
  margin-left: 18px;
  margin-top: 3px;
  font-weight: normal;
}

.select-box {
  margin-left: 18px;
  margin-top: 3px;
  margin-bottom: 3px;
}
<div class="page"></div>
<div class="form" id="form">
  <div class="radio">
    <label>Show More?</label><br />
    <label>
          <input
            id="yes"
            name="radio1"
            type="radio"
            value="yes"
            required=""
          />Yes
        </label>
    <br />
    <label>
          <input id="no" name="radio1" type="radio" value="no" required="" />No
        </label>
    <br /><br />
  </div>
  <div id="moreQuestions">
    <select class="select-box">
      <option value="0">0</option>
      <option value="0.5">0.5</option>
      <option value="1">1</option>
      <option value="1.5">1.5</option>
      <option value="2">2</option>
      <option value="2.5">2.5</option>
      <option value="3">3</option>
      <option value="3.5">3.5</option>
      <option value="4">4</option>
      <option value="4.5">4.5</option>
      <option value="5">5</option>
    </select><br /><br />
  </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

Nodeca's js-yaml now allows appending '>-' to handle extended strings with ease

With the npm package js-yaml, I am attempting to work with a .yaml file. Although I can manipulate it successfully, I encounter an issue when trying to save a long string. Actual: abvs_adas: >- c2Rhc2Rhc2Rhc2Rhc2RwaW9qbGtkZ2hqbGtzZGhmZ2psaGFzamh ...

"Enhancing Your List: A Comprehensive Guide to Editing List Items with the Power of AJAX, jQuery, and

At the moment, I am able to edit a list item by clicking the 'Edit' link. However, I would prefer to simply click on the list item itself to initiate the editing process. This is the content of my _item.html.erb partial. In this case, each proj ...

The Google Maps geocoding service fails to provide accurate location information

I am currently attempting to utilize the Google Maps Geocoding API within my JavaScript code. Below is the snippet I have written: var geocoder = new google.maps.Geocoder(); function geocodeAddress() { var address = document.getElementById("address").v ...

Retrieve information from arrays within objects in a nested structure

I am working with structured data that looks like the example below: const arr = [{ id: 0, name: 'Biomes', icon: 'mdi-image-filter-hdr', isParent: true, children: [{ id: 1, name: 'Redwood forest& ...

Tips for adjusting the item count in mat-autocomplete

For quite some time now, I've been attempting to adjust the number of items in a mat-autocomplete without any luck. My project involves using material.angular.io Below is a snippet of my code import { Component, OnInit } from '@angular/core&a ...

Deliver feedback from NodeJS Server to JavaScript on the client side

I have set up an HTTP server in NodeJS by utilizing the http.createServer(...) method. In my client-side JavaScript file, I sent a query using the POST method to the localhost URL. The server effectively received the data from the client, but now I am enco ...

Having trouble decoding invalid JSON received from the Twilio API

For the past 4 hours, I've been struggling to parse a basic JSON from Twilio. The process is as follows: A text message containing a magnet link is sent Twilio forwards the request to my serverless function in the cloud I attempt to parse the reques ...

How can I position divs in a way that the top right corner of the child div touches the bottom left corner

I am currently working on implementing a message box feature on my website. When a user clicks on the inbox icon, I want a messages box to appear, similar to how stackoverflow handles it. Stackoverflow achieves this by placing a div outside the ordered lis ...

Showing ASP code within a DIV element (inline)

Working on setting up a 'shopping cart' feature on our website, but running into some issues with the ASP code. Does anyone have any advice to offer? In the image below, you can see that when items are added to the cart, the 'total' is ...

JavaScript: Exporting and Utilizing a Function within a Model.js File

Coming from a background in PHP OOP development, I am aware that there are various methods to create classes in JavaScript. I require assistance from a JavaScript developer to resolve this particular issue. Here is the situation: I am building an AWS lamb ...

Could there be any issues with the structure of my mongoose schema?

I've been stuck for 3 hours trying to solve this problem. I can't seem to retrieve any data from my document. var mongoose = require('mongoose'); var Schema = mongoose.Schema; var accountSchema = mongoose.Schema({ username: String ...

Tips for identifying a pair of numbers (with varying ranges) in which one number must be present at all times

I am currently trying to understand the regex I have implemented in Angular 2 using Typescript: /[0-5]?[0-9]?/ Surprisingly, this regular expression works flawlessly to match any valid minute from 1 to 59, even though it seems like an empty string would ...

SignalR 2.2 application encountering communication issues with client message reception

I am facing an issue in my application where clients are not receiving messages from the Hub when a user signs in. Here is my Hub class: public class GameHub : Hub { public async Task UserLoggedIn(string userName) { aw ...

Combine Vue Plugin Styles without Using Components

Question Time To clarify, when I mention 'without component', I am referring to my plugin being a custom Vue Directive that does not rely on a template. It acts as a wrapper for a class, without the need for an additional component. However, I a ...

Identifying specific text enclosed within tags in an external file using PHP

I recently started learning about php, and I am looking for a script that can identify text between specific tags in an external file. I came across a solution here that extracts the text within tags from a given string. However, I am unsure how to mo ...

Retrieve data using $http.get when an accordion group is expanded in AngularJS

Currently, I am utilizing Angular v1.2.0rc1 along with Angular-UI Bootstrap. [edit] My objective is to implement a load-on-demand feature with caching while incorporating an accordion functionality. The accordion group that I am using can be found here. ...

Switching video sources with jQuery and HTML5 can be achieved by clicking on an

I need to develop an engaging video using HTML5 and jQuery. My objective is to: Start playing video1 Show button1 when video1 finishes, then switch to video2 upon clicking and hide button1 Play video2 Display button 2 after video2 ends, then change to vi ...

Is there a way to eliminate duplicates from an array in JavaScript by utilizing a set and placing each element in an li tag? Here is the code

const numbers = [" 4", "9", "16"," 4", "9", "16"," 4", "9", "16"] <ul> {(<li> {[...new Set(numbers)]} </li>)} </ul> const numbers = [" 4", "9", "16"," 4", "9", "16"," ...

When I zoom in, my h1 tags shift to the right

I am relatively new to this and I am puzzled as to why the text inside my h1 tag seems to shift to the right when I zoom in. Below is the CSS code: h1 { font-family: 'Raleway', sans-serif; border-bottom: 1px solid black; border-top: ...

Off Canvas left navigation menu using Bootstrap

I am working on creating a responsive layout for a webpage using Bootstrap. On larger displays, such as desktop resolutions, I want the webpage to show the header and left navigation as normal. However, when the site is resized to that of tablets or mobile ...