Is it possible to generate a dynamic list of input fields that add a new input field as you type, and remove it once the input is cleared?

As a newcomer to jQuery, I am facing a challenge in my current project where I need to implement a list of input fields with certain conditions:

  • Whenever text is entered into the first input field, another input field should be dynamically added
  • If the characters are deleted and the input field becomes empty, it should be removed
  • All the values entered should be combined into a single string at the end
  • If possible, the values should be stored in an array (optional)

Due to my limited knowledge of jQuery, I have managed to achieve the first condition but I am unsure if my solution is optimal.

http://jsfiddle.net/kubydpvr/5/

$(document).ready(() => {
  let count = 0;
  let arr = [createInput(0)];
  $(".Fields").append(arr);

  function addListField() {
    $("#id_" + count).one("input", addListField);
    $("#id_" + count).attr({
      type: "text"
    });
    arr.push(createInput(count + 1, "hidden"));
    $("#id_" + count).after(createInput(count + 1, "hidden"));
    count++;
  }

  function createInput(id, type = "text") {
    return (
      "<input type=" + type + ' value = "" id = id_' + id + " ></input>"
    );
  }
  addListField();
});
body {
  font-size: 17px;
  font-family: "Courier New", Courier, monospace;
  background: whitesmoke;
  line-height: 1.5em;
}

header {
  background: rgb(1, 60, 14);
  color: whitesmoke;
  padding: 20px;
  text-align: center;
  border-bottom: 4px rgb(26, 0, 62) solid;
  margin-bottom: 10px;
}

.container {
  margin: auto;
  padding: 10px;
  width: 200px;
}

.Fields {
  display: flex;
  flex-direction: column;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<header>
  <h1>I Learn jQuery.</h1>
  <div class="container">
    <div class="Fields"></div>
  </div>

Answer №1

Here is a possible solution for your query:

$(document).ready(() => {
  let count = 0;
  let arr = [createInput(0)];
  $(".Fields").append(arr);

  function addListField() {
    $("#id_" + count).one("input", addListField);
    $("#id_" + count).on("change", function() {
      let item = parseInt($(this).attr("id").split("_")[1]);
      if (!$(this).val().length) {
        arr.splice(item, 1)
        $(this).remove();
      }
    })
    $("#id_" + count).attr({
      type: "text"
    });
    arr.push(createInput(count + 1, "hidden"));
    $("#id_" + count).after(createInput(count + 1, "hidden"));
    count++;
  }
  $("#output").on("click", function() {
    let vals = [];
    $('[id^=id_]').each(function() {
      if ($(this).val() !== "") {
        vals.push($(this).val())
      }
      //vals += $(this).val()
    })
    console.log(vals)
    console.log(arr)
  })

  function createInput(id, type = "text") {
    return (
      "<input type=" + type + ' value = "" id = id_' + id + " ></input>"
    );
  }

  addListField();
});
body {
  font-size: 17px;
  font-family: "Courier New", Courier, monospace;
  background: whitesmoke;
  line-height: 1.5em;
}

header {
  background: rgb(1, 60, 14);
  color: whitesmoke;
  padding: 20px;
  text-align: center;
  border-bottom: 4px rgb(26, 0, 62) solid;
  margin-bottom: 10px;
}

.container {
  margin: auto;
  padding: 10px;
  width: 200px;
}

.Fields {
  display: flex;
  flex-direction: column;
}
<!DOCTYPE html>
<html>

<head>
  <title>Learn jQuery</title>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>

<body>
  <header>
    <h1>I Learn jQuery.</h1>
    <div class="container">
      <div class="Fields"></div>
    </div>
    <button id="output">
        Output
      </button>
  </header>
</body>

</html>

I trust this information proves helpful to you.

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

DIY Tooltip jQuery Plugin behaving strangely

Take a look at my code snippet: http://jsfiddle.net/w3kXj/2/ I'm working on a functionality where a checkbox input should reveal the .terms-of-use div on hover. Unfortunately, the behavior of the div is quite unpredictable. There are times when it do ...

Maintaining duplicate values in a JSON stringify operation: Tips for retention

Server responses are being received in JSON format, which may contain objects with duplicate keys. When displaying the results, I noticed that only the last value for duplicate keys was showing up. After investigating, I realized this was due to using the ...

What is the difference in speed between drawing on a transparent canvas and determining if a point is transparent compared to determining if a point is within a complex polygon?

I'm curious if anyone has done research on adding event support to a game engine. Specifically, I am working on incorporating pixel-perfect hover over 2D object event support into my own game engine. I am exploring different ways of achieving this eff ...

Issue with Google Chrome not showing stylesheets on Windows 7

Recently, I've been facing an issue with CSS layers on my website while using Google Chrome. Despite following the code accurately, my browser fails to display the expected result. To troubleshoot, I even copied and pasted code from a reliable source ...

What steps should I take to modify the jQuery find selector when I convert the name of the input form field into an array?

Currently updating some code to dynamically include form fields. Initially, it looked like this: <input name="projDesc" /> Then I used the following function to generate additional fields: function GetHtml() { var len = $('.extraProject& ...

Removing a user using Vue.js in combination with Firebase

Having trouble removing an account from Firebase in vue.js. Followed the firebase docs but it's not working as expected. Here is the button to delete: <template> [...] <div class="text-center"> <button type="button" class ...

What are some effective replacements for SoundManager2 worth considering?

While Soundmanager2 is a useful app, many find the code to be overly complex and difficult to navigate. It almost seems as if it was purposely written in a way to confuse rather than clarify. Are there any recommended alternatives to Soundmanager2 that are ...

Transferring Variables from JavaScript to PHP: A Step-by-Step Guide

I am trying to pass a variable from JavaScript to PHP. Specifically, I want to transfer the value from $('.form_datetime') in JavaScript to $TimeFrom in PHP. Despite its apparent simplicity, I have not been able to get this working yet. I do not ...

Changing the MIME type from "application/octet-stream" to "video/mp4" in HTML5: A Step-by-Step Guide

<!DOCTYPE html> <html> <head> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"> </head> <body> <video id="video" controls src="${maps.url }" height="598" width="782"> ...

Using QML to assign global properties by invoking imported JavaScript functions

Utilizing the Universal style in my QtQuick application, I am seeking to implement a ColorDialog for adjusting the accent color. My current setup looks like this: ColorDialog { id: accChooser title: "Please choose a color" onAcce ...

Can someone please provide me with the correct syntax for a jQuery AJAX PUT request that is JSON encoded?

Here is the ajax PUT request that I have written: jQuery.ajax({ url: url_lab_data+"backend/read/{\"f_anid\":"+anid+"}", type: "PUT", data: JSON.stringify({"read": 1}), ...

What is the most efficient method for exporting React components in an array format?

I've successfully implemented this code, but I'm looking for ways to enhance its clarity. I am in the process of building a compilation of SVG patterns and aim to design a dashboard that showcases each pattern similar to what you would find on t ...

Using jQuery to parse JSON data from Pylons

My pylons server is set up to handle requests in the form of "/searcher?q=blahblah". When I make a request, it returns JSON data like this: function search() { var query = $('#search_box').val(); $.getJSON('/searcher', { ...

Using Nuxt: Integrating a Third-Party Library into a Vue Page Component

Consider the scenario where you wish to integrate a third-party JavaScript library (such as Three.js) into a Vue page using Nuxt. Attempting to link local sources in the head section of either nuxt.config.js or YourPage.vue proves unsuccessful: head: { ...

The contentType property is functioning correctly for application/xml but is experiencing issues with application/json

Hello, I am reaching out here for the first time with a question. Despite searching on various platforms like Stack Overflow, I have not been able to find a definitive answer regarding what is needed for FullCalendar to properly accept a jQuery data proper ...

Loading the JS file after waiting on Lib (IronRouter) causes the HTML not to load properly

Currently, I am utilizing wait-on-lib along with IRLibLoader.load() in conjunction with Iron-Router, following the instructions provided in the tutorial found at: . My objective is to load external javascript code. Below is a snippet of my routing code: R ...

Is it a good idea to steer clear of including OAuth tokens in the

Utilizing my OAuth2 token in my API program is essential. However, I am also keen on sharing my code through GitHub. How can I securely use my confidential token without including it directly in my source code? ...

Results from Ajax without displaying the view

I have implemented a method that utilizes jQuery form for handling file uploads. After the upload process, I aim to update a specific layer on the web page. Here is the code snippet... However, there is an issue with the method being a JsonResult, and I a ...

Tips for displaying HTML tags in a chatbot using JavaScript or jQuery

I'm currently working on revamping an older chatbot project I stumbled upon online. It serves as a basic "command bot" that provides specific responses based on user input. However, the chatbot is mainly text-based and does not support rendering HTML ...

Accessing the selected list item from an unordered list in Vue.js

How can I capture the selected item from a dropdown-style list and perform operations based on that selection? In my list, each item is associated with a key for unique identification, except for 'Create New Filter'. I am seeking guidance on ho ...