aslamdoctor
aslamdoctor

Reputation: 3935

How to get number of elements in array of textbox using jQuery?

I have created a javascript in which when we click "Add" button, it adds textboxes with similar name, which creates a list of textboxes. The textboxes have code like below

<input type="text" name="my_textbox[]" id="my_textbox" />
<input type="text" name="my_textbox[]" id="my_textbox" />
<input type="text" name="my_textbox[]" id="my_textbox" />
<input type="text" name="my_textbox[]" id="my_textbox" />

The reason why I have given name as "my_textbox[]" is because this gets submitted to php code which then pretends these textboxes as array.

Now I would like to know the number of textboxes generate. It would be best if I can get the count through jQuery.

Thanks in advance.

Upvotes: 3

Views: 19697

Answers (5)

user369661
user369661

Reputation:

Working link http://jsfiddle.net/sameerast/5vUDZ/

$(document).ready( function () {

    var iptCount= $("input[name='my_textbox[]']").length;
    alert(iptCount)

}); 

Upvotes: 0

Jayendra
Jayendra

Reputation: 52779

This would give you the count -

alert($("input[name='my_textbox[]']").length)

you might want to change the ids of the input added making them unique.

Upvotes: 0

Siva Charan
Siva Charan

Reputation: 18064

$('#my_textbox').length

You could also use:

$('#my_textbox').size()

which is functionally equivalent, but the former is preferred.

Upvotes: 0

roselan
roselan

Reputation: 3775

first, each id shall be unique, else javascript will break.

<input type="text" name="my_textbox[]" id="my_textbox1" />
<input type="text" name="my_textbox[]" id="my_textbox2" />
<input type="text" name="my_textbox[]" id="my_textbox3" />
<input type="text" name="my_textbox[]" id="my_textbox4" />

for what you want:

$(document).ready( function () {

 var nbtextbox = $('input').length;

});

Upvotes: 0

realshadow
realshadow

Reputation: 2585

You can use length:

alert($('input[name="my_textbox[]"]').length);

Upvotes: 9

Related Questions