ipel
ipel

Reputation: 1348

Javascript get length of an array of fields with a array keys in it

I have a simple form with an array in it:

<form id='my_form'>
    <input type="text" name="my_array[1]">
    <input type="text" name="my_array[5]">
    <input type="text" name="my_array[6]">
    <input type="text" name="non_array_field">
</form>

As you can see the array keys are specified

How can I get the lenght of this array? I can use javascript or jquery

These only works if the array doesn't have keys:

document.querySelectorAll("[name='my_array[]']").length
document.formName.elements["my_array[]"].length

Upvotes: 3

Views: 97

Answers (1)

Tushar
Tushar

Reputation: 87203

Use attribute-starts with selector. To select only the elements inside form, use form selector.

[attr^=value]

Represents an element with an attribute name of attr and whose value is prefixed by "value".

document.querySelectorAll("#my_form [name^='my_array[']").length

var len = document.querySelectorAll('#my_form [name^="my_array["]').length;
console.log(len);
<form id='my_form'>
  <input type="text" name="my_array[1]">
  <input type="text" name="my_array[5]">
  <input type="text" name="my_array[6]">
  <input type="text" name="non_array_field">
</form>

Using jQuery

Docs

$("#my_form [name^='my_array[']").length

var len = $('#my_form [name^="my_array["]').length;
console.log(len);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form id='my_form'>
  <input type="text" name="my_array[1]">
  <input type="text" name="my_array[5]">
  <input type="text" name="my_array[6]">
  <input type="text" name="non_array_field">
</form>

Upvotes: 2

Related Questions