tik
tik

Reputation: 135

How to calculate button counts of a HTML page?

I have a HTML page, source code is given below -

<html>
<script type="text/javascript">
function jsMeth() {
        alert('Count of buttons : '+document.getElementsByTagName('button').length);
}
</script>
<input type="button" value="button 1" id="btn1" name="btn1" /><br>
<input type="button" value="butto 2" id="btn2" name="btn2" /><br><br>
<input type="button" value="Calculate button count" id="btn3" name="btn3" onclick="jsMeth();"/>
</html>

My basic purpose is, when I click on button having id "btn3", it should display number of buttons in my HTML page (in this case 3). But somehow it is always showing 0.


Thanks for your quick reply. As all of you suggested, I have modified my code as shown below -

<html>
<script type="text/javascript">
function jsMeth() {
        alert('Count of buttons : '+document.querySelectorAll('[type=button]').length);
}
</script>
<input type="button" value="button 1" id="btn1" name="btn1" /><br>
<input type="button" value="butto 2" id="btn2" name="btn2" /><br><br>
<input type="button" value="Calculate button count" id="btn3" name="btn3" onclick="jsMeth();"/>
</html>

But now I am getting below error -

Message: Object doesn't support this property or method
Line: 4
Char: 9
Code: 0
URI: file:///C:/Documents%20and%20Settings/556996/Desktop/demohtml.html

I am testing in IE8. Please help!

Thanks, Kartic

Upvotes: 1

Views: 1962

Answers (3)

MG_Bautista
MG_Bautista

Reputation: 2653

Use this...

function jsMeth() {
        alert('Count of buttons : '+document.querySelectorAll('[type=button]').length);
}

Or this for old browsers

function jsMeth() {
    var elem = document.getElementsByTagName('input');
    var numBts = 0;
    for(i = 0; i < elem.length; i++){
        if(elem[i].getAttribute('type') === 'button'){
           numBts+=1; 
        }
    }
    alert(numBts);
}

DEMO

Upvotes: 1

Brian Nickel
Brian Nickel

Reputation: 27560

The problem you're facing is that you don't have any elements with the tag name button. All of your buttons have the tag name input.

If you aren't supporting IE7, you could use querySelectorAll to get those elements:

document.querySelectorAll('input[type=button]')

Or you could change your HTML to use <button> elements:

<button type="button" value="button 1" id="btn1" name="btn1">button 1</button>

Upvotes: 2

Explosion Pills
Explosion Pills

Reputation: 191789

Try using either of

document.getElementsByTagName('input')

or the more specific

document.querySelectorAll('[type=button'])

Upvotes: 3

Related Questions