Automatically adjusting input box size and position in real-time

I am working on a form that includes a button and an input field. When the user clicks on the button "ADD MORE FIELDS," I want to dynamically generate a new input box. Although I have tried using code from this jsfiddle link and it works, my goal is to achieve a layout similar to this image:

https://i.stack.imgur.com/FFR7V.png

In order to position the input fields as shown in the picture: - If only one box is added in a row, its width should be set to 200px. - If two boxes are added in a row, each box should have a width of 100px. - As illustrated on the right side of the image, there should be an option to remove a box by clicking on it. After removing a box, all remaining boxes should be realigned accordingly (e.g., when box 3 is removed, box 4 takes its place, box 6 becomes smaller, and box 5 moves to the left).

Although I attempted the code provided in the following jsfiddle, I believe additional CSS and jQuery modifications are necessary:

$(document).ready(function() {
  var max_fields      = 10; //maximum input boxes allowed
  var wrapper         = $(".input_fields_wrap"); //Fields wrapper
  var add_button      = $(".add_field_button"); //Add button ID

  var x = 1; //initial text box count
  $(add_button).click(function(e){ //on add input button click
    e.preventDefault();
    if(x < max_fields){ //max input box allowed
      x++; //text box increment
      $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="remove_field">Remove</a></div>'); //add input box
    }
  });

  $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); $(this).parent('div').remove(); x--;
  })
});

Thank you!

Answer №1

TL;DR: https://jsfiddle.net/6b24z4j7/4/

In order to maintain the view order of inputs, applying some nth-child CSS logic was necessary. I made slight modifications to the jQuery while keeping your original logic intact. Check out the fiddle example where I added a placeholder attribute for demonstration purposes (which can be removed later).

CSS:

*{
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}
.form{
  width: 400px;
  max-width: 90%;
  margin: 20px auto;
  padding: 20px;
  background-color: #fff;
  border: 1px solid #e2e2e2;
  border-radius: 15px;
}
.form__actions{
  text-align: center;
}
.form__button{
  display: table;
  margin: 0 auto 15px;
  padding: 6px;
  color: #fff;
  background: #3498db;
  border: none;
  border-radius: 4px;
  cursor: pointer;

  -webkit-appereance: none;
  -moz-appereance: none;
  -ms-appereance: none;
  appereance: none;  
}
.form__row{
  margin: 0 -10px;
}
.form__row:before, .form__row:after{
  content: '';
  display: table;
  clear: both;
}
.form__field{
  float: left;
  padding: 0 10px;
  margin: 0 0 25px;
  position: relative;
}
.form__field:nth-child(2n-1){
  width: 50%;
}
.form__field:nth-child(2n){
  width: 50%;
}
.form__field:nth-child(3n){
  width: 100%;
}
.form__field:hover .form__removeField{
  opacity: 1;
}
.form__removeField{
  position: absolute;
  top: -10px;
  right: 20px;
  width: 20px;
  height: 20px;
  opacity: 0;
  background: #e74c3c;
  color: #fff;
  line-height: 20px;
  text-align: center;
  font-size: 14px;
  border-radius: 50%;
  cursor: pointer;

  -webkit-transition(all .4s ease);
  -moz-transition(all .4s ease);
  -ms-transition(all .4s ease);
  transition(all .4s ease);
}
.form__input{
  display: block;
  width: 100%;
  background: #fff;
  padding: 0 10px;
  line-height: 32px; 
  border: 1px solid #888;
  border-radius: 5px;
  -webkit-appereance: none;
  -moz-appereance: none;
  -ms-appereance: none;
  appereance: none;
} 

JS (jQuery):

$(document).ready(function() {
  var max_fields      = 10; //maximum input boxes allowed
  var wrapper         = $(".input_fields_wrap"); //Fields wrapper
  var add_button      = $(".add_field_button"); //Add button ID
    var count           = $(".input_fields_wrap").find('.form__field').length; //or write a static number if you know how many fields you will have

  $(add_button).click(function(e){ //on add input button click

    e.preventDefault(); 
    if(count < max_fields){ //max input box allowed
      count++; //text box increment
      $(wrapper).append('<div type="text" class="form__field"><input type="text" class="form__input" placeholder="'+count+'"><div class="form__removeField remove_field">x</div></div>'); //add input box
    }
  });

  $(wrapper).on("click",".remove_field", function(e){ //user click on remove text
    e.preventDefault(); 
    $(this).parent('div').remove(); 
    count--;
  })
});

HTML:

<form class="form">
  <div class="form__actions">
    <button class="form__button add_field_button">Add input</button>
  </div>
  <div class="form__row input_fields_wrap">
    <div type="text" class="form__field">
      <input type="text" class="form__input">
      <div class="form__removeField remove_field">x</div>
    </div>
    <div type="text" class="form__field">
      <input type="text" class="form__input">
      <div class="form__removeField remove_field">x</div>
    </div>
    <div type="text" class="form__field">
      <input type="text" class="form__input">
      <div class="form__removeField remove_field">x</div>
    </div>   
  </div>
</form>

I hope this helps in understanding the input creation and removal logic.

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

Error: No schema found for the specified "User" model

Attempting to establish a connection with the MongoDB database using Mongoose and defining the model resulted in the following error message: MissingSchemaError: Schema hasn't been registered for model "User" Several approaches were taken to address ...

Pressing the Enter key will result in data fetched from JSON being logged multiple times

I am currently implementing a search feature on my React website. When a user enters a keyword in the search input, the keyword is matched in a JSON file. If a match is found, it logs "yes" to the console; otherwise, nothing is logged. Here is an example ...

Iterating through a JSON object to verify the presence of a specific value

I have a JSON Object and I am looking for a way in Angular 6 to search for the value "Tennis" in the key "name". Can you provide guidance on how to achieve this? { "id":2, "name":"Sports", "url":"/sports" "children":[ { "id":1, ...

experiencing an excessive amount of rerenders when trying to utilize the

When I call the contacts function from the main return, everything seems fine. However, I encounter an error at this point: const showContacts = React.useCallback( (data: UsersQueryHookResult) => { if (data) { return ( < ...

The style from 'http://localhost:2000/cssFile/style.css' was rejected because its MIME type was 'text/html'

Currently, I am attempting to include my style.css file in the home.ejs file being rendered by express.js. However, I keep encountering the following error: Refused to apply style from 'http://localhost:2000/cssFile/style.css' because its MIME t ...

Exploring Advanced Querying Methods in Sequelize

I'm trying to display data with a gains value greater than 1, but I'm running into issues when using Postman with the following URL: http://localhost:3000/api/betHistory/winners The result I'm getting is: Executing (default): SELECT `id`, ...

Combining HTML file input with a form submission using a button of type "button", along with jQuery in the context of MVC 2.0 in Asp.net

I have a requirement in MVC 2.0 and ASP.NET where I need to upload multiple files using a partial user control view without submitting the form using an input button. The challenge is to post the form with only a button type of 'button' so that ...

A guide to setting an href using variable values in jQuery through manual methods

I have a datepicker set up where each day, month, and year is stored in a variable. I then display this information in the desired format. Below is the jQuery code: jQuery(document).ready( function($){ alert('alert function'); var txtFr ...

A step-by-step guide on deleting an element within a div using jQuery

I am attempting to delete an HTML element using JQuery like this $('#' + divId + ' .settings_class').remove('.print_settings'); This code does not result in an error or remove the specified html element, however, the selecto ...

The functionality of z-index is not applying when using position fixed

I have the following CSS code: #one{ position: fixed; top: 0; left: 0; right: 0; bottom: 0; z-index: 999; } #two{ position: relative; z-index: 9; width: 200px; height: 200px; background: red; } #link { position: ...

Data input not populating in email

After filling out the form, Gmail pops up with no data entered. How can I ensure that the information I input in the form is transferred to the email? <form class="" action="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_em ...

Achieving perfect alignment in a CSS grid for form elements vertically

One of my current projects involves creating a form layout using HTML and CSS that follows a Material Design style: <div class="form-group"> <input type="text" id="feedName" name="name" value={nameValue} onChange={this.handl ...

Finding the correct index number for the active class - a step-by-step guide

I am currently troubleshooting an issue with my demo. I am having trouble retrieving the correct index number of .carousel-item.active. Even when the second slide is displayed, I continue to receive the index of the first slide. var totalItems = $(&apos ...

Issue with updating nested child object reference in Redux state input value

I have a function in redux that updates an object with a specified path and value. The inputs on my page are based on the values in the object stored in state. Whenever the listingObj is modified in redux, I want the DOM to automatically refresh. This i ...

How can I make my navbar visible once a specific section has been reached?

Is there a way to conditionally display my navbar in react only when a specific section is reached? Currently, I am monitoring scroll position but this method becomes unreliable on larger screens due to varying scroll positions. I need the navbar to beco ...

Greek symbols do not display correctly in SQL Server when accessed through PHP

At my server database, there is a table with collation set to greek_ci_ai, but I am facing an issue where Greek characters are displaying as question marks(????). I have attempted using header("Content-Type: text/html; charset=iso-8859-7") and <meta ...

How can I implement pagination using jQuery?

I'm looking to incorporate jQuery pagination in my CodeIgniter project. After doing some research on the CodeIgniter forum and CodeIgniter AJAX Pagination Example/Guideline, I came across suggestions to check out a solution on TOHIN's blog. Howe ...

How to use jQuery to remove an empty <ul> tag

Here is the code snippet I am working with: ` <ul id="jsddm"> <li><a href="Default.aspx"> Menu</a> <ul style="visibility: hidden;" ...

The function SVGGeometryElement.isPointInFill() may not function correctly in Chromium, but it does work properly in Firefox

I'm currently working on a solution to detect when a path within an SVG file on a canvas has been clicked. The code I've written functions correctly in Firefox, but I'm encountering issues with Chromium browsers. When I surround the code wit ...

Determining the time gap in milliseconds between two specified times using the "DD/MM/YYYY HH:mm:ss:ms" format in JavaScript

I have a situation where I need to calculate the time difference between two timestamps. Starting time: "2014/10/28 11:50:28:318" Ending time: "2014/10/28 11:50:35:249" To achieve this, I utilized moment.js for the calculation. Here is my code: var msE ...