簡體   English   中英

Jquery 根據復選框值獲取對象數組

[英]Jquery to get array of objects based on checkbox values

我在html中有多個復選框,當ZFC35FDC70D5FC70D5FC69D269D2698883A822C7A53EED ITED IS the Mondey It thy ys a whosect ys y shand thyecect y shand thye y a wheckeck y y a y shoseck y shoseck y shoseck y shoseck y haseck時,我需要獲取對象數組

我更喜歡使用 $.map

期望值為

[{"A": "dataA"},{"B": "dataB"}] 當 A 和 B 都被檢查時 [{"A": "dataA"}] 當只有 A 被檢查時等等

我試過了

 <:DOCTYPE html> <html> <head> <script src="https.//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function(){ $('input[type="checkbox"]').change(function() { alert($:map($("input[type='checkbox'],checked"). function(i) { var a = [] a[$(this).attr("name")] = $(this);attr("data-id"); return a })); }); }); </script> <input data-id="dataA" name="A" type="checkbox" />A <input data-id="dataB" name="B" type="checkbox" />B </head> </html>

這是使用 $().map() 而不是 $.map 的 object 數組 - 注意.get()獲取數組

 $(function() { $('input[type="checkbox"]').on("change", function() { // using function allows "this" const res = $("input[type='checkbox']:checked").map(function(i) { return { [this.name]: this.dataset.id }; }).get(); console.log(res) }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <input data-id="dataA" name="A" type="checkbox" />A <input data-id="dataB" name="B" type="checkbox" />B

這是一個 object:

 $(function() { $('input[type="checkbox"]').on("change", function() { const res = {} $("input[type='checkbox']:checked").each(function(i) { res[this.name] = this.dataset.id; }); console.log(res) }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <input data-id="dataA" name="A" type="checkbox" />A <input data-id="dataB" name="B" type="checkbox" />B

您的邏輯問題是map()返回一個數組; 您不需要在迭代處理程序中定義一個新數組並返回它。 您只需返回要從每個復選框生成的 object,如下所示:

 jQuery($ => { let $cb = $(':checkbox').on('change', () => { let checkedValues = $cb.filter(':checked').map((i, el) => ({ [el.name]: el.dataset.id })).get(); console.log(checkedValues); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <input data-id="dataA" name="A" type="checkbox" />A <input data-id="dataB" name="B" type="checkbox" />B

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM