This situation basically happens when we create an Array of elements that get submitted using PHP. And the input values get retrieved using $_POST variable in array format. I made an interface where I created HTML form with one textbox as telephone_no with a button Add more. When I click this button, it generates a new textbox element with the same name telephone_no. I wanted to submit them as PHP array variables, so I write the textbox element name as telephone_no[]. So the textbox elements in HTML code look like this :
<input type="text" name="telephone_no[]" id="telephone_no" />
<input type="text" name="telephone_no[]" id="telephone_no" />
<input type="text" name="telephone_no[]" id="telephone_no" />
<input type="text" name="telephone_no[]" id="telephone_no" />
<input type="text" name="telephone_no[]" id="telephone_no" />
On the backend, I made a PHP script to catch all these telephone numbers using $_POST[‘telephone_no’] array variable. But on front-end, I also wanted to calculate how many telephone numbers were added, which can be done using jQuery. But if you do it like below, it returns only 1 in place of 5 elements.
alert($('#telephone_no').length);
So I used the below code which worked perfectly.
alert($('input[name="telephone_no[]"]').length);
Leave a Reply