javascripthtmlgetelementbyidgetelementsbytagnamegetelementsbyclassname

javascript getelement where value contains specific string


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.


Solution

  • 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++;
    }