Javascript计算具有相同值的总输入

时间:2017-12-11 04:38:58

标签: javascript

我想通过计算返回特定行业的输入数量来了解每个行业中有多少不同的用户。我想在每个行业的页面上打印总结果。

while($db_name = mysqli_fetch_row($set)){
echo '<input value="'.$companyindustry.'" name="companyindustry" type="text" />';
}
echo '<p>$companyindustry : (total_number)</p>';

结果

<input name="Animal & Pet" value="Animal & Pet" />
<input name="Animal & Pet" value="Animal & Pet" />
<input name="Engineering & Energy" value="Engineering & Energy" />

Animal & Pet = (2)
Engineering & Energy = (1)

的Javascript

<script>
function countIndustryType(){
    var arr = document.querySelectorAll('input[value=$companyindustry]');
    var total=0;
    arr.forEach(function(item){

    });

}
countIndustryType();
</script>

4 个答案:

答案 0 :(得分:0)

我的建议是为每个输入元素分配一个特定的类,以便您可以选择所需的特定输入。

var arr = {};
var els = document.getElementsByTagName('input');
for(var i = 0;i < els.length;i++) {
    if(arr[els[i].name]) {
        arr[els[i].name] += 1; 
    } else {
        arr[els[i].name] = 1;
    }
}
// Now just iterate over the keys and print the values

答案 1 :(得分:0)

UIImage
var industry_list = ['Animal & Pet','Engineering & Energy']
var industry_count_obj  = {};
function countIndustryType(){
    industry_list.forEach(function(industry){
            var arr = document.querySelectorAll('input[value="'+industry+'"]');
            var total=0;
            industry_count_obj[industry] = arr.length; 
    })
    console.log(industry_count_obj)
}
countIndustryType();

答案 2 :(得分:0)

您可以获取页面上所有输入的列表,然后按名称对其进行分组,以获取每个行业的计数:

&#13;
&#13;
const inputs = document.querySelectorAll('input');

const inputsCount = {};

inputs.forEach(i => {
  const name = i.name;
  inputsCount[name] = inputsCount[name] ?
      inputsCount[name] + 1 :
      1;
});

console.log(inputsCount);
&#13;
<input name="Animal & Pet" value="Animal & Pet" />
<input name="Animal & Pet" value="Animal & Pet" />
<input name="Engineering & Energy" value="Engineering & Energy" />
&#13;
&#13;
&#13;

答案 3 :(得分:0)

    var obj = {}
    var repeats = [];
    var vlen = document.querySelectorAll('input');

    for (x = 0; x < vlen.length; x++) {
        var l = vlen[x].value;
        obj[l] = (isNaN(obj[l]) ? 1 : obj[l] + 1);
    }
    console.log(obj)