1

I was wanting to count the occurrences of input fields that has a class name of text where that text input contains a specific value.

document.getElementById('c_files').getElementsByClassName('text').length;

So far this counts all textboxes with the class name of text but how can i make it value specific, say if i have 50 textboxes but i only want to count the ones where the value of that textbox contains abc somewhere within the string.

Thanks.

Edit: Thank you everyone for your time and answers, i have voted you all up, but i prefer John Bupit's solution out of them all so thats the one i will accept. Thanks again.

FoxyFish
  • 874
  • 1
  • 12
  • 21

4 Answers4

2

You can iterate over the elements and see which ones have the desired value:

var elems = document.getElementById('c_files').getElementsByClassName('text');

var count = 0;
for(var i = 0; i < elems.length; i++) {
    if(elems[i].value.match(/abc/)) count++;
}
John Bupit
  • 10,406
  • 8
  • 39
  • 75
2

You can select all textboxes first and after that filter those matching your criteria. For example, by using Array.prototype.filter method:

var allText  = document.getElementById('c_files').getElementsByClassName('text'),

    filtered = [].filter.call(allText, function(textbox) {
        return textbox.value.indexOf('abc') > -1;
    });

Above code will produce and array of text elements where value contains substring "abc".

dfsq
  • 191,768
  • 25
  • 236
  • 258
1

Hi I think you need to review this SO post-

https://stackoverflow.com/a/9558906/3748701
https://stackoverflow.com/a/10095064/3748701

This is something which would help in getting your solution.

Community
  • 1
  • 1
Manik Arora
  • 4,702
  • 1
  • 25
  • 48
1

You'll need to loop over all of the text boxes with the specified class and calculate it from there.

Something like the following logic should work:

var counter = 0;
var inputElements = document.getElementById('c_files').getElementsByClassName('text').length;
for (var i = 0; i < inputElements.length; i++) {
    if (inputElements.value == "someText") {
        counter++;
    }
}
Jako Basson
  • 1,461
  • 12
  • 19