Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 将Div id和checkbox值存储到数组(多维)Jquery中_Javascript_Jquery - Fatal编程技术网

Javascript 将Div id和checkbox值存储到数组(多维)Jquery中

Javascript 将Div id和checkbox值存储到数组(多维)Jquery中,javascript,jquery,Javascript,Jquery,我想将div ID和checked值存储到一个数组中 拨弄 假设我从品牌和ram中检查三星和联想,数组应该是: array[ ] = ["brand" => "samsung,lenovo" , "ram" => "5gb"] HTML 三星 尼康 联想 阿尔卡特 2 GB 3 GB 5 GB 6GB 请注意,div是从服务器动态抓取的。这只是一个示例,有多个div,不可能知道特定div的Id。 感谢您的帮助。 提前谢谢 var values = {}; // go thro

我想将div ID和checked值存储到一个数组中

拨弄

假设我从品牌
ram中检查
三星
联想
,数组应该是:

array[ ] = ["brand" => "samsung,lenovo" , "ram" => "5gb"]
HTML


三星
尼康
联想
阿尔卡特
2 GB
3 GB
5 GB
6GB
请注意,div是从服务器动态抓取的。这只是一个示例,有多个div,不可能知道特定div的
Id


感谢您的帮助。
提前谢谢

var values = {};

// go through each checkbox
$(':checkbox').each(function() {
    // initialize the array of values using the checkbox name/group
    values[this.name] = values[this.name] || [];

    if (this.checked)
    {
        // if the checkbox is checked, add it to the array of values
        values[this.name].push(this.value);
    }
});
本例假设您的复选框有一个
name
属性,它们应该这样做。如果它们绝对不能具有
名称
属性(而且它们确实应该),并且您绝对必须使用
div
ID,则可以使用:

// if this.name (checkbox name/group) is unavailable, use closest div's ID
var name = $(this).closest('div').attr('id');
此外,此示例将构造数组的映射,而不是字符串中逗号分隔值的映射。如果需要字符串,可以在数组上使用
.join(',)

$('[type=“button”]')。单击(函数(){
var结果=[];
$('div')。每个(函数(){
var vals=$(this).find(':checked').map(函数(){
返回$(this.val();
}).get().join(',');
结果[$(this).attr('id')]=VAL;
});
控制台日志(结果);
});

三星

尼康
联想
阿尔卡特
2 GB
3 GB
5 GB
6GB
这将创建一个数组,并根据复选框进行更新。根据你的问题,它是多维的

var arr = [];
$("input[type=checkbox]").on("change", function(){
    var $this = $(this),
    $id = $this.parent().attr("id"),
    value = $this.val();
    if(typeof arr[$id] != "object"){
        arr[$id] = [];
    }
    if($this.is(":checked")){
        arr[$id].push(value);
    }else{
        var ai = arr[$id].indexOf(value);
        arr[$id].splice(ai, 1);
    }
});
如果您需要品牌和ram为CSV(逗号分隔值),那么您可以按照@Agop的建议,使用
。join(',')
例如:

newArr['brand'] = arr['brand'].join(',');

这是一个多维数组吗?这会留下逗号。最好只使用数组和
.join(',')
@alphabett,它正在工作。您必须打开控制台才能再次看到记录的结果Thakyou。但我无法提醒数组。@Alphabett,你能用小提琴重现这个问题,以便我能提供更好的帮助吗?@Alphabett,在这种情况下,你不能使用for(i)循环,因为键不是数字而是ID。您必须使用for-in循环。谢谢你。我使用了
.join(',')
但仍然无法输出数组。
newArr['brand'] = arr['brand'].join(',');