McRui
McRui

Reputation: 1955

Accessing input names with array pattern jQuery

I'm trying to access, via jQuery, the following input names in order to change their state properties based on a group of possible options. The markup is the following:

<input name="extra[00]" id="extra[00]" type="text" class="optional-field extra " value="" disabled="disabled">
<input name="extra[01]" id="extra[01]" type="text" class="optional-field extra " value="" disabled="disabled">
<input name="extra[02]" id="extra[02]" type="text" class="optional-field extra " value="" disabled="disabled">
<input name="extra[20]" id="extra[20]" type="text" class="optional-field extra " value="" disabled="disabled">
<input name="extra[21]" id="extra[21]" type="text" class="optional-field extra " value="" disabled="disabled">
<input name="extra[30]" id="extra[30]" type="text" class="optional-field extra " value="" disabled="disabled">

The first digit in name="extra[XX]" states a group and that's why it may repeat, while the second sets the order. I was trying this, but can't find a way to get the second possible element:

var id = jQuery(this).val(); // Changes from a drop-down
var extra = jQuery('input[name="extra[' + id + ']"]');

Is it possible to count how many "extra" elements are in the DOM starting, for instance by the id=2 (jQuery('input[name="extra[2*]"]')) ?

Thank in advance for any help.

Upvotes: 1

Views: 1030

Answers (2)

Felix Guo
Felix Guo

Reputation: 2708

You can use $("#container input[name=^extra]"); to select all the elements that begins with extra. Then just count the number of elements in that list. :)

Upvotes: 1

Sushanth --
Sushanth --

Reputation: 55750

Try this

$('input[name^="extra\\[2"]').length

Need to escape the [ with \\

This will give you the length of input elements that start with name="extra[2"

^ is the attribute starts with selector.

Check Fiddle

Upvotes: 2

Related Questions