Skip to content Skip to sidebar Skip to footer

Appending To An Array Depending On Amount Of Elements

here is my code currently: When there is only 1 row, the code is working correctly as the array is being outputted in the format I would like. However, when there are multiple row

Solution 1:

You will need to save the outputs into an array before printing them. See below.

<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
console.log("submitted");
var output = [];
$(".container").children("div").each(function () {
	var title = $(this).find(".line-title").val();
	var firstNum = $(this).find(".first-number-el input").val();
	var secondNum = $(this).find(".second-number-el input").val();
	output.push({
		"posx": firstNum,
		"posy": secondNum,
		"text": title
	});
});
console.log('your array is: ' + JSON.stringify(output));
}

	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>

Solution 2:

Similar to @zatopeks' but I am a bit late...

<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
	 console.log("submitted");
     var all_items = []
	 $(".container").children("div").each(function() {
       var tmp_item = {
          "text": $(this).find(".line-title").val(),
          "posx": parseFloat($(this).find(".first-number-el input").val()),
          "posy": parseFloat($(this).find(".second-number-el input").val())
       }
       all_items.push(tmp_item)
	 })
     console.log('your array is: ' + JSON.stringify(all_items));

	}
	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>

Solution 3:

Use map() to create an array of objects for each row.

Add some classes to the rows to make them easy to isolate, then map each row

const data = $('.input-row').map(function() {
  const $row = $(this)
  return {
    posx: $row.find('.pos-x').val(),
    posy: $row.find('.pos-y').val(),
    text: $row.find('.line-title').val()
  };
}).get()

console.log(data)
.as-console-wrapper {	max-height: 100%!important;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-row">
  <input class="line-title" value="Text 1">
  <input class="line-number pos-x" value="1">
  <input class="line-number pos-y" value="2">
</div>
<div class="input-row">
  <input class="line-title" value="Text 2">
  <input class="line-number pos-x" value="3">
  <input class="line-number pos-y" value="4">
</div>

Solution 4:

Look closely at what's happening in submitted(). On each loop you print that line. What you want is to print the formalities ahead of time, then just the {} objects during the loop.

Something like this, probably:

<!DOCTYPE html>
<html>
<head>

	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<script>
	$(function() {
	 $("#submitBtn").on("click", submitted);
	  $(".add-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container").append(createNewRow());
	   })
	   
	   $(".remove-row-btn").on("click", function(evt) {
	     evt.preventDefault();
	     evt.stopPropagation();
	     $(".container div").eq($(".container div").length - 1).remove();
	   })
	   
	 $('#amount').on('change', function() {
	   var containerEl = $(".container");
	   containerEl.empty();
	   var startingNumberOfLines = parseInt($("#amount").val());
	   for (var i = 0; i < startingNumberOfLines; i++) {
	     $(".container").append(createNewRow());
	   }
	 });
	 $(".add-row-btn").trigger("click");
	})


	var createNewRow = function() {
	 var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
	   .addClass("line-title");
	 var labelEl = $("<label>");
	 var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
	   .addClass("line-number");
	 var firstNumberEl = labelEl.clone();
	 firstNumberEl.text("posx: ").attr("class", "first-number-el").append(inputEl.clone());

	 var secondNumberEl = labelEl.clone();
	 secondNumberEl.text("poxy: ").attr("class", "second-number-el").append(inputEl.clone());

	 var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);

	 return newRowEl;
	}

	function submitted() {
	 console.log("submitted");
     let buffer = 'your array is: [';
	 $(".container").children("div").each(function() {
	   var title = $(this).find(".line-title").val();
	   var firstNum = $(this).find(".first-number-el input").val();
	   var secondNum = $(this).find(".second-number-el input").val();
	   buffer += '{"posx":'+ firstNum + ',"posy":' + secondNum+',"text":"'+ title +'"}';
     buffer += ']';
     console.log(buffer);
	 })

	}
	</script>
	<style>
	.line-title {
	 width: 259px;
	 margin: 0px;
	 height: 15px;
	 clear: left;
	}

	.line-number {
	 width: 45px;
	}

	.container {
	 margin: 10px;
	}
	</style>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
	</script>
	<title></title>
</head>
<body>
	<form>
		<fieldset style=" margin: 0 0 5px 0;">
			<!--<div>enter amount of text + number boxes:
      <input id="amount" step="1" style=" width: 45px;" type="number" value="1">
    </div>-->
			<div class="container"></div><button class="add-row-btn">Add row</button> <button class="remove-row-btn">Remove row</button> <input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
		</fieldset>
	</form>
</body>
</html>

Post a Comment for "Appending To An Array Depending On Amount Of Elements"