0

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.

5
  • How did you try to do it with the array? Maybe you had a simple typo. Commented Oct 11, 2016 at 2:59
  • Check this link:-api.jquery.com/input-selector Commented Oct 11, 2016 at 3:02
  • Petras99: dynamically created elements can't simply access with normal jquery. Try to use 'on' function in jquery. It can couple functionalities to dynamically created elements. Commented Oct 11, 2016 at 3:05
  • The code was: `var mins = []; for(var x = 0; x < idnum; x++){mins[x] = $("#minutes" + x+1).val() } @epascarrello Commented Oct 11, 2016 at 3:09
  • @JTheDev alright i'll look at the documentation for 'on' and see how it works. I'll tell you if i get it working. Commented Oct 11, 2016 at 3:22

2 Answers 2

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;
                             });
                         });
Sign up to request clarification or add additional context in comments.

8 Comments

How would i go about seeing the value of the data placed in the array of objects?
@Petras99 inputs[/* index of element in array */]["minutes"] or inputs[/* index of element in array */]["vidseconds"]. You can also set the property name to another identifier. Or, instead of returning an object, return only .value of element. Are you trying to only include input elements where id begins with minute? What is expected result?
@Petras99 Using selector to match only input elements where id begings with "minute" return .value` of element to array var inputs = $.map($("#append input[id^=minute]"), function(el) { return el.value });
@Petras99 Or, are you trying to add all the values of the input elements?
My expected result is of the values that have the id of "minute" + idnum which i believe i will be able to do with your code, and a for loop
|
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.