Reputation: 65988
HTML
<li id="li-tip-line">
<table>
<tbody><tr>
<td>
<label for="lblTipLine" data-petkey="dog">Dog Tip Line Amount :</label></td>
<td>
<input type="text" name="tip-line-amount" id="tip-line-amount" value="0.00" class="cls-tip-line-amount"></td>
</tr>
<tr>
<td>
<label for="lblTipLine" data-petkey="bruiser">Bruiser Tip Line Amount :</label></td>
<td>
<input type="text" name="tip-line-amount" class="tip-line-amount" value="0.00" class="cls-tip-line-amount"></td>
</tr>
</tbody></table>
</li>
UI
My Question
When user clicks the 'paid' button,need to send the "data-petkey" value and the "tip-line-amount" as an array ? How can I do that ?
Upvotes: 0
Views: 48
Reputation: 90
Anton's answer is awesome. But maybe what you really want to do is send the post request via ajax. suppose you form like this:
<form method="post" action="paid.aspx" id="payform">
<li id="li-tip-line">
<table>
<tbody><tr>
<td>
<label for="lblTipLine" data-petkey="dog">Dog Tip Line Amount :</label></td>
<td>
<input type="text" name="tip-line-amount" id="tip-line-amount" value="0.00" class="cls-tip-line-amount"></td>
</tr>
<tr>
<td>
<label for="lblTipLine" data-petkey="bruiser">Bruiser Tip Line Amount :</label></td>
<td>
<input type="text" name="tip-line-amount" class="tip-line-amount" value="0.00" class="cls-tip-line-amount"></td>
</tr>
</tbody>
</table>
</li>
</form>
and use this script
<script>
$( document ).ready(function() {
$("#payform").submit(function(e){
e.preventDefault();
$.post($("#payform").attr('action'),$("#payform").serialize())
.done(function(data) {
// handle the result from the server
alert(data);
});
});
});
</script>
Upvotes: 0
Reputation: 32591
Use .map()
var arrData = $('[data-petkey],.tip-line-amount').map(function(){
return ($(this).hasClass('tip-line-amount')?this.value:$(this).data('petkey'));
}).get();
//returns ["dog", "0.00", "bruiser", "0.00"]
If you want 2 seperate arrays do this
var arrDataKey = $('[data-petkey]').map(function(){
return $(this).data('petkey');
}).get();
var arrLine = $('.tip-line-amount').map(function(){
return this.value;
}).get();
If you want a JSON object {bruiser:"0.00",dog:"0.00"}
use .each()
$('button').click(function () {
var data = {};
$(this).closest('table').find('[data-petkey]').each(function () {
data[$(this).data('petkey')] = $(this).closest('tr').find('.tip-line-amount').val();
});
console.log(data);
});
Upvotes: 2