1

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.

2
  • I would think about changing your design here. You could use a combination of class and data attributes instead and then forget about the confusing names and ids. Commented Nov 21, 2012 at 18:39
  • Can't, because these might change depending on several factors, from having none, to more than one and even the id's being different. The html markup is populated from the database and I can't tell what might come from there, so I need to do this after they are rendered. Thanks anyway for the tip Cory. Commented Nov 21, 2012 at 18:53

2 Answers 2

2

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

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

2 Comments

That's the one! Great help everyone. This was really helpful.
@Mario .. Glad to have helped :)
1

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. :)

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.