2014-03-06 55 views
0

HTML發送數據作爲JavaScript數組

<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

enter image description here

我的問題

當用戶點擊 '支付' 按鈕,需要發送「data-petkey」值和「tip-line-amount」作爲數組?我怎樣才能做到這一點 ?

+0

我想你的意思JavaScript數組,對不對? –

+1

發送地點?你有什麼嘗試? –

+3

**注意:** ID必須是唯一的。 – Anton

回答

2

使用.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"] 

DEMO


如果你想如果你想有一個JSON對象{bruiser:"0.00",dog:"0.00"}使用2個獨立的陣列做

var arrDataKey = $('[data-petkey]').map(function(){ 
     return $(this).data('petkey'); 
}).get(); 

var arrLine = $('.tip-line-amount').map(function(){ 
     return this.value; 
}).get(); 

.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); 
}); 

DEMO

+0

你能告訴我如何將這個數組發送到服務器(在我的情況下,asp.net mvc),並分別提取數組內容? – Sampath

+0

感謝您的支持。:) – Sampath

0

安東的回答是真棒。但也許你真正想要做的是通過ajax發送發佈請求。 假設你形成這樣的:

<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> 

,並使用這個腳本

<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> 
相關問題