Petras99
Petras99

Reputation: 45

How to get the values of all input fields jQuery

So i have a program where it starts off with one input field, and if you press the plus button it adds new input field. I also have it so it gives the new input field a different id. I would prefer it so when i press calculate, it saves the values of all the input fields data into an array. I have tried using a for loop with .val(), but that didnt 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="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>

<!-- when this is pressed i want it to save the input fields data-->
<p id="calculate">Calculate</p>

</body>
</html>

//JavaScript

$(document).ready(function(){
	var mins = [];
	//where it add the 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");
	});
    	
	// to remove an input field
	$("#minus").click(function(){
		if(idnum >= 2){
			$("#minute" + idnum+ ", #second" + idnum).remove();
			idnum-=1;
		}
	});
    	
   	// i want it to put all of the data from the input fields in an array in that click function
	$("#calculate").click(function(){
    			
	});    	
});  
/*StyleSheet */

#append {
	display: inline-block;
}
#plusnminus {
	display: inline-block;
}
button {
	border-style: none;
	background-color: #C0C0C0;
	width: 24px;
	height: 24px;
}

Everything is inline because i'm trying to keep it a single file. I have placed comments however for readability.

Upvotes: 0

Views: 426

Answers (2)

guest271314
guest271314

Reputation: 1

You can use $.map(), selectors #append input[id^=minute], #append input[id^second] to get all input elements that are descendants of #append element; return an array containing two arrays of values, utilize destructuring assignment to set variable identifiers; for example, minutes, seconds, for arrays corresponding to .value of element where id begins with "minute" or "second"

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

  //where it add the 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");
  });

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

  // i want it to put all of the data 
  // from the input fields in an array 
  // in that click function
  $("#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;
      })]
    });
    // do stuff with `minutes`, `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>
  <!-- ************where the input fields are*******-->
  <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>

  <!-- when this is pressed i want it to save the input fields data-->
  <p id="calculate">Calculate</p>
</body>
</html>

You can alternatively substitute Array.from() for $.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;
                             });
                         });

Upvotes: 1

Soviut
Soviut

Reputation: 91525

If you wrap your input fields in a form, you can use .serialize() or .serializeArray() to serialize the whole form at once.

$(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>

Upvotes: 0

Related Questions