Reputation: 133
I have a table as follows:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
// I'd like a suggestion here
});
});
</head>
<body>
<table>
<tr><th>Name</th><th>Email</th></tr>
<tr><td>abc</td><td>[email protected]</td></tr>
<tr><td>xyz</td><tr><td>[email protected]</td>
</table>
<button>click here</button>
</body>
</html>
I want after clicking that button it should create a json object conataining all data in table send it to the another url using jquery.
Upvotes: 0
Views: 3346
Reputation: 193261
You can select table rows with data and then use $.fn.map
method to extract necessary values and put them in array:
$('button').click(function() {
var data = $('table tr:gt(0)').map(function() {
return {
name: $(this.cells[0]).text(),
email: $(this.cells[1]).text()
};
}).get();
alert(JSON.stringify(data, null, 4))
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<th>Name</th>
<th>Email</th>
</tr>
<tr>
<td>abc</td>
<td>[email protected]</td>
</tr>
<tr>
<td>xyz</td>
<td>[email protected]</td>
</tr>
</table>
<button>click here</button>
Upvotes: 1