Select items displayed next to each other with varying number of columns in HTML

Users can select a medicine for each day of their plan, with the option to choose up to 7 days. I want to dynamically show a corresponding number of Select dropdowns based on the user's selection.

body {
    width: 500px;
    margin: 0 auto;
    padding: 50px;
  }
  
  div.elem-group {
    margin: 20px 0;
  }
  
  div.elem-group.inlined {
    width: 49%;
    display: inline-block;
    float: left;
    margin-left: 1%;
  }
  
  label {
    display: block;
    font-family: 'Nanum Gothic';
    padding-bottom: 10px;
    font-size: 1.25em;
  }
  
  input, select, textarea {
    border-radius: 2px;
    border: 2px solid #777;
    box-sizing: border-box;
    font-size: 1.25em;
    font-family: 'Nanum Gothic';
    width: 100%;
    padding: 10px;
  }
  
  div.elem-group.inlined input {
    width: 95%;
    display: inline-block;
  }
  
  textarea {
    height: 250px;
  }
  
  hr {
    border: 1px dotted #ccc;
  }
  
  button {
    height: 50px;
    background: orange;
    border: none;
    color: white;
    font-size: 1.25em;
    font-family: 'Nanum Gothic';
    border-radius: 4px;
    cursor: pointer;
  }
  
  button:hover {
    border: 2px solid black;
  }

  .btn-fetch{
    width: 120%;
    padding: 14px 20px;
    margin: 8px 5px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background-color: #3498DB;
    color: white;
  
  }
    <form #datesForm = "ngForm" (ngSubmit)="checkDates(datesForm.value)">
    <div class="elem-group inlined">
      <label>First Day Of Your Plan</label>
      <input type="date" name="firstDate" required>
    </div>
    <div class="elem-group inlined">
      <label>Last Day Of Your Plan</label>
      <input type="date" name="lastDate" required>
    </div>
    <button class="btn-fetch" (click)="checkDates(datesForm.value)">Confirm Dates</button>
    <div class="elem-group" >
      <label>Select A Plan Number </label>
      <select  name="planId"  id="deviceoption" (click)="fetchPlans()" required>
          <option type=placeholder>Choose a number from the List</option>
      </select>
      <br><br>
      <select name="meds" required>
        <option value="">Choose a Medicine</option>
        <option value="medsName"></option>
    </select>
    </div>
    <button type="submit">Save the Plan</button>
</form>

If a user selects 5 days, there will be 5 instances of the "Choose Medicine" option, and if they select 7 days, there will be 7 instances. Any advice on how to achieve this dynamic functionality?

Answer №1

To achieve your desired outcome, JavaScript is required. Initially, you must determine the number of days between the two specified dates. Following this calculation, you simply need to provide options in accordance with the calculated number of days.

// Function definition to validate a date
function isValidDate(date) {
    let d = new Date(date);
    return !isNaN(d.getTime());
}

function onDateChange() {
  // Obtain input elements
  let firstDate = document.getElementById("first-date");
  let lastDate = document.getElementById("last-date");

  // Get the select element
  let medsOption = document.getElementById("meds-options");
  
  // Validate both input values as dates
  if (!isValidDate(firstDate.value) || !isValidDate(lastDate.value)) {
      return;
  }

  // Convert input values into Date objects
  let date1Object = new Date(firstDate.value);
  let date2Object = new Date(lastDate.value);

  // Calculate time difference in milliseconds
  let difference = date2Object - date1Object;

  // Convert milliseconds to days
  let days = difference / (1000 * 60 * 60 * 24);

  // Clear any existing options
  medsOption.innerHTML = "";

  // Iterate through the range of days
  for (let i = 0; i < days; i++) {
      // Create a new option element
      let option = document.createElement("option");

      // Assign value and text to the option
      option.value = i + 1;
      option.text = "Choose a Medicine";

      // Append the option to the select element
      medsOption.appendChild(option);
  }
}

let firstDate = document.getElementById("first-date");
let lastDate = document.getElementById("last-date");

// Add event listeners to the input elements
firstDate.addEventListener("change", onDateChange);
lastDate.addEventListener("change", onDateChange);
body {
    width: 500px;
    margin: 0 auto;
    padding: 50px;
  }
  
  div.elem-group {
    margin: 20px 0;
  }
  
  div.elem-group.inlined {
    width: 49%;
    display: inline-block;
    float: left;
    margin-left: 1%;
  }
  
  label {
    display: block;
    font-family: 'Nanum Gothic';
    padding-bottom: 10px;
    font-size: 1.25em;
  }
  
  input, select, textarea {
    border-radius: 2px;
    border: 2px solid #777;
    box-sizing: border-box;
    font-size: 1.25em;
    font-family: 'Nanum Gothic';
    width: 100%;
    padding: 10px;
  }
  
  div.elem-group.inlined input {
    width: 95%;
    display: inline-block;
  }
  
  textarea {
    height: 250px;
  }
  
  hr {
    border: 1px dotted #ccc;
  }
  
  button {
    height: 50px;
    background: orange;
    border: none;
    color: white;
    font-size: 1.25em;
    font-family: 'Nanum Gothic';
    border-radius: 4px;
    cursor: pointer;
  }
  
  button:hover {
    border: 2px solid black;
  }

  .btn-fetch{
    width: 120%;
    padding: 14px 20px;
    margin: 8px 5px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    background-color: #3498DB;
    color: white;
  
  }
<form #datesForm = "ngForm" (ngSubmit)="checkDates(datesForm.value)">
    <div class="elem-group inlined">
      <label>First Day Of Your Plan</label>
      <input id="first-date" type="date" name="firstDate" required>
    </div>
    <div class="elem-group inlined">
      <label>Last Day Of Your Plan</label>
      <input id="last-date" type="date" name="lastDate" required>
    </div>
    <button id="confirm-dates-button" class="btn-fetch" (click)="checkDates(datesForm.value)">Confirm Dates</button>
    <div class="elem-group" >
      <label>Select A Plan Number </label>
      <select  name="planId"  id="deviceoption" (click)="fetchPlans()" required>
          <option type=placeholder>Choose a number from the List</option>
      </select>
      <br><br>
      <select id="meds-options" name="meds" required>
        <option value="">Choose a Medicine</option>
        <option value="medsName"></option>
    </select>
    </div>
    <button type="submit">Save the Plan</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

The issue of importing images in Angular2 using TypeScript with Express is causing problems for Webpack

Having trouble importing images in my headercomponent.ts file. I believe the issue lies in how I am compiling the TypeScript with webpack ts loader, as it works fine with React (where the components are written in es6). The error occurs at: //headercompo ...

How to retrieve a stored value using Ionic 3 native storage

Hey there, I recently attempted to implement code from the Native Storage plugin documentation found at this link: Native Storage import { NativeStorage } from '@ionic-native/native-storage'; constructor(private nativeStorage: NativeStorag ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

Unable to locate the Bootstrap CSS file when deploying on PythonAnywhere

I recently created an admin panel that integrates with a database. To automate the process of generating the admin panel, I utilized flask-admin. Running the server locally on my PC displayed the bootstrap swatch correctly and everything worked seamlessly. ...

What is the procedure for assigning an element's background-color to match its class name?

Is there a way to use jQuery to make the background color of a span element match its class? $(function() { $("span").css("background-color") }); span { display: inline-block; width: 5px; height: 5px; border: solid #0a0a0a 1px; } <script src= ...

Incorporate JavaScript to enable the transfer of text from one textarea to another upon clicking a button, while simultaneously clearing the original textarea

After working on the provided code, I have managed to create a functionality where text from one textarea is copied to another textarea when a button is clicked using JavaScript. <head> <script type="text/javascript"> function displayOut(){ ...

I'm having trouble getting the gutter padding to show up in one specific content block on my Bootstrap webpage. How can I troubleshoot and resolve this

Currently, I am delving into the realm of Bootstrap 5 and have recently put together a simplistic webpage using the row/column structure suggested by Bootstrap. However, while my other columns seem to be cooperating and displaying the gutter padding as exp ...

Create a moving background gradient with styled-components

Currently, I am working on setting the background of the <Paper /> component using Material-UI version 1.0.0-beta.25 to display a gradient of colors. The colors are dynamically added by clicking the Add button and selecting one from the color picker. ...

image in the background following the header

Live Example: http://jsbin.com/opokev/54 I am currently trying to set this image as the background image while also including a header, but as you can see in the demo, the header is overlapping the image. Is there a way I can rearrange this so that the h ...

The assignment of Type Observable<Observable<any[]>> to Observable<any[]> is not valid

Working on implementing autocomplete using data from a database service: @Injectable() export class SchoolService { constructor(private db: AngularFirestore) { } getSchools(): Observable<School[]> { return this.db.collection<School> ...

Using a video as a background in HTML

My code has an issue where I have set overflow: hidden in the CSS but the video is still not displaying below the text as intended. The relevant CSS snippets are: fullscreen-bg { top: 0; right: 0; bottom: 0; left: 0; overflow:hidden ...

Stable placement in browsers using webkit technology

Having trouble with fixed positioning on webkit browsers. Works fine in Firefox, but can't seem to solve the issue. You can see the problem here: When clicking on a project, a page is loaded using jQuery's .load() function. On this page, there ...

Ways to stop the click event from being triggered in JQuery

There is a single toggle switch that, when clicked, switches ON and a popup with close and OK buttons appears. However, if the toggle is clicked again, it switches OFF and disappears. The specific requirement is that with every click where the toggle switc ...

Creating Unique Spacing in Bootstrap Using Concise Text

https://i.sstatic.net/uZ4CD.png Trying to align the bullet point text with others can be a challenge, especially when the text does not span multiple lines. The bullet point in this case is an image. Concerns html and css .description-row { margin- ...

Creating Instances of Variables Within a Class

Currently, I am working on a project using Ionic and Angular. I have come across various ways of instantiating variables and I'm unsure about the implications of each method. Here are three scenarios that confuse me: export class someClass { myVaria ...

How to retrieve information from a pre-populated <textarea> using Google Maps script in AngularJS

Is there a way to transfer data from a prefilled <textarea> that is populated by accessing the Google Maps API in a JavaScript script, into an AngularJS controller? $scope.Add=function(msg){ $log.log(msg) } <div ng-app=""> <div ng-contro ...

Angular - Implementing service worker to extract dynamic ID from route in "Notificationclick" event?

I have integrated push notifications into my code to notify users when an action is taken. The backend was developed using lib.net.webpush 3.1.0 with .net 4.5.2 in C#. The notification system is functioning well, but I am facing a challenge: Within my ser ...

Adding to a webpage's URL with PHP prior to rendering the content

Currently, I am investigating how to add a random query string at the end of a URL when someone visits my page for the first time. Let's say an individual goes to my website at www.example.com. If everything proceeds as planned, they will land on my i ...

Is it beneficial to consolidate masterdata calls into a single call?

Our application is built using REST with an Angular 2 client. We frequently make calls to master data APIs such as country and agreement during login, totaling around 6-7 calls. From a performance standpoint, would it be beneficial to consolidate these c ...

Angular2: AuthGuard malfunctioning with browser navigation controls

My AuthGuard setup works flawlessly during normal navigation within the application (see code below). Now, consider this scenario: A user goes to /content/secured-content, which requires authentication => they are redirected to /authentication/login d ...