Reputation: 2197
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
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
Reputation: 6965
var numberofElements = document.getElementsByName("TextBx[]").length;
Name of textbox is 'name','TxtBx_[]'
getting by TxtBx_
.
Upvotes: 1
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
Reputation: 943571
The elements' names are TextBx[]
, not TxtBx_
.
var myarr=document.getElementsByName('TextBx[]');
var numberofElements=myarr.length;
Upvotes: 2
Reputation: 160843
Just use the class to get them:
var numberofElements = $('.txtbx').length;
Upvotes: 0