3

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

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

1 Comment

To use regex in selector see Pass Regex To JQuery Selector

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.