First I hit the button Add then 'Show' and lastly Show Object
The problem is that when I hit the button Show Object I get only one object for the last input element instead one object for each input element.
How can I add new objects from inside a function without loosing most of them?
Here is the code:
$(document).ready(function() {
// body...
var tableInput = "<tr><td><input type='text'/></td><td><input type='text'/></td></tr>";
var obj = {};
const rowNo = 2;
$("h1").text("Helllo Sonq");
console.log("function called!");
$("#add").click(function() {
$("#table").append(tableInput)
})
$("#show").click(function() {
$(":text").each(function(index) {
console.log(index + ': ' + $(this).val());
var rowno = "row" + parseInt(index / rowNo)
obj[rowno] = new Object()
obj[rowno]["element" + index.toString()] = $(this).val();
// obj[rowno]["element" + index.toString()] = $(this).val();
})
})
$("#show-object").click(function() {
console.log(obj);
})
})
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="js/js.js"></script>
<h1>Hello Riko!</h1>
<button id="add">Add</button>
<button id="show">Show</button>
<button id="show-object">Show Object</button>
<table id="table">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
</table>
</body>
</html>
Into the function :
$("#show").click(function(){
$(":text").each(function(index) {
I want to add an object to the global obj for each iterated input type=text element.
var rowno = "row" + parseInt(index/rowNo)What are you trying to achieve here? you are trying to divideindexwithrowNoand assign it torowNo?index/rowNowill always beNaN.