t4thilina
t4thilina

Reputation: 2197

Get the length of an array using document.getElementsbyName()

Hi I have an array like this.

 var i;
 for(i=0;i<10;i++){
     $('<input/>').attr('type','text')
                 .attr('name','TxtBx_[]')
                 .attr('id','TxtBx_' + i)
                 .attr("readonly","readonly")
                 .attr('value',i)
                 .addClass('txtbx')
                 .appendTo($div);
    }     

And I prints the 10 input boxes well.

Later I need to get the number of text boxes I have created. So I'm using

var myarr=document.getElementsByName('TxtBx_');
var numberofElements=myarr.length;

but when I put an alert to check the value of numberofElements it gives me always 0. The length of the array must be 10. Could someone please let me know the mistake I have made.

Upvotes: 2

Views: 5537

Answers (6)

Jashwant
Jashwant

Reputation: 29005

Because no element has name TxtBx_ . It's TextBx[] actually.

Since you are alrady using jQuery, you can find by class like below,

$('.txtbx').length

Few other things, I would like to add here.

attr accepts a object too. So, you can pass all inputs at once. Also, you can pass attributes as second arguement while dynamically creating input. Also, according to jQuery docs, you should specify type in input type while dynamically creating them or it won't work in some IE.

So, try something like this,

var i;
for(i=0;i<10;i++) {
     $('<input type="text"/>',{
                 'name': 'TxtBx_[]',
                 'id': 'TxtBx_' + i,
                 'readonly':'readonly'
                 'value': i,
                 'class': 'txtbx'
     }).appendTo($div);  
}

Upvotes: 1

Prateek
Prateek

Reputation: 6965

var numberofElements = document.getElementsByName("TextBx[]").length;

Name of textbox is 'name','TxtBx_[]' getting by TxtBx_.

Upvotes: 1

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

Element names are TextBx[] and TxtBx_ is a class name

var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;

Read getElementsByName() documentation for more information

Upvotes: 2

Quentin
Quentin

Reputation: 943571

The elements' names are TextBx[], not TxtBx_.

var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;

Upvotes: 2

xdazz
xdazz

Reputation: 160843

Just use the class to get them:

var numberofElements = $('.txtbx').length;

Upvotes: 0

HDT
HDT

Reputation: 2047

Try it

$("input.txtbx").length;

Upvotes: 0

Related Questions