3

我有类似下面的数组文本框

<input type="text" name="txtname[]" value="single" />
<input type="text" name="txtname[]" value="twin" />
<input type="text" name="txtname[]" value="single" />
<input type="text" name="txtname[]" value="dulex" />
<input type="text" name="txtname[]" value="single" />

我想向...展示这些价值

单人 -------- 3
双 -------- 1 双
-------- 1

4

3 回答 3

8
var txtname = $(':input[name="txtname[]"]').map(function(a,b){ return $(b).val(); }).toArray();

var unique = {};
$.each(txtname, function(a,b){
    if (!unique[b])
        unique[b] = 0;
    unique[b]++;
});

unique最终得到:

({single:3, twin:1, dulex:1})

更新

如果您希望它作为jQuery 插件

$.fn.extend({
    unique_count: function(){
        var unique = {};
        this.each(function(a,b){
            var v = $(b).val();
            if (!unique[v])
                unique[v] = 0;
            unique[v]++;
        });
        return unique;
    },
    unique_vals: function(){
        var unique = [];
        $.each($(this).unique_count(), function(a,b){ unique.push(a); });
        return unique;
    }
});

输出是:

var $inputs = $(':input[name="txtname[]"]');
$inputs.unique_count() // = Object: {single:3, twin:1, dulex:1}
$inputs.unique_vals()  // = Array:  ["single", "twin", "duplex"]
于 2011-09-29T17:20:14.380 回答
1

查看 jquery 独有的功能:http ://api.jquery.com/jQuery.unique/

于 2011-09-29T17:17:14.417 回答
1

你可以这样说:

var all = $(":text");
var uniqueNames = jQuery.unique(all.map(function(){return $(this).attr("value"); }));
jQuery.each(uniqueNames, function(){
    console.log(this + "---" + all.filter("[value=" + this + "]").length);
});

代码是自我描述的:

  1. 找到唯一值
  2. 在原始数组中计算它们

请参阅此处的示例:http: //jsfiddle.net/BPxTd/

于 2011-09-29T17:18:13.807 回答