3

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.

5 Answers 5

9

You can use length:

alert($('input[name="my_textbox[]"]').length);
Sign up to request clarification or add additional context in comments.

Comments

0

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;

});

Comments

0
$('#my_textbox').length

You could also use:

$('#my_textbox').size()

which is functionally equivalent, but the former is preferred.

1 Comment

would both of them not give 1 as the count as you are referring the id
0

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.

Comments

0

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

$(document).ready( function () {

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

}); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.