2016-08-18 33 views
0

我有一系列複選框輸入使用以下格式。如何使用jQuery .map函數獲取值和數據屬性表單輸入

<input type="checkbox" name="xyz" value="124" data-info="some info"> 

我使用jQuery來選擇檢查輸入,並試圖使用.map()函數來獲取值和數據信息,並在一個Ajax請求使用它。我可以得到像這樣的價值。

checked_options = $(button).parent().find('input:checkbox:checked').map(function() { 
     return this.value; 
    }).get(); 

但我不知道如何獲取值和數據信息並將它們作爲數組或對象返回。

回答

2

您可以使用.data()方法,如:

checked_options = $(button).parent().find('input:checkbox:checked').map(function() { 
    return this.value + ',' + $(this).data('info'); 
}).get(); 

編輯:

您可以創建一個包含價值和數據信息樣

checked_options = $(button).parent().find('input:checkbox:checked').map(function() { 
    return { 
    v: this.value, 
    d: $(this).data('info') 
    }; 
}).get(); 

console.log(checked_options); // Array of objects as result here 
+0

好,我竟是對象的數組能夠使用'$(this).attr(「data-desc」)'獲取數據,但我不想將它們串聯起來,而是作爲一個對象或數組。對不起,我不清楚。我編輯了我的問題。 – skribe

+0

我已經更新了代碼。如果結果格式正確,請檢查您的瀏覽器控制檯。 –

+1

太棒了!謝謝! – skribe