Discovering the data from every input field using jQuery

So, I've created a program that starts with one input field. By pressing the plus button, it adds new input fields with different IDs. When I press calculate, I want to save all the input field values into an array. I attempted using a for loop with .val() but it didn't work.

Code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <title></title>
    </head>
    <body>
<!-- ************where the input fields are*******-->
<div id="newfields">
<p style="display:inline-block; margin-bottom:0px;">
        <input type='text' class='minutes' id="minute1"/>
        <input type='text' class='vidseconds' id="second1"/>
</p>
<div id="addremove">
        <button id="plus">+</button>
        <button id="minus">-</button>
</div>
</div>

<!-- Save data when this is pressed -->
<p id="calculation">Calculate</p>

</body>
</html>

//JavaScript

$(document).ready(function(){
var mins = [];
// Add new input field
var idnum = 1;
$("#plus").click(function(){
idnum+=1;
var newInput = "<p><input type='text' class='minutes' id='minute"+idnum+"' /><input type='text' class='vidseconds'         id='second"+idnum+"'/></p>";
$(newInput).appendTo("#newfields");
});
    
// Remove an input field
$("#minus").click(function(){
if(idnum >= 2){
$("#minute" + idnum+ ", #second" + idnum).remove();
idnum-=1;
}
});
    
   // Put input field data in an array on click
$("#calculation").click(function(){
    
});    
}); 
/*StyleSheet */

#newfields {
display: inline-block;
}

#addremove {
display: inline-block;
}

button {
border-style: none;
background-color: #C0C0C0;
width: 24px;
height: 24px;
}

Everything is inline because I'm aiming to keep it as a single file. Comments have been added for readability.

Answer №1

To retrieve all input elements that are descendants of the #append element, you can utilize $.map(), selectors #append input[id^=minute], and #append input[id^second]. This will return an array containing two arrays of values. You can then use destructuring assignment to assign variable identifiers such as minutes and seconds for arrays corresponding to .value of elements where id starts with "minute" or "second"

$(document).ready(function() {
  var mins = [];

  // Add a new input field
  var idnum = 1;
  $("#plus").click(function() {
    idnum += 1;

    var input = "<p><input type='text' class='minutes' id='minute" 
                + idnum 
                + "' /><input type='text' class='vidseconds' id='second" 
                + idnum 
                + "'/></p>";
    $(input).appendTo("#append");
  });

  // Remove an input field
  $("#minus").click(function() {
    if (idnum >= 2) {
      $("#minute" + idnum + ", #second" + idnum).remove();
      idnum -= 1;
    }
  });

  // Store data from input fields in an array 
  $("#calculate").click(function() {
    var [minutes, seconds] = $.map([$("#append input[id^=minute]")]
                             , $("#append input[id^=second]")]
      , function(el) {
      return [$.map(el, function(elem) {
        return elem.value;
      })];
    });
    // Perform actions using `minutes` and `seconds` variables
    console.log("minutes:", minutes, "seconds:", seconds);
  });
});
#append {
  display: inline-block;
}
#plusnminus {
  display: inline-block;
}
button {
  border-style: none;
  background-color: #C0C0C0;
  width: 24px;
  height: 24px;
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <title></title>
</head>

<body>
  <!-- Input fields section -->
  <div id="append">
    <p style="display:inline-block; margin-bottom:0px;">
      <input type='text' class='minutes' id="minute1" />
      <input type='text' class='vidseconds' id="second1" />
    </p>

    <div id="plusnminus">
      <button id="plus">+</button>
      <button id="minus">-</button>
    </div>

  </div>

  <!-- Save input fields data when this button is clicked-->
  <p id="calculate">Calculate</p>
</body>
</html>

You can also use Array.from() instead of $.map()

var [minutes, seconds] = Array.from([$("#append input[id^=minute]")]
                                   , $("#append input[id^=second]")]
                         , function(el) {
                             return Array.from(el, function(elem) {
                               return elem.value;
                             });
                         });

Answer №2

To efficiently serialize all input fields within a form, you can utilize the .serialize() or .serializeArray() methods.

$(function() {
  $('#my-button').on('click', function() {
    var values = $('#my-form').serializeArray();
    console.log(values);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="my-form">
  <input type="text" name="input1" value="first field"><br/>
  <input type="text" name="input2" value="second field"><br/>
  <input type="text" name="input3" value="third field"><br/>
</form>

<button id="my-button">Get All Values</button>

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

Using Vue.js, learn how to target a specific clicked component and update its state accordingly

One of the challenges I'm facing is with a dropdown component that is used multiple times on a single page. Each dropdown contains various options, allowing users to select more than one option at a time. The issue arises when the page refreshes afte ...

How to properly position HTML elements and center text within paragraphs with inputs

Hello friends! I've been scouring Google and YouTube for a solution to my issue but no luck so far. This is the first time I've encountered this problem. I want to align everything in the center, which it is, but there seems to be a vertical ali ...

The external function in HTML Form's onsubmit attribute is failing to execute

My HTML Form has an onsubmit event that should call a validate() function. Everything works fine when the validate() function is inside a script tag at the end of the body tag. But if the validate() function is in an external JavaScript file, like in thi ...

Submitting values to a different page in PHP using jQuery AJAX

I am having trouble sending data to another page using jQuery AJAX and PHP. Below is the form located in page1.php: <form method="post" action="page1.php"> Name : <input type="text" id="N_Txt"> Email : <input type="text" id="Emai ...

Guide on implementing image tag and source in Django template language system

I need to include a base64 encoded image in JSON format into a Django HTML template. What is the best way to do this? <img src="R0lGODlhEAAQAMQAAORHHOVSKudfOulrSOp(Some 64 bit image);base64 /> How can I properly translate this code snippet into my ...

Invoke another component to display within a React.js application

Click here to view the code snippet. I am facing an issue with my React components. I have component A that handles fetching and rendering a list, and I also have component B that accepts user input. How can I trigger component A from component B? It seem ...

Is the iPhone height incorrect using jQuery?

When setting the viewport tag to 480px on an iPhone in portrait mode, the true dimensions of the website are as follows: 480x534px when the top bar is visible 480x594px when the top bar is hidden However, despite setting the viewport size correctly, fun ...

415 error returned from REST API during Ajax file upload operation

I have developed a basic HTML form for uploading files: <form method="post" enctype="multipart/form-data" action="#" id="upload-file"> <input id="file" class="browse-files-button" value="Browse" type="file" name="files"></input> & ...

Encountering a 'Object is not a function' issue while attempting to implement Page Object with Protractor

Whenever I attempt to run my tests, I keep encountering a TypeError: object is not a function. Prior to incorporating PageObject, everything worked fine. Below is my spec.js 'use strict'; var todoAppPage = require('../pages/angular.page&a ...

Use Jquery to smoothly scroll to the top offset of

I've been successfully utilizing jquery ScrollTo from https://github.com/balupton/jquery-scrollto, but I'm interested in incorporating the "offset top" add-on. Has anyone had experience setting this up? I'm not quite sure how to implement it ...

Seamless Exploration with Google StreetView

Google uses a special effect on StreetView images to transition smoothly between them. You can see an example of this effect in the images below, with the second image showing it being applied. My question is: How can I incorporate this same effect into m ...

Occasionally, the NodeJs server will freeze up and require a forced stop via ctrl+c to

My node.js server is set up to handle ajax requests. When I click on the webpage, an ajax call is sent and the function runs smoothly most of the time. However, there are instances where the server freezes. In some cases, using ctrl+c unfreezes it and it c ...

Guide on diverting response from an ajax request

I have a situation where I need to redirect to a page based on a response. I have successfully made an ajax call and can handle the success part. The response contains an html page, but I'm unsure of how to redirect to that page. Below is the code I ...

Is it possible to utilize Vue.js' v-if directive to validate if a certain value is present within an array

In my form, I have a checkbox and I want to be able to use v-if directly to display or hide sections based on the selected checkbox values. Can this be done using v-if, or do I need to use watch:? ...

Utilizing Javascript to export modules and call multiple functions simultaneously

Is there a way to automate the calling of all functions within a module instead of individually selecting each one? For instance: bettermovies.js module.exports={ printAvatar: function(){ console.log("Avatar"); }, printLord: funct ...

Avoid potential issues caused by cancelled asynchronous requests affecting the application's status by using the watchEffect() function

Imagine a scenario where a component receives the ID of a resource through a prop called resourceId. This component is responsible for fetching the corresponding resource from an API and displaying it, while also managing loading and error states (similar ...

Changing color of entire SVG image: a step-by-step guide

Check out this SVG image I found: https://jsfiddle.net/hey0qvgk/3/ <?xml version="1.0" encoding="utf-8"?> <!-- Generator: Adobe Illustrator 19.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1" width="90" height="9 ...

Implementing a Masonry layout within an ASP UpdatePanel

I have an ASP-WebPage where I'm using an UpdatePanel with a Dropdown and Output-Div for dynamically generated Cards. These cards are layouted by Masonry. The content of the Output-Div is bound to the Dropdown selection. Initially, the Masonry-Layout ...

Mastering the 'wing' corner effect using only CSS

Is there a way to achieve the corner effect shown in this image (top corners)? I'm not familiar with the name of this effect. If it is possible, how would you go about implementing it? Update: Some have suggested that this question is a duplicate. Ho ...

How can I transfer a JavaScript value to PHP for storage in an SQL database?

<script> var latitudeVal = document.getElementById("latitude"); var longitudeVal = document.getElementById("longitude"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); ...