当前位置: 动力学知识库 > 问答 > 编程问答 >

Javascript on counting occurence of letter 'Z' in for loop textfield

问题描述:

Javascript on counting occurence of letter 'Z' in for loop textfield

I have like 50 text fields, user can enter up to 5 letter or number

I need a counter to count how many time did the letter "z" appear on all the text field.

I tried something like this, my textfield is with class mytext and id mytext_NUM, the textfield could be empty or with value.

var zoccur=0;

for(i=1;i<=50;i++)

{

$('.mytext').each(function () {

var value = document.getElementById("mytext_"+i).value;

zoccur = zoccur + value.match(/z/g);

})

alert("z occur is " + zoccur);

It return me z is 0zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz null null null null repeatly

网友答案:

You have a mistake.

//zoccur = zoccur + value.match(/z/g); Number + Array
zoccur = zoccur + value.match(/z/g).length;// Number + Number

Also ... your for is not closing. Are you try to do this?

var zoccur=0;
$('.mytext').each(function () {
    if(this.value.match(/z/g))
        zoccur += this.value.match(/z/g).length;
});
alert("z occur is " + zoccur);
网友答案:

I would try something like demo

var inputs = document.querySelectorAll("input");
var zOccur = [].reduce.call(inputs, function(sum, elem) {
    return sum + elem.value.match(/z/g).length;
}, 0);

alert(zOccur);

Works on HTML like this

<input value="zzzabczzz" />
<input value="zzzabczzz" />
<input value="zzzabczzz" />
<input value="zzzabczzz" />
<input value="zzzabczzz" />

Output

30

Credit to Thanasis Grammatopoulos for good way of counting Z's in an input's value

分享给朋友:
您可能感兴趣的文章:
随机阅读: